I am using node 18 in my Typescript code and nock library https://www.npmjs.com/package/nock for tests.
I have a simple class which makes fetch
call to one endpoint and want to test it by mocking the response.
My simplified code is
MagicClient.ts
type Config = {
baseUrl: string;
};
export default class MagicClient {
// eslint-disable-next-line no-useless-constructor
constructor(private readonly config: Config) {}
public async doMagic(): Promise<Object> {
const response = await fetch(`${this.config.baseUrl}/do-magic`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ magic: true }),
});
return JSON.parse(await response.text());
}
}
My test code is
MagicClient.test.ts
import nock from 'nock';
import MagicClient from '../../../src/MagicClient';
describe(MagicClient.name, () => {
const client = new MagicClient({
baseUrl: process.env.MAGIC_BASE_URL,
});
beforeEach(() => {
jest.resetAllMocks();
nock.cleanAll();
nock.disableNetConnect();
nock.enableNetConnect('127.0.0.1');
});
afterEach(() => {
expect(nock.isDone()).toBeTruthy();
});
const mockedResponse = {
success: true,
magic: 'abc',
};
it('calls do magic', () => {
nock(process.env.MAGIC_BASE_URL)
.post('/do-magic', { magic: true })
.reply(200, mockedResponse);
expect(
client.doMagic(),
).toEqual(mockedResponse);
});
});
Result is:
Real endpoint is being called! and nock does nothing. I can fully confirm this because I get response from real api endpoint... instead of seeing my mock response
My environment:
node v18.16.0
"jest": "^29.2.0",
"nock": "^13.4.0",
My thoughts:
I think nock.disableNetConnect();
is not working sometimes... as the call is clearly going through the real endpoint in the internet.
I have setup the test env process.env.MAGIC_BASE_URL to match a real endpoint, no localhost nothing is a public rest http endpoint and call goes through..
I have another doubt and it might be that nock does not intercept the native fetch
...
Any idea why this is not working and how to fix ?
I have other code using nock exactly in the same way that works fine so it is mind blowing.
After deep debugging I figured out nock does not support native
fetch
I confirmed that this is the issue because found it reported as well
https://github.com/nock/nock/issues/2397
Solution
I just imported for the time being
import fetch from 'node-fetch';
in top of the file and nock worked