In this tutorial, I will show you how to unit test any custom ReactJS component that talks to a Redux store. As Redux is a complex beast, writing unit tests for components that are wrapped in a connect() method will need some thought. To test a Redux wrapped component we will need a way to mock the Redux store. Mocking the Redux store can be done using redux-mock-store. After mocking the store we can start to write all kind of cool tests. To demonstrate how to test a component, I will use the one shown below:

To write a simple snapshot test for the component above is done like this:

Let us walk through what this test is doing. On line 7, a mock store is being created using configureStore(). The mock store is passed into Provider as a prop called store. Doing this allows us to mock the store and to test that the correct interactions are taking place when the component runs. Finally, we can validate the component matches our expectations. In this instance, I am using toMatchSnapshot() to perform snapshot test.

You can default state into your store when it loads by passing props into your mock store, like so:

If you want to test that certain actions have been triggered, you can mock the dispatch call like so:

As you can see in line 2, we mock the dispatch() call using jest.fn();. This mocking allows dispatch() calls to be made without the test failing and throwing an error. This is great for our testing! On line 11, you can then test how the dispatch() call was used while the test was running. This should give you more confidence that your application behaves the way you intend it to!

Combing all these things will allow you to test most Redux based ReactJS components. Give it a go and see how you get on. Happy Coding 🤘