NestJS 问题模拟 axios obersvable 响应
NestJS problem mocking axios obersvable response
我在单元测试中模拟 nestjs/axios 调用时遇到问题。
我尝试模拟实现,但它总是超时,这意味着它无法正常工作
jest.spyOn(httpService, 'get').mockImplementationOnce(() => of(result))
const response: CustomerDetail = await client.getCustomerDetails('1');
expect(response).toBeDefined();
下面是我要测试的代码示例。注意:我正在使用 lastValueFrom 将 observable 转换为 promise。
@Injectable()
export class CustomerDetailsClient {
constructor(private httpService: HttpService) {}
async getCustomerDetails(customerId: string): Promise < CustomerDetail > {
let customerDetails: Promise < CustomerDetail > = null;
try {
customerDetails = await lastValueFrom(this.httpService.get(`localhost:80/customers/${customerId}/details`)
.pipe(
map((response) => {
return response.data
}),
),
);
} catch (e) {
throw new InternalServerErrorException('A system error occurred');
}
return customerDetails;
}
}
如有任何帮助,我们将不胜感激
我设法用以下代码解决了这个问题
const response: Promise<CustomerDetail> = client.getCustomerDetails('1');
const customerDetail: CustomerDetail = await response;
expect(response).toBeDefined();
我在单元测试中模拟 nestjs/axios 调用时遇到问题。
我尝试模拟实现,但它总是超时,这意味着它无法正常工作
jest.spyOn(httpService, 'get').mockImplementationOnce(() => of(result))
const response: CustomerDetail = await client.getCustomerDetails('1');
expect(response).toBeDefined();
下面是我要测试的代码示例。注意:我正在使用 lastValueFrom 将 observable 转换为 promise。
@Injectable()
export class CustomerDetailsClient {
constructor(private httpService: HttpService) {}
async getCustomerDetails(customerId: string): Promise < CustomerDetail > {
let customerDetails: Promise < CustomerDetail > = null;
try {
customerDetails = await lastValueFrom(this.httpService.get(`localhost:80/customers/${customerId}/details`)
.pipe(
map((response) => {
return response.data
}),
),
);
} catch (e) {
throw new InternalServerErrorException('A system error occurred');
}
return customerDetails;
}
}
如有任何帮助,我们将不胜感激
我设法用以下代码解决了这个问题
const response: Promise<CustomerDetail> = client.getCustomerDetails('1');
const customerDetail: CustomerDetail = await response;
expect(response).toBeDefined();