Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Testing Library with Redux Toolkit

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!

like image 745
Subhranshu Avatar asked Apr 11 '26 17:04

Subhranshu


1 Answers

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')
like image 85
Chris Danna Avatar answered Apr 13 '26 08:04

Chris Danna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!