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
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.
Related Questions
- → Make a Laravel collection into angular array (octobercms)
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → Angularjs not working inside laravel form
- → Analysis of Flux implementations
- → how to write react component to construct HTML DOM
- → angular ng-repeat and images in a row
- → Conditional BG Color on AngularJS
- → Should I 'use strict' for every single javascript function I write?
- → getting the correct record in Angular with a json feed and passed data
- → "Undefined is not a function" at .toBe fucntion
- → angularjs data binding issue
- → Angular / JavaScript auto hydrate an instance
- → Convert generic text string in json object into valid url using Angular