|
| 1 | +--- |
| 2 | +title: Testing & Mocking |
| 3 | +description: How to test and mock oRPC routers and procedures? |
| 4 | +--- |
| 5 | + |
| 6 | +# Testing & Mocking |
| 7 | + |
| 8 | +Testing and mocking are essential parts of the development process, ensuring your oRPC routers and procedures work as expected. This guide covers strategies for testing and mocking in oRPC applications. |
| 9 | + |
| 10 | +## Testing |
| 11 | + |
| 12 | +Using [Server-Side Clients](/docs/client/server-side), you can directly invoke your procedures in tests without additional setup. This approach allows you to test procedures in isolation, ensuring they behave correctly. |
| 13 | + |
| 14 | +```ts |
| 15 | +import { call } from '@orpc/server' |
| 16 | + |
| 17 | +it('works', async () => { |
| 18 | + await expect( |
| 19 | + call(router.planet.list, { page: 1, size: 10 }) |
| 20 | + ).resolves.toEqual([ |
| 21 | + { id: '1', name: 'Earth' }, |
| 22 | + { id: '2', name: 'Mars' }, |
| 23 | + ]) |
| 24 | +}) |
| 25 | +``` |
| 26 | + |
| 27 | +::: info |
| 28 | +You can also use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to create production-like clients for testing purposes. [Learn more](/docs/best-practices/optimize-ssr#alternative-approach) |
| 29 | +::: |
| 30 | + |
| 31 | +## Mocking |
| 32 | + |
| 33 | +The [Implementer](/docs/contract-first/implement-contract#the-implementer) is designed for contract-first development, but it can also create alternative versions of your [router](/docs/router) or [procedure](/docs/procedure) for testing. |
| 34 | + |
| 35 | +```ts twoslash |
| 36 | +import { router } from './shared/planet' |
| 37 | +// ---cut--- |
| 38 | +import { implement, unlazyRouter } from '@orpc/server' |
| 39 | + |
| 40 | +const fakeListPlanet = implement(router.planet.list).handler(() => []) |
| 41 | +``` |
| 42 | + |
| 43 | +You can use `fakeListPlanet` to replace the actual `listPlanet` implementation during tests. |
| 44 | + |
| 45 | +::: info |
| 46 | +The `implement` function is also useful for creating mock servers for frontend testing scenarios. |
| 47 | +::: |
| 48 | + |
| 49 | +::: warning |
| 50 | +The `implement` function doesn't support [lazy routers](/docs/router#lazy-router) yet. Use the `unlazyRouter` utility to convert your lazy router before implementing. [Learn more](/docs/contract-first/router-to-contract#unlazy-the-router) |
| 51 | +::: |
0 commit comments