Ask Your Question
3

Why are my JEST tests failing with the error message "fetch is not defined"?

asked 2021-10-07 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-08-28 05:00:00 +0000

lalupa gravatar image

This error message is indicating that the global fetch function, which is used to make HTTP requests, is not defined in your testing environment.

There are a few possible solutions to this issue:

  1. If you are using jest to run your tests, you can install a testing library called jest-fetch-mock that provides a mock implementation of the fetch function. Install it using npm install --save-dev jest-fetch-mock and then import it in your test files.
// in your test file
import fetchMock from 'jest-fetch-mock';

fetchMock.enableMocks();
  1. You can also define a mock implementation of the fetch function in your test setup file. For example, if you are using axios to make HTTP requests, you can define a mock implementation using axios-mock-adapter.
// in your test setup file
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const mock = new MockAdapter(axios);

mock.onGet('/users').reply(200, {
  users: [{ id: 1, name: 'John' }]
});
  1. If you are running your tests in a browser environment, you may need to install a global fetch polyfill to provide an implementation of the fetch function. One popular library is whatwg-fetch. Install it using npm install --save-dev whatwg-fetch and then import it in your test files.
// in your test file
import 'whatwg-fetch';
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-07 11:00:00 +0000

Seen: 9 times

Last updated: Aug 28 '22