how to best test trpc?

does programs like postman not work well with trpc? if i wanted to test my trpc server by making requests, what the best way to do that?
1 Reply
y_nk
y_nk2w ago
i've found that best is to use the trpc client in your test runner (vitest/jest) by setting up the trpc client to use a custom http link which uses supertest with your app passed as param. with fastify (but it works with express too):
export function createTestClient(app: FastifyInstance) {
const agent = supertest.agent(app.server)

return createTRPCClient<AppRouter>({
links: [
httpLink({
transformer: superjson,
url: 'http://localhost/api',
async fetch(input, options) {
const method = options?.method?.toLowerCase() ?? 'get'
const url = new URL(input)

let call = agent[method](`${url.pathname}${url.search}`)

// Add headers
if (options?.headers) {
for (const [key, val] of Object.entries(options.headers)) {
call = call.set(key, val)
}
}

if (options?.body) {
call = call.send(options.body)
}

const res = await call

return new Response(JSON.stringify(res.body), {
status: res.status,
headers: res.headers,
})
},
}),
],
})
}
export function createTestClient(app: FastifyInstance) {
const agent = supertest.agent(app.server)

return createTRPCClient<AppRouter>({
links: [
httpLink({
transformer: superjson,
url: 'http://localhost/api',
async fetch(input, options) {
const method = options?.method?.toLowerCase() ?? 'get'
const url = new URL(input)

let call = agent[method](`${url.pathname}${url.search}`)

// Add headers
if (options?.headers) {
for (const [key, val] of Object.entries(options.headers)) {
call = call.set(key, val)
}
}

if (options?.body) {
call = call.send(options.body)
}

const res = await call

return new Response(JSON.stringify(res.body), {
status: res.status,
headers: res.headers,
})
},
}),
],
})
}

Did you find this page helpful?