React Redux: test UI and useSelector

How to test a stateless component importing useSelector

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

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

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 :)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store