HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Testing Redux-connected components with React Testing Library

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
testingcomponentswithreactconnectedreduxlibrary

Problem

Testing Redux-connected components with React Testing Library is a very common scenario. However, it might be a little complicated without the proper tools and you could end up repeating yourself. This is especially true when writing the boilerplate to connect to your redux store.
Here's a simple utility function adapted from React Testing Library's docs on the subject to help you speed up your testing:
```jsx title="test/utils/renderConnected.js"
import React from 'react';
import { render } from '@testing-library/react';

Solution

This utility uses the `createStore` function and the `<Provider>` component to wrap a redux-connected component to the passed state. Then it uses React Testing Library's `render` to finally render the result.

Remember to replace `import` statements with the appropriate files and exports to set up the utility as necessary. After creating the utility function and saving it in an appropriate file, you can use it like this:


```jsx title="test/utils/renderConnected.js"
import React from 'react';
import { render } from '@testing-library/react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
// Replace this with the appropriate imports for your project

Code Snippets

This utility uses the `createStore` function and the `<Provider>` component to wrap a redux-connected component to the passed state. Then it uses React Testing Library's `render` to finally render the result.

Remember to replace `import` statements with the appropriate files and exports to set up the utility as necessary. After creating the utility function and saving it in an appropriate file, you can use it like this:

Context

From 30-seconds-of-code: testing-redux-connected-components

Revisions (0)

No revisions yet.