这个错误是由于没有正确引入 Testing Library 的 React Hooks 导致的。需要在测试文件的开头引入 Testing Library 的 React Hooks,并使用 renderHook
方法进行测试。
代码示例:
import { renderHook } from '@testing-library/react-hooks';
import { useQuery } from '@apollo/client';
import { MyQuery } from './MyQuery';
describe('MyQuery', () => {
it('should fetch data', async () => {
const { result, waitForNextUpdate } = renderHook(() => useQuery(MyQuery));
// 等待异步操作完成
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeUndefined();
expect(result.current.data).toHaveProperty('myData');
});
});