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 ex
I solved this problem by doing the following:
describe('should reject promise', () => {
let resolved: boolean;
let rejected: boolean;
let _e: any;
beforeEach(function (done) {
resolved = false;
rejected = false;
// ensure conditions here are such that myFn() should return a rejected promise
service.myFn().then(() => {
resolved = true;
done();
}).catch((e) => {
rejected = true;
_e = e;
done();
});
})
it('should reject', () => {
expect(resolved).toEqual(false);
expect(rejected).toEqual(true);
expect(_e.name).toEqual("MyCustomErrorName");
});
});
It turns out I was mocking mockAngularFireAuth
correctly. I needed to reject mockAngularFireAuth.auth signInAnonymously()
's promise with an error and expect it to be caught, a la:
import { TestBed, async, 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 { MockUser} from './mock-user';
import { environment } from '../environments/environment';
describe('AuthService', () => {
// An anonymous user
const authState: MockUser = {
displayName: null,
isAnonymous: true,
uid: '17WvU2Vj58SnTz8v7EqyYYb0WRc2'
};
const mockAngularFireAuth: any = {
auth: jasmine.createSpyObj('auth', {
'signInAnonymously': Promise.reject({
code: 'auth/operation-not-allowed'
}),
// 'signInWithPopup': Promise.reject(),
// 'signOut': Promise.reject()
}),
authState: Observable.of(authState)
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: AngularFireAuth, useValue: mockAngularFireAuth },
{ provide: AuthService, useClass: AuthService }
]
});
});
it('should be created', inject([ AuthService ], (service: AuthService) => {
expect(service).toBeTruthy();
}));
describe('can authenticate anonymously', () => {
describe('AngularFireAuth.auth.signInAnonymously()', () => {
it('should return a resolved promise', () => {
mockAngularFireAuth.auth.signInAnonymously()
.then((data: MockUser) => {
expect(data).toEqual(authState);
});
});
});
});
describe('can’t authenticate anonymously', () => {
describe('AngularFireAuth.auth.signInAnonymously()', () => {
it('should return a rejected promise', () => {
mockAngularFireAuth.auth.signInAnonymously()
.catch((error: { code: string }) => {
expect(error.code).toEqual('auth/operation-not-allowed');
});
});
});
});
…
});