'How to correctly mock node-fetch?
I'm having problems mocking node-fetch it is not mocking and makes an actual request to an API.
Here is the module I'm trying to mock
import fetch from 'node-fetch';
export const createUser = async () => {
const response = await fetch('http://website.com/users', { method: 'GET' });
const userId = await response.json();
return userId;
};
Test
import { createUser } from '../createUser';
import { jest } from '@jest/globals';
const mockFetch = jest.fn().mockReturnValue(
Promise.resolve({
json: async () => ({
id: 4
})
})
);
it("tests get request" , async () => {
const userId = await createUser(); // makes an actual request
expect(userId.id).toBe(4);
expect(mockFetch).toHaveBeenCalledWith('http://website.com/users', {
method: 'GET'
});
})
Another way I tried to mock like it is specified in docs, but getting an error that fetch.mockResolvedValueOnce is not a function
jest.mock('node-fetch');
import { createUser } from '../createUser';
import { jest } from '@jest/globals';
import fetch from 'node-fetch';
it("tests get request", async () => {
fetch.mockResolvedValueOnce(
Promise.resolve(() => ({
id: 4
}))
);
const userId = await createUser(); // makes an actual request
expect(userId.id).toBe(4);
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
