function createRequest(method) {
const init = {
method,
headers: new Headers({.....}),
};
return new Request(url, init); }
I am using Request headers (with Fetch) in the above code (https://davidwalsh.name/fetch )
However while writing unit test cases using Jest, it gives me this error: ReferenceError: Headers is not defined
DO I need to mock even these standard modules? How should I import Headers in unit test cases
adding ' import "isomorphic-fetch" ' to the jest setup file should resolve this issue as this will make the missing dom APIs available in the tests
I say yes, mocking Headers is definitely an option in a testing context. In my particular case, I have simply mocked it like so:
global.Headers = ()=>{}
This will work just fine if you want to test that your code is behaving properly based on the response returned by fetch. If you also need to check that the correct headers are sent, you would need a more sophisticated mock, and/or perhaps a specialized test suite for your networking methods.
I know this is an old question, but for anyone who runs into this (as I did), this worked for me:
// before running each test
beforeEach(() => {
// define `append` as a mocked fn
const append = jest.fn();
// set test `Headers`
global.Headers = () => ({
append: append,
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With