Search code examples
react-nativereact-hooksjestjsreact-querytesting-library

React Native: 'Jest did not exit one second after the test run has completed' with @testing-library/react-hooks and react-query


I am using jest and @testing-library/react-hooks to test hooks implemented with react-query in my React Native code.

The tests work ok, but at the end, I am getting:

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

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

Here is my simplified code:

import { renderHook } from '@testing-library/react-hooks'
import React from 'react'
import { QueryClient, QueryClientProvider, useQuery } from 'react-query'

const useSomething = () => {
  return useQuery('myquery', () => 'OK')
}

beforeAll((done) => {
  done()
})

afterAll((done) => {
  done()
})

// test cases
describe('Testing something', () => {
  it('should do something', async () => {
    const queryClient = new QueryClient()
    const wrapper = ({ children }: { children: React.ReactFragment }) => (
      <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
    )
    const { result, waitFor } = renderHook(() => useSomething(), { wrapper })

    await waitFor(() => {
      return result.current.isSuccess
    })

    expect(result.current.data).toBe('OK')

  })

})

I tried using cleanup, done, unmount, etc. before each/all with no results. If I remove useQuery from useSomething, the problem disappears.

Any idea how to fix it?


Solution

  • This issue has been reported in the past here: https://github.com/tannerlinsley/react-query/issues/1847

    The issue is caused by the react-query garbage collection timer running, which defaults to 5 minutes. Solutions are, as described in the issue:

    • clearing the queryCache after each test: afterEach(() => { queryClient.clear() });
    • setting cacheTime to 0 for your test, e.g. with: queryClient.setDefaultOptions({ queries: { cacheTime: 0 } })
    • using jest.useFakeTimers()