maloguertin / msw-trpc

tPRC support for MSW
208 stars 21 forks source link

Issue running with react hooks with tRPC 10.33.1+ #28

Open tarehart opened 11 months ago

tarehart commented 11 months ago

Describe the bug

Starting at exactly version https://github.com/trpc/trpc/releases/tag/v10.33.1, the useQuery hook no longer testable with msw-trpc in vitest. For some reason the msw proxy server never receives a request. Possibly useQuery is not calling fetch, or not calling fetch in a way that msw is able to intercept.

I also reported this to tRPC: https://github.com/trpc/trpc/issues/5134

I'm not sure if you can do anything to fix this, since my understanding is that msw-trpc only gets involved after msw's server receives a request.

As evidence that no request reaches the server, if I modify the test to have configuration like this, no error is thrown:

const server = setupServer();
server.listen({ onUnhandledRequest: 'error' });

To Reproduce Steps to reproduce the behavior:

git clone https://github.com/c-ehrlich/msw-trpc-example/
cd msw-trpc-example
npm install
npm run test

Expected behavior Test passes.

Test used to pass, this can be verified by pinning the tRPC versions to 10.33.0.

Versions

System:
    OS: macOS 13.5.2
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 840.20 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.15.0 - ~/.nvm/versions/node/v18.15.0/bin/node
    npm: 9.5.0 - ~/.nvm/versions/node/v18.15.0/bin/npm
  Browsers:
    Chrome: 119.0.6045.199
    Safari: 17.1.2
  npmPackages:
    @tanstack/react-query: ^4.28.0 => 4.36.1 
    @trpc/client: ^10.18.0 => 10.44.1 
    @trpc/next: ^10.18.0 => 10.44.1 
    @trpc/react-query: ^10.18.0 => 10.44.1 
    @trpc/server: ^10.18.0 => 10.44.1 
    msw: ^1.2.1 => 1.3.2 
    msw-trpc: ^1.3.3 => 1.3.4 
    next: ^13.4.1 => 13.5.6 
    react: 18.2.0 => 18.2.0 
    typescript: ^5.0.2 => 5.2.2 
tarehart commented 11 months ago

I found a better way of doing things that works with tRPC latest, I described it in https://github.com/trpc/trpc/issues/5134 and closed that issue.

Would you be interested in an integration test contribution that covers react hooks?

maloguertin commented 11 months ago

Hi thanks for your work! So just to make sure, the problem is with setting global.fetch like https://github.com/c-ehrlich/msw-trpc-example this example is showing?

Is this repo linked in the tRPC docs because I can't seem to find it?

Would you be interested in an integration test contribution that covers react hooks?

That would be nice, also we could add something about that to the readme?

tarehart commented 11 months ago

Yes, setting global.fetch was the problem.

Nope, the repo is just something I found while googling, I never found an official recommendation on how to test with hooks.

My modified solution doesn't rely on setting global.fetch, but does still use the cross-fetch library. I'll go ahead and make a pull request to illustrate.