我正在调用 nestjs 服务中的 API,如下所示,
import { HttpService, Post } from '@nestjs/common';
export class MyService {
constructor(private httpClient: HttpService) {}
public myMethod(input: any) {
return this.httpClient
.post<any>(
this.someUrl,
this.createObject(input.code),
{ headers: this.createHeader() },
)
.pipe(map(response => response.data));
}
}
我怎样才能 mock /窥探 this.httpClient.post() 的调用以开玩笑返回响应而不点击实际的 API?
describe('myMethod', () => {
it('should return the value', async () => {
const input = {
code: 'value',
};
const result = ['test'];
// spyOn?
expect(await myService.myMethod(input)).toBe(result);
});
});
最佳答案
使用 spyOn 让它工作。
describe('myMethod', () => {
it('should return the value', async () => {
const input = {
code: 'mock value',
};
const data = ['test'];
const response: AxiosResponse<any> = {
data,
headers: {},
config: { url: 'http://localhost:3000/mockUrl' },
status: 200,
statusText: 'OK',
};
jest
.spyOn(httpService, 'post')
.mockImplementationOnce(() => of(response));
myService.myMethod(input).subscribe(res => {
expect(res).toEqual(data);
});
});
});
关于jestjs - 如何使用 jest 测试 HttpService.Post 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59860854/