【问题标题】:Angular 8 Jasmine not matching HTTP requestAngular 8 Jasmine 不匹配 HTTP 请求
【发布时间】:2019-10-15 23:41:27
【问题描述】:

我有一个 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
    ));
}

我错过了什么?

【问题讨论】:

    标签: angular jasmine mocking httptestingcontroller


    【解决方案1】:

    缺少的是我的服务方法确实返回了一个Observable,因此要完成它,需要对其进行subscribed 的测试。

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

    service.doStuff(123).subscribe(() => {});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 2017-06-17
      • 1970-01-01
      相关资源
      最近更新 更多