Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Request Header module using Jest

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

like image 572
ALBI Avatar asked Sep 15 '17 01:09

ALBI


3 Answers

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

like image 143
Srivathsa Harish Venkataramana Avatar answered Nov 09 '22 00:11

Srivathsa Harish Venkataramana


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.

like image 29
Jonathan Cremieux Avatar answered Nov 08 '22 23:11

Jonathan Cremieux


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,
  });
});
like image 28
Jeb Avatar answered Nov 09 '22 01:11

Jeb