The "jest fetch is not defined" error occurs when you try to use fetch() in Jest tests, but Jest doesn’t recognize it. This happens because Jest does not provide a built-in implementation of fetch(), since fetch() is a browser API and Jest runs in a Node.js environment by default.
Common Causes and Solutions:
✅ 1. fetch is Not Available in Node.js
- Since fetch is a browser feature, it’s not available in Node.js, where Jest runs.
- Solution: Install node-fetch or use global.fetch in your setup file.
npm install node-fetch --save-dev
Then, in your Jest setup file (jest.setup.js):
global.fetch = require('node-fetch');
✅ 2. Missing Jest Fetch Mock
- If you're testing code that uses fetch(), Jest needs a mock implementation.
- Solution: Use jest-fetch-mock.
npm install jest-fetch-mock --save-dev
Then, add this to your jest.setup.js:
import 'jest-fetch-mock';
fetchMock.enableMocks();
Now, you can mock fetch() in your tests:
fetchMock.mockResponseOnce(JSON.stringify({ data: 'test' }));
✅ 3. Using jest.spyOn() Instead
If you want to manually mock fetch, you can use:
jest.spyOn(global, 'fetch').mockResolvedValue({
json: jest.fn().mockResolvedValue({ data: 'mocked data' }),
});
Final Thoughts
- Jest does not provide fetch() by default because it runs in Node.js, not the browser.
- Use jest-fetch-mock, node-fetch, or jest.spyOn() to handle it.
- Set up mocks correctly to avoid errors in Jest tests.