reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.69k stars 1.17k forks source link

Jest warning while using the RTK Query useQuery hook in React Native project #1777

Closed JBudny closed 2 years ago

JBudny commented 2 years ago

Hi,

I'm currently working on a React Native project testing template using the RTKQ and MSW library, but I stumbled upon a Jest warning. The warning happens only while testing components based on useQuery hook. The manual dispatch of the RTKQ initiate action followed by using redux useSelector hook doesn't cause the warning.

The warning:

Jest did not exit one second after the test run has completed.

Minimal repo to reproduce the issue: https://github.com/JBudny/react-native-rtkq-testing-with-msw ant then:

I got the mentioned workaround from here callstack/react-native-testing-library#810. A similar issue that I think might be helpful I've found under the other query-like library tannerlinsley/react-query#1847. I also think it might be important to mention that I use cross-fetch as I found a working setup here #1271.

JBudny commented 2 years ago

I've just found out that while dispatching redux-toolkit action creators it's necessary to return the unsubscribe callback to be called in the useEffect cleanup. After doing that it looks like the workaround I mentioned above no longer works.

JBudny commented 2 years ago

For anyone having the same issue.

In this specific case I ended up updating jest to the latest "^27.4.2" version and then I used:

beforeEach(() => {
    jest.useFakeTimers('legacy')
})

afterEach(() => {
    jest.useRealTimers()
})

I'm not sure if it's the proper approach to deal with this warning, but eventually it disappeared. It may break other tests using jest fake timers utilities, because msw seems to not play nice with jest fake timers.

markerikson commented 2 years ago

This may be related to https://github.com/reduxjs/redux-toolkit/issues/1762 ?

rickyalmeidadev commented 2 years ago

I was facing a similar issue. I fixed it by preventing the API from keeping the data when the code is running in the test environment. A code example of my solution:

const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({
    baseUrl: 'any-base-url',
  }),
  keepUnusedDataFor: process.env.NODE_ENV !== 'test' ? 60 : 0, <- here
  endpoints: () => {
    return {
      // your endpoints
    };
  },
});

My answer to a related question on Stack Overflow: https://stackoverflow.com/a/70734352/15442064

JBudny commented 2 years ago

@markerikson Looks like that's what I was looking for. Thanks! :smiley:

I'm closing the issue as it seems to be the right answer