在Angular服务中测试管道/嵌套HttpClient的测试未完成

问题描述 投票:0回答:2

我想测试管道的HttpClient调用,但是似乎http调用未及时完成并且没有响应。

configuration.service.ts

public loadData() {
   return this.configurationService.getAppConfig().pipe(
      switchMap(appConfig => this.http.get<string[]>("url"))
   );
}

configuration.service.spec.ts

let service: CustomService;
let httpTestingController: HttpTestingController;

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [
            CustomService,
            { provide: ConfigurationService, useClass: MockedConfigurationService }
        ],
        imports: [HttpClientTestingModule],
    });

    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(ConfigurationService);
});

it("should make a get request for loadData", () => {
    service.loadData().subscribe(data => {
        // This is not called
        console.log(data);
    });

    const req = httpTestingController.expectOne("url");
    req.flush(["my.data"]);

    expect(req.request.method).toEqual("GET");

    httpTestingController.verify();
});

如果我只是像返回请求一样,一切都很好。

return this.http.get<string[]>("url");

我也尝试过使用手动创建/完成的Observables,但未为httpClient调用订阅:

const appConfig$ = this.configurationService.getAppConfig();

return new Observable(observer => {
    appConfig$.subscribe(appConfig => {
        this.http.get<string[]>("url").subscribe(
            result => {
                observer.next(result);
                observer.complete();
            }
        );
    });
});

我在做什么错?在httpClient能够完成之前,测试用例似乎已经完成。

我想测试管道的HttpClient调用,但是看来http调用无法及时完成,并且没有响应。 configuration.service.ts public loadData(){返回this.configurationService ....

angular jasmine observable karma-jasmine angular8
2个回答
0
投票

我认为您的MockedConfigurationService不正确。我们可以看到吗?


0
投票

同时我想通了。

© www.soinside.com 2019 - 2024. All rights reserved.