tPRC support for MSW
- Create MSW handlers from your tRPC router.
- Get your tRPC typing into your MSW handlers.
- Augments MSW with utils for tRPC.
- Use it like you would use the tRPC client.
- Merged routers supported !
- Use
msw
v2
Motivation
As someone who loves MSW and was already using it I wanted to keep using it instead of mocking tRPC. While it is possible to simply write the Rest handlers it felt like it would be great not to lose the full power of tRPC types in the tests.
Usage
1. Install msw-trpc
.
npm i msw-trpc --save-dev
2. build your trpcMsw with createTRPCMsw.
import { createTRPCMsw } from 'msw-trpc'
import type { AppRouter } from 'path/to/your/router'
export const trpcMsw = createTRPCMsw<AppRouter>() /* 👈 */
3. Start using it.
const server = setupServer(
trpcMsw.userById.query(() => ({ id: '1', name: 'Uncle bob' })),
trpcMsw.createUser.mutation((name) => ({ id: '2', name }))
)
You can find examples of how to use it in the test-react package or in the test-node package.
How it works
createTRPCMsw
returns a Proxy that infers types from your AppRouter
// all queries will expose a query function that accepts a MSW handler
trpcMsw.myQuery.query(() => {})
// all mutations will expose a mutation function that accepts a MSW handler
trpcMsw.myMutation.mutation(() => {})
Config
You need to pass a httpLink
to the createTRPCMsw
function like you would do with the tRPC client.
You can pass an optional transformer like superjson
to the createTRPCMsw
function.
interface TRPCMswConfig {
links: Link[]
transformer?: TRPCCombinedDataTransformer
}
Requirements
Peer dependencies:
Please note:
- Batch is not yet supported