Firebase auth unit testing error No Firebase App

2,203

Have a look at how they tested directly in firebase_auth code : https://github.com/FirebaseExtended/flutterfire/tree/master/packages/firebase_auth/firebase_auth/test

Call the setupFirebaseAuthMocks (you can adapt the code from here) method at the beginning of your main method and call await Firebase.initializeApp(); in a setUpAll method.

Share:
2,203
Rahul sharma
Author by

Rahul sharma

I'm full time Android and Flutter Developer. No one is perfect so do i . But I'm Good learner. Don't remember every single line of code. Just remember technique.

Updated on December 23, 2022

Comments

  • Rahul sharma
    Rahul sharma over 1 year

    I'm trying to test my firebase auth methods. Auth methods are signin, signout , register, etc. this are methods i want to perform unit test.

    I'm getting error No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

    I tried to initialize Firebase.initializeApp in test main method its also doesn't work.

     class MockUserRepository extends Mock implements AuthService {
      final MockFirebaseAuth auth;
      MockUserRepository({this.auth});
     }
     class MockFirebaseAuth extends Mock implements FirebaseAuth{}
     class MockFirebaseUser extends Mock implements FirebaseUser{}
     class MockFirebase extends Mock implements Firebase{}
     void main() {
       MockFirebase firebase=MockFirebase();
       MockFirebaseAuth _auth = MockFirebaseAuth();
       BehaviorSubject<MockFirebaseUser> _user = BehaviorSubject<MockFirebaseUser>();
       when(_auth.onAuthStateChanged).thenAnswer((_){
          return _user;
         });
       AuthService _repo = AuthService.instance(auth: _auth);
       group('user repository test', (){
           when(_auth.signInWithEmailAndPassword(email: "email",password: "password")).thenAnswer((_)async{
      _user.add(MockFirebaseUser());
    });
    when(_auth.signInWithEmailAndPassword(email: "mail",password: "pass")).thenThrow((){
      return null;
    });
    test("sign in with email and password", () async {
      var signedIn = await _repo.onLogin(email:"[email protected]",password: "123456");
      expect(signedIn, isNotNull);
      expect(_repo.status, Status.Authenticated);
    });
    
    test("sing in fails with incorrect email and password",() async {
      var signedIn = await _repo.onLogin(email:"[email protected]",password: "666666");
      expect(signedIn, false);
      expect(_repo.status, Status.Unauthenticated);
    });
    
    test('sign out', ()async{
      await _repo.signout();
      expect(_repo.status, Status.Unauthenticated);
     });
    });
    } 
    

    AuthService class

        enum Status { Uninitialized, Authenticated, Authenticating, 
        Unauthenticated }
    
       class AuthService with ChangeNotifier {
         FirebaseAuth auth = FirebaseAuth.instance;
         FirebaseUser _user;
    
        FirebaseUser get user => _user;
    
        set user(FirebaseUser value) {
          _user = value;
        }
    
        Status _status = Status.Uninitialized;
    
        Future<User> getCurrentUser() async {
          User currentUser;
          await FirebaseAuth.instance.authStateChanges().listen((User user) {
          currentUser = user;
          });
          return currentUser;
         }
        AuthService();
        AuthService.instance({this.auth}) {
           //    auth.onAuthStateChanged.listen((user) {
          //      onAuthStateChanged(user);
          //    });
          }
    
         Future<void> signout() async {
         await auth.signOut();
           }
    
         Future<User> createAccount({String email, String password}) async {
            try {
               UserCredential userCredential = await 
                      auth.createUserWithEmailAndPassword(
                 email: email, password: password);
                return userCredential != null ? userCredential.user : null;
              } on FirebaseAuthException catch (e) {
               showToast(e.message);
              } catch (e) {
              log(e.toString());
               return null;
              }
           }
    
         Future<User> onLogin({String email, String password}) async {
          try {
            User user;
               await auth
            .signInWithEmailAndPassword(email: email, password: password)
          .then((value) {
            showToast("Login sucessful");
           user = value != null ? value.user : null;
          });
          return user;
         } on FirebaseAuthException catch (e) {
          showToast(e.message);
         }
        }
    
        sendResetPassword({String email}) async {
          bool isSent = false;
          try {
             await auth.sendPasswordResetEmail(email: email).then((value) {
               showToast("Reset password email sent");
                isSent = true;
            });
            return isSent;
           } on FirebaseAuthException catch (e) {
               showToast(e.message);
        }
      }
    
        Future<void> onAuthStateChanged(FirebaseUser user) async {
         if (user == null) {
           _status = Status.Unauthenticated;
            } else {
            _user = user;
            _status = Status.Authenticated;
           }
           notifyListeners();
         }
    
         Status get status => _status;
    
         set status(Status value) {
            _status = value;
            }
       }
    
  • Rahul sharma
    Rahul sharma over 3 years
    I have tried to Firebase.initializeApp() in my test file its also didn't work.
  • dgilperez
    dgilperez over 3 years
    Great stuff, thanks. Just for clarification, you can pick the mock_auth.dart file over there and bring it to your test suite and use it.
  • masus04
    masus04 about 2 years
    Great answer, ty. Is there any way we can import this file from dependencies? I can't find it in the packages from pub.dev.