Mar*_*oLe 2 unit-testing mocking jasmine angularfire2 angular
我有一个核心服务,它获取 obj 的实例firebase.auth并使用 getter 返回它。它很简单,如下所示:
export class AuthService {
...
constructor(private afAuth: AngularFireAuth,
private afs: AngularFirestore) {
...
}
public getAuthInstance(): FirebaseAuth {
return this.afAuth.auth;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个 LoginService 需要 AuthService 来登录我的应用程序。
export class LoginService {
constructor(private authService: AuthService) {
}
public login(email, password): Promise<UserCredential | string> {
return this.authService.getAuthInstance().signInWithEmailAndPassword(email, password)
.catch(() => Promise.reject('Login failed.'));
}
Run Code Online (Sandbox Code Playgroud)
也不要太复杂。但现在我想测试我的登录组件。- 特别是login方法。我无法嘲笑signInWithEmailAndPassword。我基本上尝试了一切:
jasmine.spies测试类如下所示:
...
const authStub: AuthService = jasmine.createSpyObj('AuthService', ['getAuthInstance']);
const fireStub = {
auth: {
signInWithEmailAndPassword() {
return Promise.resolve();
}
}
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{provide: AuthService, useValue: authStub},
{provide: AngularFireAuth, useValue: fireStub},
LoginService
]
});
});
const spy = it('should call signInWithPasswordAndEmail', inject([LoginService], (service: LoginService) => {
(<jasmine.Spy>authStub.getAuthInstance).and.returnValue({username: 'test'});
spyOn(fireStub.auth, 'signInWithEmailAndPassword').and.callThrough();
service.login(email, password).then(() => expect(spy).toHaveBeenCalledTimes(1));
}));
Run Code Online (Sandbox Code Playgroud)
谁能帮我让这个该死的测试变绿吗?xD^^ 错误消息。抛出的是: this.getAuthInstance().signInWithEmail.... 不是一个函数
经过一番试验和错误后,我间接模拟了AuthService测试AngularFireAuth配置AngularFireStore,如下所示:
describe('LoginService', () => {
const email: string = 'email';
const password: string = 'password';
const authStub: any = {
authState: {},
auth: {
signInWithEmailAndPassword() {
return Promise.resolve();
}
}
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{provide: AngularFireAuth, useValue: authStub},
{provide: AngularFirestore},
LoginService
]
});
authStub.authState = of(null);
});
it('should call signInWithPasswordAndEmail', inject([LoginService], (service: LoginService) => {
const mock = TestBed.get(AngularFireAuth);
const spy = spyOn(authStub.auth, 'signInWithEmailAndPassword').and.callThrough();
mock.auth = authStub.auth;
service.login(email, password);
expect(spy).toHaveBeenCalledWith(email, password);
}));
});
Run Code Online (Sandbox Code Playgroud)
它完成了工作。如果有人有更好的解决方案,我会很高兴知道。
| 归档时间: |
|
| 查看次数: |
1160 次 |
| 最近记录: |