Testing a component in Next.js with testing-library that relies on tRCP

Viewed 290

I was experimenting with tRCP and diligently followed the setup for my Next.js project described in the official docs over here: https://trpc.io/docs/nextjs

However I noticed that a simple component that relies on tRPC such as this

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

cannot be properly tested since the following trivial test

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

since there is no setup of provider such as the setup with the withTRCP HOC used for the application itself. As such the test fails claiming client (presumably the trcpClient, unlike the queryClient) is undefined.

I'd like to know how to setup the test correctly, in this case providing a correct client, as well as mocking the queries, since I don't have the respective server-side code running while invoking the tests.

1 Answers

Since you are getting undefined for the trpc client implementation, you can try spying on the query call.

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();
  });
});

This is also possible with the mutations but you need to provide a mock implementation for the useMutation response for mutate property.

Related