Ad

Unit Testing Angular Service That Uses Firebase Auth?

I've setup simple authentication service on angular that returns a Promise:

import * as firebase from 'firebase/app';

@Injectable({
    providedIn: 'root'
})

export class AuthService {

  doLogin(val:{email:string, password:string}) {
  return new Promise<any>((resolve, reject) => {
    firebase
      .auth()
      .signInWithEmailAndPassword(val.email, val.password)
      .then(
        res => resolve(res),
        err => reject(err)
      );
    });
  }

}

How do I properly implement unit testing on the service? The way I currently achieve this to do unit testing using jasmine, by providing real user credential (which is not a good thing, as I'm going to push the code to github) and calling the doLogin method directly using the credential.

describe('AuthService', () => {
let service: AuthService;
const userCreds = {
    email: '[email protected]',
    password: 'somerealpassword'
};

beforeEach(() => TestBed.configureTestingModule({
    imports: [FirebaseModule],
    providers: [AuthService]
}));

beforeEach(() => {
    service = TestBed.get(AuthService);
});

it('should logged in', async((done) => {
    service.doLogin(userCreds).then(
        res => {
            expect(res).toBeTruthy();
        }
    )
}));

Sorry if the code is mess, I'm totally new on both angular and jasmine, any advice or idea is greatly appreciated, thanks

Ad

Answer

I would strongly suggest you refactor your code to use dependency injection. See the docs here.

You would then inject Firebase as an external dependency, which will make it much easier to mock and therefore much easier to test. See examples on how to do this with Firebase in The official Angular library for Firebase

Once you have done this, then you can test it in a fairly straightforward way. Here is an example in Stackblitz of testing a firebase service.

Ad
source: stackoverflow.com
Ad