React Redux: test UI and useSelector

How to test a stateless component importing useSelector

Fabio Marcoccia
2 min readJan 19, 2021

Before you start reading, it is recommended that you read the previous article about the test here

I started a project with CRA and I added redux-toolkit and redux-mock-store into it.

We should have 3 file which represent our slice of store regarding conversion rate.

conversion.slice.ts
conversion.action.ts
conversion.selector.ts

This slice of store, will be linked to our conversion component in this way

conversion.component.tsx

When you test a component that uses the redux hooks such as useSelector, useDispatch etc… we should ask ourselves this question:

When the store has changes, our UI behave correctly?

Now, make sense “mock” the methods: useSelector and useDispatch (provided by react-redux library) like this:


jest.mock(‘react-redux’, () => ({
useDispatch: jest.fn(),
useSelector: jest.fn()
}));
// you can add it in the setup file or in every single test file if necessary

Make sense to test: start point, loading state and success state.

conversion.test.tsx

In the second and third tests we have to mock the slice of the store that is interesting to test.
Using spyOn on useSelector the test adds an observe to this method, using mockImplementation we enabled to return the mockStore and not the really store.

So in the second test we are able to understand how our UI reacts when isLoading = true,
in the third when the API is resolved and we have the conversion rate.

In the next article we’ll see how to test the store (reducer, action, selector).

Thanks :)

--

--