Mocking Request Header module using Jest

ALBI picture ALBI · Sep 15, 2017 · Viewed 8.5k times · Source
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

Answer

Jonathan Cremieux picture Jonathan Cremieux · Nov 21, 2017

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.