I'm trying to work with RTK Query, but can't find a good example of how to write unit tests with react testing library for a component that uses requests with RTK Query.
For example, we have a component that gets a list of something from server. How do mock data for requests? I found a solution to use mswjs for mocking API for tests.
But even with it, I have a problem: I need to add await new Promise((r) => setTimeout(r, 1000)); before I'll check that something from the collection exists.
Maybe, somebody knows how to test components with RTK Query?
You can take a look at the tests of RTK Query itself.
Some things:
msw to mock an apistoreRef.wrapper in the example) await waitFor(() =>
expect(screen.getByTestId('isFetching').textContent).toBe('false')
)
An alternative I have found is mocking the rtk query hooks themselves. Then you can set anything you want for the data object.
jest.mock('pathToHook', () => ({
__esModule: true,
default: () => () => { data: 'whatever you want' },
}))
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