playmP
tRPC2y ago
1 reply
playm

Test React component using trpc client and `useSuspenseQuery`

Hello !

I'm trying to test my React component that's querying through a tRPC client and
useSuspenseQuery
.
I'm using Jest and I'm mocking the tPRC server with Mockttp.

I suppose that when using
useSuspenseQuery
we should mock that query using a stream, so my test looks like this:
describe('Navigation menu', () => {
  const mockServer = mockttp.getLocal({
    cors: {...},
  });

  ...

  it('should display the nav menu', async () => {
    const reqUrl = '/ConversationAPI.countPendingConversations';
    const mockedStream = new PassThrough();
    await mockServer.forGet(reqUrl).thenStream(200, mockedStream);

    render(
      <Suspense fallback={<div>Loading...</div>}>
        <Nav />,
      </Suspense>
    );

    mockedStream.emit('data', {
      pending: 0,
    });
    mockedStream.emit('end');

    await waitFor(() => {
      return expect(screen.getByTestId('badge')).toBe('0');
    });
  });


I'm running my tests using
mockttp -c jest
as recommended in Mockttp's documentation. That part looks fine.

My problem is that when running this test I'm having the following error:
console.error
  Error: Error: socket hang up
      at Object.dispatchError ([...]/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:63:19)
      ...
      at processTicksAndRejections (node:internal/process/task_queues:82:21) {
    type: 'XMLHttpRequest'
  }


I'm not super familiar with streams but I'm wondering if I'm using the right function from mockttp to mock the
useSuspenseQuery
or if I'm not passing the right thing to
thenStream(...)
.

Any help is appreciated, thanks !
Was this page helpful?