React Native:使用@testing-library/react-hooks和react-query“测试运行完成后一秒Jest没有退出”

GRZ*_*RZa 3 jestjs react-native react-hooks testing-library react-query

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

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

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.
Run Code Online (Sandbox Code Playgroud)

这是我的简化代码:

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

  })
Run Code Online (Sandbox Code Playgroud)

})

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

知道如何修复它吗?

TkD*_*odo 6

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

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

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