使用依赖于 tRCP 的测试库测试 Next.js 中的组件

Chr*_*vic 7 reactjs next.js react-testing-library trpc.io

我正在尝试 tRCP,并认真遵循此处官方文档中描述的 Next.js 项目的设置: https: //trpc.io/docs/nextjs

然而我注意到有一个依赖 tRPC 的简单组件,比如这样

export const Sample = () => {
  const { data } = trpc.useQuery(['hello', { text: 'User' }]);
  if (data === undefined) {
    return <div>Loading...</div>;
  }
  return <div>{data.greeting}</div>;
};
Run Code Online (Sandbox Code Playgroud)

由于以下琐碎测试而无法正确测试

describe('Sample', () => {
  it('should render successfully', () => {
    const { baseElement } = render(<Sample />);
    expect(baseElement).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

因为没有提供程序的设置,例如withTRCP用于应用程序本身的 HOC 的设置。因此,测试失败了client(大概是trcpClient,与queryClient)未定义。

我想知道如何正确设置测试,在这种情况下提供正确的客户端,以及模拟查询,因为我在调用测试时没有运行相应的服务器端代码。

小智 0

由于 trpc 客户端实现未定义,因此您可以尝试监视查询调用。

import trpc from 'utils/trpc'; // This is the client implementation

describe('Sample', () => {
  it('should render successfully', () => {
    jest.spyOn(trpc, 'useQuery')
        .mockReturnValue({ greeting: "Greeting" });

    const { baseElement } = render(<Sample />);
    expect(baseElement).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

这对于突变也是可能的,但您需要为 mutate 属性的 useMutation 响应提供模拟实现。