【问题标题】:How to unit test nested HTTP Calls如何对嵌套的 HTTP 调用进行单元测试
【发布时间】:2020-10-10 16:37:48
【问题描述】:

我正在尝试对以下功能进行单元测试:

async fetchGreatHouseByName(name: string) {
  const [house] = await this.httpGetHouseByName(name);
  const currentLord = house.currentLord ? house.currentLord : '957';
  const result: any = await this.httpGetLord(currentLord);
  const character = Characters.default.find(char => char.characterName === result.name);
  return {...house, character};
}

这个函数内部是多个 HTTP GET 调用。我知道如何测试它们,但我如何处理嵌套的 HTTP 调用,每个调用都是一个 Promise。

我得到了什么:

it('should get house from http', done => {
  const httpMock: HttpTestingController = TestBed.inject(HttpTestingController);

  const mockResponse = {
    name: 'House One',
    currentLord: 'Some Lord'
  };

  service.fetchGreatHouseByName('House One').then((house: House) => {
    expect(house).toBeTruthy();
    console.log(house);
  });

  const mockRequest = httpMock.expectOne(
    'https://www.anapioficeandfire.com/api/houses?name=House%20Lannister%20of%20Casterly%20Rock'
  );

  mockRequest.flush(mockResponse);

});

所以httpGetHouseByName 通常会返回类似mockRequest 的内容。还有httpGetLord 和包含name 的对象以及其他属性。这个 HTTP 调用是否还需要一个 mock,如果需要,我该如何使用它?

【问题讨论】:

    标签: javascript angular typescript unit-testing jasmine


    【解决方案1】:

    我认为调用该函数应该将两个 HTTP 调用放入队列中。尝试依次刷新两个调用并将您的断言放入 .then 块中。

    it('should get house from http', done => {
      const httpMock: HttpTestingController = TestBed.inject(HttpTestingController);
    
      const mockResponse = {
        name: 'House One',
        currentLord: 'Some Lord'
      };
    
      service.fetchGreatHouseByName('House One').then((house: House) => {
        expect(house).toBeTruthy();
        console.log(house);
        // your other assertions here
      });
    
      const mockRequest = httpMock.expectOne(
        'https://www.anapioficeandfire.com/api/houses?name=House%20Lannister%20of%20Casterly%20Rock'
      );
    
      mockRequest.flush(mockResponse);
    
      const response = {
         // mock response of httpGetLord here
        };
      const request = httpMock.expectOne(/* url of httpGetLord*/);
      request.flush(response);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多