英文:
How to test a react component that use "useQuery" outside ApolloProvider with the "client" set as an option
问题
Here is the translation of the provided text:
由于我正在切换到使用 Next.js 创建的 SSR 应用,遵循这个 "official" post。
关键点在于使用 apollo 的组件没有包装在 ApolloProvider 中。相反,"client" 是一个可以在客户端和服务器上使用的单例。
示例:
const { data, loading, error } = useQuery<
{ project: IProject },
{ id: number }
>(GET_PROJECT, {
variables: { id },
client: getClient(), <==
});
一切都正常,除了测试不起作用。我认为这可能是由于以下原因:
<MockedProvider mocks={[mockedProjectRequest]}>
MockedProvider 不与组件共享相同的客户端... 因此,MockedProvider 不接受客户端作为参数...
如果有人找到解决方法,请分享一下
我尝试将新创建的客户端(在 before each 中)的缓存传递如下:
const component = renderWithProvider(
<MockedProvider addTypename={false} mocks={[mockedProjectRequest]} cache={client.cache}> <== 这里
<Project />
</MockedProvider>
store,
"/project/112551",
);
但是它不起作用,mockedProjectRequest 对我的测试组件来说是不可读的。
英文:
As I'm switching to an ssr app using next js following this "official" post.
The main thing is that components using apollo aren't wrapper in an ApolloProvider. Instead the "client" is a singleton that can be used on the client & server.
Exemple:
const { data, loading, error } = useQuery<
{ project: IProject },
{ id: number }
>(GET_PROJECT, {
variables: { id },
client: getClient(), <==
});
Everything works fine expect the tests who dosent. I think that it might be due to:
<MockedProvider mocks={[mockedProjectRequest]}>
MockedProvider doesn’t share the same client as the component... Thus, MockedProvider doesn’t accept a client as a parameter...
If anyone has found a work-around please share it
I've tried to pass the cache from the newly created client (in before each) like so:
const component = renderWithProvider(
<MockedProvider addTypename={false} mocks={[mockedProjectRequest]} cache={client.cache}> <== here
<Project />
</MockedProvider>
store,
"/project/112551",
);
But it dosent work, the mockedProjectRequest is just not readable by my test component.
答案1
得分: 0
我找到了这个新的实验性库,可能对这个用例有帮助:
为了更容易在Next.js中采用Apollo Client,团队发布了一个实验性库:@apollo/experimental-nextjs-app-support
这个库将为您做所有正确的事情,无论您是在Server Components下运行还是在Client Components下运行。
测试也变得更简单,因为我们可以使用mockedProvider。
英文:
Found this new experimental library which might help with this use case:
In order to make it easier to adopt Apollo Client in Next.js, the team is releasing an experimental library: @apollo/experimental-nextjs-app-support
This library will do all the right things for you whether you’re running under Server Components or if you’re running in Client Components.
Testing is also simplified as we can use a mockedProvider.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论