Angular 8 Jasmine与HTTP请求不匹配
我有一个Angular服务发出一些HTTP请求,我想测试它是否以正确的方式发出请求 在其依赖项中,它还有一个Angular 8 Jasmine与HTTP请求不匹配,angular,jasmine,mocking,httptestingcontroller,Angular,Jasmine,Mocking,Httptestingcontroller,我有一个Angular服务发出一些HTTP请求,我想测试它是否以正确的方式发出请求 在其依赖项中,它还有一个EnvironmentService,它根据环境返回正确的API端点,我用Jasmine模仿了它 我的测试如下所示: describe('ShipmentsService', () => { let httpTestingController: HttpTestingController; let service: ShipmentsService; con
EnvironmentService
,它根据环境返回正确的API端点,我用Jasmine模仿了它
我的测试如下所示:
describe('ShipmentsService', () => {
let httpTestingController: HttpTestingController;
let service: ShipmentsService;
const envSpy = jasmine.createSpyObj('EnvironmentService', ['getRestEndpoint', 'dev']);
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ShipmentsService,
{provide: EnvironmentService, useValue: envSpy}
],
imports: [HttpClientTestingModule]
});
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(ShipmentsService);
});
it('does the right HTTP request', () => {
envSpy.getRestEndpoint.and.returnValue('foo');
service.doStuff(123);
expect(envSpy.getRestEndpoint)
.toHaveBeenCalledWith('changePackingProperties');
const request = httpTestingController.expectOne('foo');
request.flush({shipmentId: 123});
httpTestingController.verify();
});
});
这是我的ShipmentsService
方法:
doStuff(shipmentId: number) {
let path = this.environmentService.getRestEndpoint('changePackingProperties');
return this.http.post(path, body, {headers}).pipe(map(
(response) => response
));
}
我遗漏了什么?遗漏的是,我的服务方法确实返回了一个可观察的
,,因此要完成测试,需要订阅它
因此,为了使测试能够工作,实际的服务调用需要
service.doStuff(123).subscribe(() => {});