Last active
October 13, 2023 06:01
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Example:
https://github.com/c-ehrlich/msw-trpc-example/blob/main/src/components/greeting.test.tsx