在HTTP单元测试中总是会调用catchError [英] catchError always gets called in HTTP unit testing
本文介绍了在HTTP单元测试中总是会调用catchError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个进行HTTP调用的服务,并且我正在尝试为此编写测试.我要测试的服务中的方法如下所示:
I have a service that makes a HTTP call and I am trying to write tests for it. The method in the service that I am trying to test looks like this
// my.service.ts
setUserAgreement(accept: boolean): Observable<any> {
const data = { accept };
return this.http.post<any>(this.url, data, this.getHttpHeader('1'))
.pipe(
tap(x => this.logHttp(x)),
map(x => this.parseHttp(x)),
catchError(this.handleErrorInternal('setUserAgreement'))
);
}
我的测试文件如下
import { TestBed, async } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { myService } from './my.service';
describe('myService', () => {
let service;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
service = TestBed.get(myService);
httpMock = TestBed.get(HttpTestingController);
});
describe(`#setUserAgreement`, () => {
const mockResponse = 'Mock response';
afterEach(() => {
httpMock.verify();
});
it(`should not call handleErrorInternal when the call resolves successfully`, async(() => {
spyOn(service, 'handleErrorInternal');
service.setUserAgreement(true).subscribe(() => {
expect(service.handleErrorInternal).not.toHaveBeenCalled();
});
const req = httpMock.expectOne(service.url);
req.flush(mockResponse, { status: 200, statusText: 'OK' });
}));
});
});
但是测试失败,并显示消息Error: Expected spy handleErrorInternal not to have been called.
However the test fails with the message Error: Expected spy handleErrorInternal not to have been called.
有人可以帮忙吗?
推荐答案
我发现了这个问题,它似乎是由这一行引起的
I found the issue, it looks like it was caused by this line
catchError(this.handleErrorInternal('setUserAgreement'))
做这样的事情可以固定行为
Doing something like this fixed the behaviour
catchError(x => {
this.handleErrorInternal('setUserAgreement');
// return an observable here
})
这篇关于在HTTP单元测试中总是会调用catchError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文