'Why do I get reference error for fetch when I do unit tests using Jest?
I'm new to unit tests using Jest but basically I have a file client.js looking like this:
function add(a, b) {
return a + b;
}
const fetcher = () => {
return fetch('http://localhost:3000/').then(res => res.json);
}
module.exports = {add, fetcher};
The client.test.js is as follows:
const client = require('../client');
test('Testing addition', () => {
expect(client.add(1, 2)).toBe(3);
});
test('Yet another addition', () => {
expect(client.add(3, 10)).toBe(13);
});
test('Testing a promise', () => {
return client.fetcher().then(data => {
expect(data).toBe(1824);
})
});
When I try to run tests it throws an error ReferenceError: fetch is not defined. How do I fix this?
Solution 1:[1]
Either:
- Define a
fetchfunction somewhere (e.g. by loading the node-fetch module that is available on NPM) - Use the
--experimental-fetchflag when you run Node (and make sure it is version 17.5 or newer
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
