I am calling a API in nestjs service like below,
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));
}
}
How can I mock/spyOn the call to this.httpClient.post() in jest to return response without hitting the actual API?
describe('myMethod', () => {
it('should return the value', async () => {
const input = {
code: 'value',
};
const result = ['test'];
// spyOn?
expect(await myService.myMethod(input)).toBe(result);
});
});
Got it working by using 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);
});
});
});
A good alternative to mocking the http service would also be to declare it in the providers array as follow.
let httpClient: HttpService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: HttpService,
useValue: {
post: jest.fn(() => of({
// your response body goes here
})),
},
},
],
}).compile();
httpClient = module.get<HttpService>(HttpService);
});
By providing your HttpService in the testing module rather than use spy on, you ensure that the HttpModule won't be imported or used and reduce your test code dependency to other services.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With