Angular catchError总是在HTTP单元测试中被调用
我有一个进行HTTP调用的服务,我正在尝试为它编写测试。我尝试测试的服务中的方法如下所示Angular catchError总是在HTTP单元测试中被调用,angular,unit-testing,rxjs,jasmine,Angular,Unit Testing,Rxjs,Jasmine,我有一个进行HTTP调用的服务,我正在尝试为它编写测试。我尝试测试的服务中的方法如下所示 // 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 =
// 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' });
}));
});
});
但是,测试失败,并显示消息错误:预期spy handleErrorInternal未被调用。
有人能帮忙吗?我发现了问题,看起来是这条线路引起的
catchError(this.handleErrorInternal('setUserAgreement'))
这样做可以纠正这种行为
catchError(x => {
this.handleErrorInternal('setUserAgreement');
// return an observable here
})
请检查您的
this.logHttp(x)
和this.parseHttp(x)
方法在测试运行时是否引发任何异常?如果是,则确保这些方法不会引发任何异常。您应该在要测试的providers数组中指定您的服务。在imports数组之后,输入一个逗号,然后是一个新行,其中包含提供者:[myService]
@user2216584谢谢您的回复。我为服务注释掉了这些行,但测试仍然失败。@dmcgrandle感谢您的回复。我将该服务添加到提供商中(我很惊讶没有它它的情况下它会构建)。但问题仍然存在。将spy更改为和.callFake
,使其具有控制台记录发送错误的功能。这应该给你一个线索,它是从哪里来的。。。另外,在subscribe中接收响应(您当前正在忽略返回的内容)并将其记录在console.log中,以确保它是您所期望的。