Mocking and testing fetch with Jest

June 04, 2018 0 Comments

Mocking and testing fetch with Jest

 

 

Photo by João Silas on Unsplash

Here’s a quick note about mocking and testing fetch calls with Jest.

Let’s take an example React component, ExampleComponent:

Let’s write a test for it using Jest and Enzyme, ExampleComponent.test.js:

Some points to note here are:

  1. By passing the done function here, we’re telling Jest to wait until the done callback is called before finishing the test. See Testing Asynchronous Code docs for more details.
  2. Since we await the call to response.json() in ExampleComponent.js, we Promise.resolve it in the test to a mockSuccessResponse object.
  3. Since we are awaiting the call to fetch(https://url-of-your-server.com/example/json), in ExampleComponent.js, and expecting the returned object to contain a json function, which returns another Promise, we Promise.resolve to an object containing such a json function.
  4. We spy on window.fetch and mock it’s implementation to return the Promise object described in 3.
  5. We invoke Enzyme to shallow render, which also invokes the React lifecycle methods *.
  6. Wrapping our assertion code inside a process.nextTick() ensures that the functions queued in the current event loop are completed, thus also ensuring that our Promises and other code inside ExampleComponent is done executing.
  7. Optionally, we clear the mock.
  8. We invoke done to tell Jest that this test case is complete.


Tag cloud