React Testing Library with Redux Toolkit
Asked Answered
N

1

11

I am using Redux Toolkit approach by creating:

  1. slices with reducer and extra reducers
  2. thunks with createAsyncThunk API

I Want to understand what is the best way to test with React Testing Library the:

  1. slices with reducer and extra reducers
  2. thunks with createAsyncThunk API

A sample is given in the below gist: https://gist.github.com/subhranshudas/8021ec6d205a05680bc9e11f3ef7fb7d

Any feedback is appreciated.

Note: I had asked the same question in Reddit and got the following reply: https://www.reddit.com/r/reduxjs/comments/hvwqc9/reduxtoolkit_unit_testing_strategy/ While I am clear with the "what" from the response, I am looking for a definitive "how" with React Testing Library.

Apologies if it is an obvious question, but I am interested in checking out the definitive ways to do so in React Testing Library (since I am new to it)

Thanks!

Neanderthal answered 27/7, 2020 at 15:9 Comment(1)
Have you tried the "classic" way of unit-testing thunks? That should still work with thunks created by createAsyncThunk. There might be additional convenience added from RTK that makes testing thunks even more concise, but I think you can always falls back on the classic way. See answers for "testing thunks with jest" for example.Aciculum
J
1

The recommended practice has shifted from isolated unit testing to component/store integration tests. Testing your components with your thunks/reducers verify the app behaves as expected the way a user would interact with it, while giving you coverage of your components and redux implementation. React Testing library is useful for testing components that are integrated with the store, and when your thunks make API requests, you can mock the responses using Mock Service Worker. If you only want to unit test the implementation details without components then you don't need React Testing Library.

E.g. testing a component containing a button that when clicked will fetch content from an API and then display the text in a heading:

// import {render, screen} from '@testing-library/react'
// import userEvent from '@testing-library/user-event'
render( 
  <Provider store={store}>
    <MyComponent />
  </Provider>
)

const loadButton = screen.getByText('Load Content')
await userEvent.click(loadButton)

await screen.findByRole('heading') // waits for a heading before throwing
expect(screen.getByRole('heading')).toHaveTextContent('Mocked content')
Janettjanetta answered 31/1, 2023 at 15:3 Comment(1)
The example provided is fairly representative of the same way the RTK/RTK-Query (which operates off of thunks) tests are written for the sections that require react i.e. the useQuery hooks. Thought I'd just link some here for reference: Testing thunk/query using react Testing without reactFukien

© 2022 - 2024 — McMap. All rights reserved.