Loading...

Testing In React-Redux

Overview:

Here are some testing examples and tips for React / Redux projects. In these examples, I will be using a project generated by Mikey. Setting up a testing suite takes time but, Mikey makes this easy with automatic setup of testing dependencies, directory, test helpers, and commands. In these examples I will primarily be using Mocha, Chai, JSDom, and Enzyme instead of the standard react testing tools. If you have any other questions at the tools I'm referencing or testing, you can check out Mikey's generated project's package.json under dev dependencies for more information.

Testing Components:

Testing Components can be pretty straight forward. Here is an example of the Component source and test:

In the test I mock the post data, since the component is passed props and needs them to render certain JSX, and expect this data to be rendered.

Testing Containers:

Testing Container components is trickier because when they are connected to the Redux store you will need to mock this. Here is an example of the Container source and test:

Inside the Container test the store is imported with { Provider } from react-router, to connect the store. With these two imports you can mock a connected store within the test.

Testing Reducers:

Testing reducers in React-Redux is fairly straight forward by expecting it to return a new state object. Here is an example:

Testing Actions:

One of the more complex things to test in React-Redux are actions, specifically asynch/thunk actions. One way of testing these type of actions is to expect the series of actions from the store. Here is an example of a series of auth actions and testing where I mock the http request. I recommend using fetch as your HTTP library because it is much easier to test with Nock.

Hopefully I have helped in some manner. If you have any questions, feel free to contact me! Don't forget to checkout: Mikey