I am using Redux Toolkit approach by creating:
I Want to understand what is the best way to test with React Testing Library the:
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!
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With