connectrpc / connect-query-es

TypeScript-first expansion pack for TanStack Query that gives you Protobuf superpowers.

Home Page:https://connectrpc.com/docs/web/query/getting-started

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: Recommended ways for testing/mocking services

ghandic opened this issue · comments

I'm looking for docs on mocking rpc function responses from the frontend for unit tests and cant find many/any references on approaches with connect-query. The only way I have seen so far is to make another abstraction ontop of the client and then mock that.

Would you be able to provide some tips on how to mock responses (errors and successes) of the gRPC calls alongside tanstack/react-query ?

eg something along the lines of this?

const mutationPromise = Promise.resolve(new SomeActionResponse());
const mockMutate = jest.fn().mockReturnValue(mutationPromise);

jest.spyOn(service.SomeAction, "useMutation").mockReturnValue({ mutationFn: mockMutate });

render(<Component />);

Hey Andy, we recommend the Router Transport for this case. It's a Transport just like createGrpcWebTransport(), but it does not call remote procedures via HTTP. Instead, you provide your own service implementation.

Here is an example:

import {Code, ConnectError, createRouterTransport} from "@connectrpc/connect";

const transport = createRouterTransport(router => {
  router.rpc(SomeService, SomeService.someAction, (req) => {
    if (req.someField === true) {
      throw new ConnectError("something bad", Code.ResourceExhausted);
    }
    return new SomeActionResponse();
  })
});

If you create a client with this Transport and call someAction, the function you provide will be called. There will not be any network activity. Depending how you structure your unit tests, you might want to pass this transport via the transport option to useMutation, or with a <TransportProvider>.

You can find more details in the documentation here. We also use it ourselves in the tests in this repository, for example here.

Note that if you are using the jest-environment-jsdom, you have to switch to our patched version @bufbuild/jest-environment-jsdom with support for the Encoding API.

We have just added in example withe React and createRouterTransport to our examples repository here.

It uses vanilla React without tanstack/query, but it should be really straight-forward to adapt.

Recently just added some basic example tests with #125 so hopefully that provides enough context. We do have a backlog issue to look into integration with the msw framework, @ghandic would that help?