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

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

我正在使用 jest@testing-library/react-hooks 来测试在我的 React Native 代码中使用 react-query 实现的挂钩。

测试工作正常,但最后,我得到:

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.

这是我的简化代码:

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

  })

})

我在 each/all 之前尝试使用 cleanupdoneunmount 等,但没有结果。如果我从 useSomething 中删除 useQuery,问题就会消失。

知道如何解决吗?

您可以尝试定义一个函数,例如:

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

那么在你考试前 expect:

await flushPromises();

更多信息

过去曾在此处报告过此问题: https://github.com/tannerlinsley/react-query/issues/1847

问题是由 react-query 垃圾收集计时器 运行 引起的,默认为 5 分钟。如问题中所述,解决方案是:

  • 每次测试后清除 queryCache: afterEach(() => { queryClient.clear() });
  • cacheTime 设置为 0 以进行测试,例如与:queryClient.setDefaultOptions({ queries: { cacheTime: 0 } })
  • 使用jest.useFakeTimers()