如何在 React 中测试 readFragment?
How to test readFragment in React?
我正在使用 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>
</>
);
我朋友给了我一个解决方案,如果有人需要,我post在这里
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();
});
});
我正在使用 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>
</>
);
我朋友给了我一个解决方案,如果有人需要,我post在这里
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();
});
});