我正在使用Apollo + React + Jest。
我在Apollo缓存中有数据,然后我也在React中从中获取数据。
但是我在测试时无法获取数据。
readFragment
和useQuery
之间获取数据的方式不同。
因此,我不能使用相同的方法来测试我的单元测试文件中的readFragment
。
我尝试模拟provider
和client
,但不起作用。
测试中是否有针对readFragment
的解决方案?
我的反应文件
import React from "react";
import { useApolloClient } from "@apollo/react-hooks";
const FileInfo: React.FC<Props> = props => {
const client = useApolloClient();
const file = client.readFragment({
id: `Rendition-222-333`,
fragment: gql`
fragment rendition on Rendition {
status
title
}
`,
});
return (
<>
<p> {file.status} </p>
<p> {file.title} </p>
</>
);
我的朋友给了我一个解决方案,如果有人需要,我将其发布在这里。
import { useApolloClient } from "@apollo/react-hooks";
jest.mock("@apollo/react-hooks");
describe("<FileInfo/>", () => {
let useApolloClientMock: jest.Mock;
beforeEach(() => {
useApolloClientMock = useApolloClient as jest.Mock;
useApolloClientMock.mockReturnValue({
readFragment: jest.fn().mockReturnValue({ status: "downloaded", title: "123test" }),
});
});
afterEach(jest.resetAllMocks);
test("When it renders Then it should not crash", () => {
const { container } = setup();
expect(container).toBeTruthy();
});
});