【发布时间】:2017-08-29 03:15:14
【问题描述】:
我正在尝试为 angular2 中的身份验证服务上的登录方法编写单元测试。我面临的问题是 Observable.subscribe 是异步的,并且没有在我的测试中运行,因此 localStorage.setItem 永远不会运行。我试图让我的代码返回一个承诺并使用 jasmine,但这似乎也不起作用。我应该如何测试这个功能?
来自身份验证服务的代码
login(username: string, password: string) {
const url = environment.apiUrl;
this._http.post(`https://${url}/authenticate`, {username, password})
.map(res => res.json())
.subscribe(
data => localStorage.setItem('id_token', data.id_token),
error => console.log(error)
);
}
单元测试
it('should set id_token', () => {
mockBackend.connections.subscribe((connection: MockConnection) => {
connection.mockRespond(validResponse);
});
spyOn(localStorage, 'setItem').and.returnValue(undefined);
authService.login('admin', 'secret');
expect(localStorage.setItem).toHaveBeenCalledWith('i am a token!');
});
【问题讨论】:
标签: angular unit-testing jasmine observable