【发布时间】: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