DEV Community

Cover image for Testing tRPC + Express with Jest and Supertest
Brecht Carnewal
Brecht Carnewal

Posted on

Testing tRPC + Express with Jest and Supertest

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,

Enter fullscreen mode Exit fullscreen mode

And then you can write your tests like this:

it('creates a team', async () => {
  const createResult = await{
    name: 'My new team',
  expect(createResult?.name).toBe('My new team')
Enter fullscreen mode Exit fullscreen mode

You can find the implementation for the supertestLink in my repo:

If anyone's interested I'll create an npm package for it :-)


Top comments (0)