[英]Mocked Apollo Provider with React testing library is not returning data
I've been trying to fix this problem for a couple days and I'm still at a loss.几天来我一直在尝试解决这个问题,但我仍然不知所措。
I have a React app that uses Apollo Client and I want to test one component with the React testing library.我有一个使用 Apollo Client 的 React 应用程序,我想使用 React 测试库测试一个组件。 Omitting all the irrelevant details, my main file code looks like that:
省略所有不相关的细节,我的主文件代码如下所示:
const ComponentToTest = () => {
...
const { data, loading } = useComponentRespQuery({
variables: {
id: idValue
},
skip: !idValue
});
if (loading) {
return <>Loading</>;
}
...
}
And the test is written like that:测试是这样写的:
const componentRender = (mockGraphQLData: any, initialEntry: string = "") => render(
<MemoryRouter initialEntries={[initialEntry]}>
<MockedProvider mocks={[ mockGraphQLData ]} addTypename={false}>
<ComponentToTest />
</MockedProvider>
</MemoryRouter>
);
describe("ComponenToTest", () => {
it("should render a component to test", async() => {
componentRender(zoneMock);
const placeHolderValues = await screen.findByText(/Bla/i);
expect(placeHolderValues).toBeInTheDocument();
});
...
}
Where componentRespDocument is equal to其中 componentRespDocument 等于
query GetResp($id: ID!) {
resp(id: $id) {
id
name
description
controls {
id
name
}
}
And my mock is written like that我的模拟是这样写的
export const componentRespMock = {
request: {
query: componentRespDocument
},
result: {
data: {
resp: {
id: "ID",
name: "NAME",
description: "DESCRIPTION",
controls: [
{
id: "CTRL_2",
name: "Second control"
}
]
}
}
}
};
I can confidently say that this way of testing worked before in my codebase.我可以自信地说,这种测试方式以前在我的代码库中是有效的。 I found one way to make Apollo return the right value while testing, and it was to comment out all the code in
useComponentRespQuery
.我找到了一种让 Apollo 在测试时返回正确值的方法,那就是注释掉
useComponentRespQuery
中的所有代码。 Anybody faced it before and knows how to fix it?以前有人遇到过它并且知道如何解决它吗?
It is a bit hard to say without knowing what's under the hood in MockedProvider
provider.在不知道
MockedProvider
提供程序的幕后情况的情况下很难说。 However, in my experience with mocks they should always match (1:1), especially if it works when you comment out { variables: { id: idValue }, skip: !idValue }
inside useComponentRespQuery
.但是,根据我的模拟经验,它们应该始终匹配 (1:1),尤其是当您在
useComponentRespQuery
中注释掉{ variables: { id: idValue }, skip: !idValue }
时它有效。
I would suggest double checking zoneMock
to make sure that it matches what you expect我建议仔细检查
zoneMock
以确保它符合您的期望
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.