Mocking Request Header module using Jest

17.9k views Asked by At
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

3

There are 3 answers

0
Jeb On

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,
  });
});
5
Jonathan Cremieux On

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.

0
Srivathsa Harish Venkataramana On

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