[英]Unit Test Mock Rejected Promise in Angular2
在嘗試測試Angular2身份驗證服務( authService
)時,尤其是AngularFireAuth
提供程序,以便我可以通過監視並返回AngularFireAuth
方法的值(例如signInAnonymously
來控制和測試各種身份驗證方案。
以下是我的測試規格摘錄。 您可以看到初始的authState
是一個Observable的null —我們未經身份驗證。 然后, authService
應該嘗試進行匿名身份驗證(使用signInAnonymously
)。
在AngularFire
, signInAnonymously
方法返回一個signInAnonymously
。 我希望這被拒絕並捕獲錯誤。
這只是一次場景,但是如果我能弄清楚這一點,我可能可以解決其余的問題。
import { inject, TestBed } 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 './testing/mock-user';
import { environment } from '../../environments/environment';
let authState: MockUser;
let mockAngularFireAuth: any = {
auth: jasmine.createSpyObj('auth', [
'signInAnonymously',
'signInWithPopup',
'signOut'
]),
authState: Observable.of(null)
};
let service: AuthService;
fdescribe('AuthService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: AngularFireAuth, useValue: mockAngularFireAuth },
{ provide: AuthService, useClass: AuthService }
]
});
});
beforeEach(inject([ AuthService ], (authService: AuthService) => {
service = authService;
}));
// TODO: Test `authState` is `null` and throw
describe('when we can’t authenticate', () => {
it('should thow', () => {
mockAngularFireAuth.auth.signInAnonymously.and.returnValue(() => {
return new Promise((resolve, reject) => {
reject('fooBar');
});
});
});
});
});
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) => {
console.log(1, authState);
if (authState === null) {
console.log(2, authState);
this.afAuth.auth.signInAnonymously()
.then((authState) => {
console.log(3, authState);
this.authState = authState;
})
.catch((error) => {
console.log(4, error.message);
throw new Error(error.message);
});
} else {
console.log(5, authState);
this.authState = authState;
}
}, (error) => {
console.log(6, error.message);
throw new Error(error.message);
});
}
}
我收到的錯誤是Cannot read property 'then' of undefined
auth.service.ts
中第21:11行Cannot read property 'then' of undefined
; 就像您期望的那樣, .then((authState) => {...
行。
AuthService
之前實例化signInAnonymously
。
相反,它可以是
describe('when we can’t authenticate', () => {
beforeEach(() => {
mockAngularFireAuth.auth.signInAnonymously.and.returnValue(Promise.reject('fooBar'));
});
it('...', inject([ AuthService ], (authService: AuthService) => {
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.