Unit testing with Jest: Redux + async actions + fetch

  • Unit testing with Jest: Redux + async actions + fetchUsing Jest v20LAST UPDATE: June 24, 2017.
  • Ok, now, let’s test it step by step based on the WritingTests from the Redux docs.A big change here since I first wrote this article in 2016 is that Jest now does not mock your dependencies automatically like it used to.
  • /api’;import configureMockStore from ‘redux-mock-store’import thunk from ‘redux-thunk’const middlewares = [ thunk ];const mockStore = I am also going to write a helper method to mock the fetch response (we don’t need nock as suggested in the Redux Writing Test example):const mockResponse = (status, statusText, response) = { return new window.Response(response,…
  • Do you remember the import at the beginning of our example action code?import ‘whatwg-fetch’If you or your team forget to use the polyfill version of fetch, Chrome or FF will still work and you won’t notice it!
  • Thanks to the Redux docs for the great explanation of how we can test those async actions and for the mocha example (2017 note: They changed the example to use Jest!)

I have been using Jest since its beginnings. I won’t lie, the path has been painful: Things like updating from version 0.x.0 to version 0.y.0 (specially to version 0.4.0) was particularly terrible…

Unit testing with Jest: Redux + async actions + fetchUsing Jest v20LAST UPDATE: June 24, 2017. Original writing: May 19, 2016.I have been using Jest since its beginnings. I won’t lie, the path has been painful: Things like updating from version 0.x.0 to version 0.y.0 (specially to version 0.4.0) was particularly terrible for my tests. Furthermore, I struggled myself more than once with the way Jest works and I even bothered the community with questions like 1, 2, and 3.But stay with me, Jest has also good things that I am going to show you in a moment. I hope somebody will find this particularly useful because, in my humble opinion, the biggest drawback of Jest is its lack of real examples.Recently (May 19, 2016), I’ve been writing an app with the React/Redux combo. It uses an external API and I decided to use a fetch polyfill in order to make my network requests. Following the Redux-way, I’ve used Async Action Creators in combination with redux-thunk. Here is how my action looks like:(Notice that nowadays you can use async/await too).Ok, now, let’s test it step by step based on the WritingTests from the Redux docs.A big change here since I first wrote this article in 2016 is that Jest now does not mock your dependencies automatically like it used to. You can read more about it on its blog: Jest 15 — Disabled automockingTherefore, we do not need to manually unmock modules we want to test.On the contrary, we are going to use redux-mock-store…

Unit testing with Jest: Redux + async actions + fetch