DEV Community

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

Posted on • Edited on

5

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 client.team.createTeam.mutate({
    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:

https://github.com/Carnewal/trpc-supertest

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

Brecht

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more