In my Angular2 app which uses AngularFire2, I have an AuthService
which tries to authenticate anonymously with Firebase.
I am trying to write a test that expects AngularFireAuth
's signInAnonymously
to return a rejected promise; for authState
to be null
and an error to be thrown.
I an new to Jasmine and testing in general but I think I may need to be using asynchronous tests but I'm getting quite stuck.
Here is a simplified AuthService
:
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class AuthService {
private authState: firebase.User;
constructor(private afAuth: AngularFireAuth) { this.init(); }
private init (): void {
this.afAuth.authState.subscribe((authState: firebase.User) => {
if (authState === null) {
this.afAuth.auth.signInAnonymously()
.then((authState) => {
this.authState = authState;
})
.catch((error) => {
throw new Error(error.message);
});
} else {
this.authState = authState;
}
}, (error) => {
throw new Error(error.message);
});
}
}
And here are my test specs:
import { TestBed, inject } from '@angular/core/testing';
import { AngularFireAuth } from 'angularfire2/auth';
import 'rxjs/add/observable/of';
import { Observable } from 'rxjs/Rx';
import { AuthService } from './auth.service';
import { environment } from '../environments/environment';
describe('AuthService', () => {
const mockAngularFireAuth: any = {
auth: jasmine.createSpyObj('auth', {
'signInAnonymously': Promise.resolve('foo'),
// 'signInWithPopup': Promise.reject(),
// 'signOut': Promise.reject()
}),
authState: Observable.of(null)
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: AngularFireAuth, useValue: mockAngularFireAuth },
{ provide: AuthService, useClass: AuthService }
]
});
});
it('should be created', inject([ AuthService ], (service: AuthService) => {
expect(service).toBeTruthy();
}));
//
//
//
//
//
describe('when we can’t authenticate', () => {
beforeEach(() => {
mockAngularFireAuth.auth.signInAnonymously.and.returnValue(Promise.reject('bar'));
});
it('should thow', inject([ AuthService ], (service: AuthService) => {
expect(mockAngularFireAuth.auth.signInAnonymously).toThrow();
}));
});
//
//
//
//
//
});
Thank you for your help!
It turns out I was mocking
mockAngularFireAuth
correctly. I needed to rejectmockAngularFireAuth.auth signInAnonymously()
's promise with an error and expect it to be caught, a la:I solved this problem by doing the following: