Coder Social home page Coder Social logo

msw-trpc's People

Contributors

cuexter avatar kondo0602 avatar madi-tracksuit avatar maloguertin avatar swallowtail62 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

msw-trpc's Issues

bug: TRPCClientError: Invalid URL

Describe the bug

So since upgrading to the latest trpc version, it seems that this library fails, although I believe the issue is not with the library per se.

[cause]: TypeError: Invalid URL
      at new NodeError (node:internal/errors:393:5)
      at URL.onParseError (node:internal/url:565:9)
      at new URL (node:internal/url:645:5)
      at new URL (node:internal/url:642:22)
      at FetchInterceptor.<anonymous> (/Users/michael/Developer/observerly/observerly/node_modules/.pnpm/@[email protected]/node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts:51:26)
      at step (/Users/michael/Developer/observerly/observerly/node_modules/.pnpm/@[email protected]/node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:59:23)
      at Object.next (/Users/michael/Developer/observerly/observerly/node_modules/.pnpm/@[email protected]/node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:40:53)
      at fulfilled (/Users/michael/Developer/observerly/observerly/node_modules/.pnpm/@[email protected]/node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:31:58)
      at processTicksAndRejections (node:internal/process/task_queues:95:5) {
    input: 'null',
    code: 'ERR_INVALID_URL'
  }

To Reproduce

Install tRPC: v10.34.0 or higher
Setup tropic-msw
See error being thrown ...

Expected behavior

Prior to this, version 10.32.0 of @trpc/* packages worked well with msw-trpc, with no issue. However, since upgrading @trpc to the latest versions ^10.34 I have seen this error.

Versions
typescript: v5.1.3
tRPC: v10.36.0
msw: v1.2.3

Question: is this compatible with msw v1.0.1 ?

I tried to install msw but pnpm warned me that peer dependencies was not met.

I checked the package.json of this repo and then find out it doesn't support major version update in msw (^ instead of >=)

`req.getInput` incorrectly typed for `query`

Describe the bug

When mocking a query, and using req.getInput, TS incorrectly infers the type.

To Reproduce
I've created an example repo to reproduce the bug:

https://github.com/DavidAmmeraal/msw-trpc-bug/blob/main/src/example.ts

Given the following:

trpcMsw.post.byId.query((req, res, ctx) => {
    assert.equal(req.getInput(), { id: '1' });

    return res(
      ctx.status(200),
      ctx.data({
        id: '1',
        title: 'test',
        text: 'test',
        createdAt: new Date(),
        updatedAt: new Date(),
      }),
    );
  })

TS tells me that req.getInput should be of type:

(property) getInput: () => {
    id: string;
}

However, when running the code (using npx ts-node src/example.ts), the return value is instead:

{
  0: {
    json: {
      id: '1'
    }
}

Expected behavior

I would expect getInput to return a value of shape:

{
    id: string;
}

Versions
"@trpc/next": "^10.37.1",
"@trpc/react-query": "^10.37.1",
"@trpc/server": "^10.37.1",
"typescript": "^5.1.3",

When output parser is used in the procedure, `ctx.data` argument type is unknown (invalid type)

Describe the bug
As the title suggests, the argument type of the ctx.data function is not correctly inferred.

image

image

To Reproduce
Steps to reproduce the behavior:

  1. Create a router with a procedure with output parser.
  2. Create the mock service worker, as above, with your AppRouter inferred type.
  3. Check the type of ctx.data function.

Expected behavior
The expected behavior is the argument type of ctx.data is inferred as the return type of the output parser.

Versions
typescript: v5.1.6
tRPC: v10.33.1
msw: v1.2.2

Serialization of request input with e.g., superjson

First of all, this is an awesome piece of work for the tRPC community. Truly, awesome! However, I have noticed a bug when using with superjson serialisation on the input.

Bug Description

If we specify an input serialisation, such as superjson:

const msw = createTRPCMsw<AppRouter>({
  baseUrl: 'http://localhost:3000/trpc',
  transformer: {
    input: superjson,
    output: superjson
  }
})

I've found that req.getInput() gets incorrect types as:

Screenshot 2023-02-21 at 12 12 39

A workaround would be to do some type madness (which, ideally, we would like to avoid):

const { json } = req.getInput() as unknown as {
    json: inferProcedureInput<AppRouter['observations']['all']>
}

Replication Steps

  1. Create a router of your choice with some sample input. I've used skip and take from Prisma.io pagination terminology.
  2. Create the mock service worker, as above, with your AppRouter inferred type.
  3. Check the type of req.getInput() and it will be missing the json key and the nested input types.

**Expected **

The expected behvaiour when we provide an input transform, that that transform is applied to the req.getInput return type.

Versions

typescript: v4.9.5
tRPC: v10.11.1
msw: v0.49.3
msw-trpc: v1.2.0

Request: Example integration with Next and RTL

Is your feature request related to a problem? Please describe.

I would like to request a demo of a next-trpc combined with this project and RTL. Ideally Running in vite.

Describe the solution you'd like

I've set up my project in such a way I would expect things to work. I've wired up this project with storybook-msw. Code,

The trpc client is created with createTRPCNext here. This client is provided to the stories here.

Now I want to write tests for these stories. Code

The problem is that those mocks never resolve. they are in place, I can see them with server.listHandlers, and if i manually fire a query like fetch("/api/trpc/questions....") the interceptor works. But on the queries triggered by the trpc client, the query never resolves. It doesn't trigger the interceptor, it doesn't trigger the onUnhandledRequest, but if i remove the msw mock, and spy on fetch i can see the query being done.

I've spent quite some time trying to dig into what it's wrong, but this goes beyond me. Plenty of people seem to have no problem integrating this project in RTL, but they are all using the raw react approach. There is even this thread that partially explains a workaround... but I couldn't get it working for my project.

I would like to have a demo that demonstrates how this setup, or a similar one is possible. My project is quite complicated, but if you want I can try to provide a minimal reproduction with the key functionalities.

Describe alternatives you've considered

  • use cross-fetch... no effect
  • remove msw-storybook no effect.
  • Apply the workaround from here but in my code it was just not practicable.

Additional context

Thanks a lot for this project!

Cannot trigger useQuery `error` or `isError` response in test

"msw-trpc": "^1.3.4",

On my client I am making the call const { data, isLoading, isError, error } = trpc.exampleFunction.useQuery().
If isError is true, I display the error.message in my screen.

This works fine when running my client app, however I cannot get the query to return the error in my unit tests (Jest / RN Testing Library). error remains undefined, and isError remains false.

Test setup:

Have tried:

const server = setupServer(
    trpcMsw.exampleFunction.query((req, res, ctx) => {
      throw new Error("test trpc error");
    }),
  );
const server = setupServer(
  trpcMsw.exampleFunction.query((req, res, ctx) => {
    throw new TRPCError({
      message: "test trpc error",
      code: 'NOT_FOUND',
    });
  }),
);
const notFound = {
  error: {
    json: {
      message: 'NOT_FOUND',
      code: 404,
      data: {
        code: 'NOT_FOUND',
        httpStatus: 404,
        stack: '',
        path: '',
        zodError: null,
      },
    },
    meta: [],
  },
};

const server = setupServer(
  trpcMsw.exampleFunction.query((req, res, ctx) =>
    res(ctx.status(404), ctx.json(notFound)),
  ),
);

The console output during the tests with the first two of the above shows a console warning with:
TRPCClientError: request to http://localhost:3000/trpc/exampleFunction?batch=1&input=%7B%220%22%3A%220%22%7D failed, reason: test trpc error

And the last shows a console warning with:
TRPCClientError: Unable to transform response from server

error and isError are undefined and false respectively, and never update.

Is it possible to get isError and the error object to be returned from this query in the test?

`req.getInput()` should indicate that its return type is a promise for mutations

Describe the bug
req.getInput() should indicate that its return type is a promise for mutations. Incorrect typing will also mean someone attempting to get the input without awaiting this promise will get unexpected behavior.

To Reproduce
Create a mocked server where a mutation is used.

const server = setupServer(
  trpcMsw.example.hello.mutation(async (req, res, ctx) => {
    const request = await req.getInput(); // warning
    return res(
      ctx.status(200),
      ctx.data({
        greeting: `Hello ${request.text}!`,
      })
    );
  })
);

Observe the warning: 'await' has no effect on the type of this expression.

An example repo can be found here. Link to the line with the warning

Expected behavior
Since getInput() returns a promise for mutations, it the type returned from getInput() should be a promise.

Versions
typescript: v5.0.4
tRPC: v10.22.0
msw: v1.2.1

Support tRPC subscriptions (WebSockets)

Is your feature request related to a problem? Please describe.
This package doesn't support tRPC subscriptions (websockets), for example when the client looks like:

import { createTRPCProxyClient, createWSClient, wsLink } from '@trpc/client';
import type { AppRouter } from '../path/to/server/trpc';

// create persistent WebSocket connection
const wsClient = createWSClient({
  url: `ws://localhost:3001`,
});

const client = createTRPCProxyClient<AppRouter>({
  links: [
    wsLink({
      client: wsClient,
    }),
  ],
});

Unfortunately, the client/test will time out because the http request never gets upgraded to websocket.

Describe the solution you'd like
Handle the initial http request for upgrading from http to WebSocket. The request has headers:

headers@2x

Then, the package might also get another cool feature: to control when messages/event on the tRPC subscription (websocket) are sent to the client in the test.

Support for V11

Is your feature request related to a problem? Please describe.

V11 has now entered Beta. Unfortunately this package does not work out of the box with V11 and some work might be needed.

Describe the solution you'd like

support for MSW v11.

Describe alternatives you've considered

Remaining on V10 for the time being :P

Additional context

you can find a PR on my public project trying to make this bump:

PupoSDC/chair-flight#77

Thank you very much for this package! โค๏ธ

ctx is untyped..

Your library is exactly what I was hoping to find, thank you!

The one issue I have right now is that the ctx parameter is untyped. This is surprising to me as it appears that it should be correctly typed via the ExtractProcedureHandler type.

image

My mswTrpc instance is pretty straight forward:

const mswTrpc = createTRPCMsw<AppRouter>({
  transformer: { input: superjson, output: superjson },
});

..what am I missing?

Cannot run msw-trpc with vitest

Describe the bug
After upgrading msw-trpc from v1.2.1 -> v1.3.1, running vitest with my current setup is giving an ES module reference error, not quite sure what the issue could be.

image

Expected behavior
Vitest should run as normal before the upgrade.

Versions
typescript: v5.0.4
tRPC: v10.20.0
msw: v1.3.1

Merged routes not working with latest trpc and msw-trpc

Describe the bug
When using msw-trpc with the latest version of trpc and merged / sub routers, every route exposes an (errornous) mutation method instead of the subrouter

To Reproduce
Steps to reproduce the behavior:

  1. Create a trpc router with nested/merged routers
  2. Setup msw-trpc
  3. Try to access sub routers
  4. See error

Bug: `output` is used inside `getMutationInput`

Describe the bug
Inside getMutationInput, output is used instead of input to get the return value. When using a transformer, when it's mutation, deserialization is not applied for mutation input.

this should be changed from:

const getMutationInput = async (req: Request, transformer: CombinedDataTransformer) => {
  const body = await req.json()

  return transformer.output.deserialize(body)
}

to:

const getMutationInput = async (req: Request, transformer: CombinedDataTransformer) => {
  const body = await req.json()

  return transformer.input.deserialize(body)
}

Is it possible to reproduce the case where the server side throws a TRPCError?

Is your feature request related to a problem? Please describe.
yes. I would like to reproduce a case where the server side throws a TRPCError in a unit test, but the documentation does not describe how to do this.

Describe the solution you'd like
Documentation of how to resolve the above (and implementation if not already done)

Describe alternatives you've considered
nothing

Additional context
nothing

Support for createTRPCReact (react query)

Is your feature request related to a problem? Please describe.
I have a standalone trpc server (with subscriptions) that I use with React, but msw-trpc doesn't support it yet or there are no examples of how to use it with react-query and createTRPCReact. It would be great to have some examples of how to use it with useQuerywithin a react component: https://trpc.io/docs/react

Describe the solution you'd like
I would like to have the ability to use msw-trpc with React and be able to mock subscriptions, mutations and queries.

Describe alternatives you've considered
Manually mocking the provider.

Integrate with ladle

(This is a question, not a feature request. Sorry if this is the wrong place to ask.)

I use ladle for stories. I would like to mock my tRPC calls to work on the stories without having to spin up my server. I just stumbled upon msw-trpc and it looks very promising. Before I dig into integrating it with ladle myself, I just wanted to ask whether somebody already did the heavy lifting? If so, I'd be thankful if you could share it. Thanks so much! ๐Ÿ™

Call to GET http://127.0.0.1:49475/ not handled

Describe the bug
After a couple of request interceptions, I get this in jest:

console.warn
      [MSW] Warning: captured a request without a matching request handler:
      
        โ€ข GET http://127.0.0.1:49475/
      
      If you still wish to intercept this unhandled request, please create a request handler for it.
      Read more: https://mswjs.io/docs/getting-started/mocks

I guess 49475 is the port that msw decides to work with. But I don't have any calls without procedures, and that URL seems to be a call to the server but without any procedure at all. This is impossible in my codebase, because I only wrote a couple of procedures, without room for errors.

To Reproduce
Steps to reproduce the behavior:

Maybe write a test covering a scenario of re-fetch. After the re-fetch, this fails.

To be clear, I'm using httpLink and not httpBatchLink, because I know batch is not supported yet.

Expected behavior
That "empty" call shouldn't be performed.

Versions
typescript: v4.9.5
tRPC: v10.21.1-alpha.2
msw: v1.2.1

Issue running with react hooks with tRPC 10.33.1+

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: trpc/trpc#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 

Issues throwing errors in 2.0.0-beta.0

Describe the bug
In version 1.x, to return an error, the experience was not ideal:

const notFound = {
  error: {
    json: {
      message: "NOT_FOUND",
      code: -32004,
      data: {
        code: "NOT_FOUND",
        httpStatus: 404,
        stack: "",
        path: "",
        zodError: null,
      },
    },
    meta: [],
  },
};

server.use(
  api.shipment.getAddress.query((req, res, ctx) => {
    return res(ctx.status(404), ctx.json(notFound));
  })
)

From what I understand, 2.x improves the experience:

server.use(
  api.shipment.getAddress.query(() => {
      throw new TRPCError({
        code: "NOT_FOUND",
      });
  })
)

However, the error on the client side does not match the reality, and I couldn't find an escape hatch:

msw-trpc 2.0.0-beta.0:

{
  "meta": {
    "response": {}
  },
  "name": "TRPCClientError"
}

trpc 10.44.1:

{
  "meta": {
    "response": {},
    "responseJSON": [
      {
        "error": {
          "json": {
            "message": "NOT_FOUND",
            "code": -32004,
            "data": {
              "code": "NOT_FOUND",
              "httpStatus": 404,
              "stack": "TRPCError: NOT_FOUND ...",
              "path": "shipment.getAddress",
              "apiError": null,
              "zodError": null
            }
          }
        }
      }
    ]
  },
  "shape": {
    "message": "NOT_FOUND",
    "code": -32004,
    "data": {
      "code": "NOT_FOUND",
      "httpStatus": 404,
      "stack": "TRPCError: NOT_FOUND ...",
      "path": "shipment.getAddress",
      "apiError": null,
      "zodError": null
    }
  },
  "data": {
    "code": "NOT_FOUND",
    "httpStatus": 404,
    "stack": "TRPCError: NOT_FOUND ...",
    "path": "shipment.getAddress",
    "apiError": null,
    "zodError": null
  },
  "name": "TRPCClientError"
}

To Reproduce
Steps to reproduce the behavior:

  1. Create a trpc handler
  2. Setup msw-trpc and throw an NOT_FOUND TRPCError
  3. On the client, JSON.stringify the error

Expected behavior
A clear and concise description of what you expected to happen.

Versions
typescript: v5.2.2
tRPC: v10.44.1
msw: v2.0.11

trpc query firing before service worker is started

Describe the bug
My app is using Nextjs although no SSR is being performed. Despite deferring app bootstrapping as suggested here, trpc queries are fired before the MSW service worker initializes.
trpc
I can confirm that subsequent queries are being intercepted by msw. Has anyone tried integrating msw-trpc with a Nextjs app before and encountered this issue?

To Reproduce
Steps to reproduce the behavior:

  1. Create a Nextjs app using msw-trpc for request mocking
  2. Create a component that performs an immediate trpc query
  3. Navigate to component with msw active
  4. See query fired before service worker is loaded

Expected behavior
MSW service worker is finished loading before trpc queries are fired by react.

Versions
typescript: v4.7.4
tRPC: v10.9.0
msw: v1.2.2
next: v12.3.0

@typescript-eslint/no-unsafe-argument

Describe the bug

The examples fails to adhere to this typescript eslint rules
https://typescript-eslint.io/rules/no-unsafe-argument/

To Reproduce
Steps to reproduce the behavior:
add this .eslintrc.json to the root of this repository

{
  "overrides": [
    {
      "extends": [
        "plugin:@typescript-eslint/recommended-requiring-type-checking"
      ],
      "files": ["*.ts", "*.tsx"],
      "parserOptions": {
        "project": "tsconfig.json"
      }
    }
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "project": "./tsconfig.json"
  },
  "plugins": ["@typescript-eslint"],
  "extends": ["plugin:@typescript-eslint/recommended"]
}

run eslint test/integration.test.js
There will be error:

  12:35  error  Unsafe argument of type `any` assigned to a parameter of type `ResponseTransformer<DefaultBodyType, any>`  @typescript-eslint/no-unsafe-argument
  15:35  error  Unsafe argument of type `any` assigned to a parameter of type `ResponseTransformer<DefaultBodyType, any>`  @typescript-eslint/no-unsafe-argument
  18:35  error  Unsafe argument of type `any` assigned to a parameter of type `ResponseTransformer<any, any>`              @typescript-eslint/no-unsafe-argument
  21:35  error  Unsafe argument of type `any` assigned to a parameter of type `ResponseTransformer<DefaultBodyType, any>`  @typescript-eslint/no-unsafe-argument
  24:35  error  Unsafe argument of type `any` assigned to a parameter of type `ResponseTransformer<DefaultBodyType, any>`  @typescript-eslint/no-unsafe-argument
  27:35  error  Unsafe argument of type `any` assigned to a parameter of type `ResponseTransformer<any, any>`              @typescript-eslint/no-unsafe-argument

Expected behavior

There should be no error.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.