Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test RTK Query with react testing library?

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?

like image 991
Denis Avatar asked Mar 06 '26 10:03

Denis


2 Answers

You can take a look at the tests of RTK Query itself.

Some things:

  • use msw to mock an api
  • wrap your component in a real Redux store with your api (storeRef.wrapper in the example)
  • use something to wait for UI changes like
      await waitFor(() =>
        expect(screen.getByTestId('isFetching').textContent).toBe('false')
      )
like image 67
phry Avatar answered Mar 08 '26 22:03

phry


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' },
}))
like image 30
Sebastian Golbert Avatar answered Mar 08 '26 22:03

Sebastian Golbert



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!