gan*_*ers 6 unit-testing mocking angular5
我正在尝试对我的 http.get/post/etc 响应进行单元测试。
我发现这个教程非常有用:https : //medium.com/spektrakel-blog/angular-testing-snippets-httpclient-d1dc2f035eb8
通过并遵循这一点,我已经配置了我的单元测试并且我能够让一切正常工作,但是我有一个与教程不一致的部分......
在教程中,它显示测试服务登录功能是这样的:
it(`should emit 'true' for 200 Ok`, async(inject([HttpClientFeatureService, HttpTestingController],
(service: HttpClientFeatureService, backend: HttpTestingController) => {
service.login('foo', 'bar').subscribe((next) => {
expect(next).toBeTruthy();
});
backend.expectOne('auth/login').flush(null, { status: 200, statusText: 'Ok' });
})));
Run Code Online (Sandbox Code Playgroud)
这是正在测试的服务的实际方法:
login(user: string, password: string): Observable<boolean> {
const body = new HttpParams()
.set(`user`, user)
.set(`password`, password);
const headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });
return this.http.post(`auth/login`, body.toString(), { headers, observe: 'response' })
.map((res: HttpResponse<Object>) => res.ok)
.catch((err: any) => Observable.of(false));
}
Run Code Online (Sandbox Code Playgroud)
这是我的登录功能:
login(username: string, password: string): Observable<any> {
this.loggingService.log('LoginService | login | username: ' + username + '; password: xxxxx');
return this.http.post(this.loginUrl, { username: username, password: password })
.map((response: any) => {
console.log('response: ' + JSON.stringify(response));
if (response && response.length > 0) {
return response;
} else {
return this.parseErrorResponse(response);
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试:
it('login should return a valid JWT', async(inject([LoginService, HttpTestingController], (service: LoginService, backend: HttpTestingController) => {
service.login('user', 'password').subscribe((next) => {
expect(next).toEqual('asdfasdfasdf');
});
backend.expectOne(environment.authenticationServiceBaseUrl + 'api/login')
.flush('asdfasdfasdf', { status: 200, statusText: 'Ok' });
})));
Run Code Online (Sandbox Code Playgroud)
您会注意到这里的不同之处在于地图响应部分。我的版本只是从单元测试的 http.post 调用中返回一个字符串,而示例显示它正在返回一个 HttpResponse 对象并且只是检查该statusText属性是否等于“Ok”。
为什么我的版本只返回字符串,而示例版本返回实际的 HttpResponse(包括 status 和 statusText)?我想要这里的教程版本...
该示例显示它null通过刷新函数调用在响应正文中返回,而我必须在其中添加我的虚拟 JWT 值以使我的测试通过。即使我将其指定为null类似于测试,我在单元测试中得到的响应也是null.
我哪里出错了?
| 归档时间: |
|
| 查看次数: |
9409 次 |
| 最近记录: |