Search code examples
javascriptreactjsreduxrtk-query

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?


Solution

  • 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')
          )