Testing async redux actions with Jest

Alex Bachuk
2 min readSep 11, 2017

--

bugs will happen ;)

Testing your code is important. But in my experience writing tests is one of the lowest priorities, it’s always about new features. And then when something breaks in production everyone is surprised why.

Testing strategy

In most cases stability of existing code is more important than half-done and buggy new features. Investing time in a good testing strategy should be one of the top priorities for any development team (startup or big company).

100% code coverage may be ideal but not necessary, focus on the code that makes sense to write unit tests for (business logic) first. To make the code testable it should be broken down into small units (functions, modules, components). A good rule of thumb is when you find a bug (either production or reported by QA) write a unit test before fixing it and then verify the fix by running the test. It will prevent this bug in the future.

Redux action creators

Testing asynchronous code is slightly different than regular functions. When it comes to redux async actions — it’s even more different. Redux documentation has some examples but in my case it didn’t work because I’m using axios.

Most of my actions involve API calls and action creators. Here is the example action file which has 3 actions (START, SUCCESS, FAIL)

simple action creator with API call

Decide what to test

In this case, what I really want to test is that when I call getPosts function anywhere in my code it will dispatch GET_POSTS_START action and then GET_POSTS_SUCCESS with expected payload. Obviously more complex action creators may have more logic, require certain data and therefore need more testing. In this case it’s very simple.

Testing

Here is my test for the above action. All dependencies should be installed as dev-dependencies. Here we are importing our action, mocking the API call with moxios (which works well with axios) then returning mock data as API response and checking if our action payload is what we expect to see in the end. getPostMock is just a copy of API response as JSON, which is another check agains any API changes in the future.

Now that we know how test redux actions, we need to test reducers, which I’ll cover in the next article. Stay tuned.

--

--