Home > front end >  React Native: 'Jest did not exit one second after the test run has completed' with @testin
React Native: 'Jest did not exit one second after the test run has completed' with @testin

Time:04-15

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 contain midsize', 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?

CodePudding user response:

You could try defining a function like:

export function flushPromises() {
  return new Promise((resolve) => setImmediate(resolve));
}

Then on your test before the expect:

await flushPromises();

More info here

CodePudding user response:

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()
  • Related