When do I get error: jest fetch is not defined?
I am getting the following error as I am trying to use
Below given is the code:
fetch is not available, why?
How can I make fetch work in a Jest test so as to not make a mock request but a proper one?
What is the way to avoid this jest fetch is not defined error?
In the Node.js environment, fetch is not available by default, as it is a browser API that is used to make HTTP requests. A Node.js environment is run by jest, which is a Javascript testing framework, and that is why fetch does not work out of the box in jest tests. Jest is not used for integration testing but is used mostly for unit testing. Although you can make fetch work as a global variable.
Here’s how:
const MOCK_DATA = {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
};
global.fetch = jest.fn(() => Promise.resolve({
json: () => Promise.resolve(MOCK_DATA)
}));
describe('FetchTest', () => {
it('perform a fetch', async () => {
// Arrange
// Act
const res = await fetch('https://jsonplaceholder.typicode.com/users/1');
const result = await res.json();
console.log(result);
// Assert
expect(1).toBe(1);
});
});