If I'm testing a function that makes a fetch call, and all the fetch calls I have in the project are only meant to run in the browser. Do I still need to have some package installed on node and import it to be able to mock that fetch call?
A simple scenario like this throws ReferenceError: fetch is not defined
in the Jest test:
// fetcKey.js
export async function fetchKey() {
try {
const key = await fetch('http://localhost:3000/key');
return (await key.text());
}
catch(error){
throw error;
}
}
//fetchKey.test.js
import fetchKey from './fetchKey'
test('Checks fetchKey return', () => {
expect(fetchKey()).not.toThrow();
})
CodePudding user response:
You should be able to use node-fetch
:
import fetch from 'node-fetch';
(Note it's an ECMAScript Module and cannot be imported with require
, as mentioned in their documentation).