Basic Async Action Creator Test

Create a basic test for testing async action creators.

We'll cover the following

Jest handles async tests by allowing us to return a promise as the test’s result. If a promise is returned, the test runner will wait for the promise to resolve and only then continue to the next test:

it('FETCH_RECIPE', () => {
  return store.dispatch(actions.fetchRecipe(100));
});

Since store.dispatch() in this case returns a promise (remember, our fetchRecipe() action creator returns a call to the axios library), we can use it to create an async test.

As soon as our test is resolved we can use the same promise to add an expect() clause to the code.

it('FETCH_RECIPE', () => {
  return store.dispatch(actions.fetchRecipe(100))
    .then(() => expect(store.getActions()).toEqual([]))
});

The expect() clause is similar to what we used in our previous tests. We are using the mocked store’s getActions() method to get an array of all the actions dispatched to the store. In our implementation, we expect a successful network call to dispatch the result of the setRecipe() action creator.

Running this test will fail since we didn’t instruct our mocked axios library to mock the target URL. Using the small utility library we created previously, we can create the mock that will result in the correct action sequence:

it('FETCH_RECIPE', () => {
  mockRequest('recipe/100', 200, '{"title":"hello"}');

  return store.dispatch(actions.fetchRecipe(100))
    .then(() => expect(store.getActions()).toMatchSnapshot())
});

Here we mock a 200 successful response from the axios library and expect that dispatching the async action created by fetchRecipe(100) results in a later dispatch of the action created by setRecipe().

Summary

As can be seen from the previous example, testing async action creators are much more complicated than testing regular action creators. If we add proper error handling and branching, the tests quickly become very hard to build.

The Middleware chapter offers an alternative to async action creators by moving the asynchronous logic into middleware. This allows us to test and concentrate all the async codes of an application in a single place.

Get hands-on with 1200+ tech skills courses.