Skip to content

Instantly share code, notes, and snippets.

@swport
Last active October 13, 2023 06:01
Show Gist options
  • Save swport/bdb185b7360500ef29ff90fdfc0b49ea to your computer and use it in GitHub Desktop.
Save swport/bdb185b7360500ef29ff90fdfc0b49ea to your computer and use it in GitHub Desktop.
Mock tRPC query and mutation calls using msw (works well with both vitest and jest)
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, type RenderOptions } from "@testing-library/react";
import { createTRPCReact, httpLink } from "@trpc/react-query";
import { createTRPCMsw } from "msw-trpc";
import { type ReactElement } from "react";
import superjson from "superjson";
import { type AppRouter } from "@/server/api/root";
const mockedTRPC = createTRPCReact<AppRouter>({
unstable_overrides: {
useMutation: {
async onSuccess(opts) {
await opts.originalFn();
await opts.queryClient.invalidateQueries();
},
},
},
});
const mockedTRPCClient = mockedTRPC.createClient({
transformer: superjson,
links: [httpLink({ url: "http://localhost:3000/api/trpc" })],
});
const mockedQueryClient = new QueryClient();
export const MockedTRPCProvider = (props: { children: React.ReactNode }) => {
return (
<mockedTRPC.Provider client={mockedTRPCClient} queryClient={mockedQueryClient}>
<QueryClientProvider client={mockedQueryClient}>{props.children}</QueryClientProvider>
</mockedTRPC.Provider>
);
};
export const renderWithTRPC = (ui: ReactElement, options?: Omit<RenderOptions, "wrapper">) => {
return render(ui, {
wrapper: (props) => <MockedTRPCProvider {...props} />,
...options,
});
};
export const trpcMsw = createTRPCMsw<AppRouter>({
transformer: { input: superjson, output: superjson },
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment