Spent quite a bit of time getting tRPC integrated into an existing Express based application.
This is a great setup because you can run the existing Express middleware (like auth validation, error & metrics tracking) in front of tRPC.
An interesting challenge was getting testing to work. You can't really create a caller straight to the tRPC router because then you skip all of the Express middleware your production use cases may be using.
We had an existing test setup with Jest + Supertest so I decided to build upon that.
I was able to use the vanilla tRPC client to write tests by creating a custom link that uses supertest for request calling.
Creating the client looks like this:
const client = createTRPCClient<TRPCRouter>({
links: [supertestLink(app, { trpcPath: '/api/v1/trpc', headers: { Authorization: token } })],
transformer: superjson,
})
And then you can write your tests like this:
it('creates a team', async () => {
const createResult = await client.team.createTeam.mutate({
name: 'My new team',
})
expect(createResult?.name).toBe('My new team')
})
You can find the implementation for the supertestLink
in my repo:
https://github.com/Carnewal/trpc-supertest
If anyone's interested I'll create an npm package for it :-)
Brecht
Top comments (0)