Answer the question
In order to leave comments, you need to log in
How to properly lock node-fetch in Jest?
I can't figure out why an API request occurs instead of the set mock response.
And what is the right way to block node-fetch in this case?
I also took an example from the documentation ( https://jestjs.io/docs/bypassing-module-mocks ) but there was an error mockReturnValue is not a function
Trying to test the following module
import fetch from 'node-fetch';
export const createUser = async () => {
const response = await fetch('http://website.com/users', { method: 'POST' });
const userId = await response.text();
return userId;
};
import { jest } from '@jest/globals';
import { createUser } from '../createUser';
const mockFetch = jest.fn().mockReturnValue(
Promise.resolve({
json: async () => ({
id: 4
})
})
);
test('createUser calls fetch with the right args and returns the user id', async () => {
const userId = await createUser();
expect(mockFetch).toHaveBeenCalledWith('http://website.com/users', {
method: 'POST'
});
expect(userId.id).toBe(4);
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question