0

我有一个 Angular 服务发出一些 HTTP 请求,我想测试它是否使它们以正确的方式。

在它的依赖项中,它还有一个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
    ));
}

我错过了什么?

4

1 回答 1

1

缺少的是我的服务方法确实返回了一个Observable,所以要完成它,需要对它进行测试subscribe

那么,为了使测试工作,实际的服务调用需要

service.doStuff(123).subscribe(() => {});
于 2019-10-15T15:41:27.537 回答