Skip to content

Commit

Permalink
chore: port adapters' tests (#3233)
Browse files Browse the repository at this point in the history
  • Loading branch information
nilskj authored and KATT committed Nov 26, 2022
1 parent 1a95e8a commit be53d6a
Show file tree
Hide file tree
Showing 4 changed files with 644 additions and 0 deletions.
24 changes: 24 additions & 0 deletions packages/tests/server/adapters/__router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { initTRPC } from '@trpc/server';
import { z } from 'zod';

export type Context = {
user: {
name: string;
} | null;
};

const t = initTRPC.context<Context>().create();

export const router = t.router({
hello: t.procedure
.input(
z
.object({
who: z.string().nullish(),
})
.nullish(),
)
.query(({ input, ctx }) => ({
text: `hello ${input?.who ?? ctx.user?.name ?? 'world'}`,
})),
});
98 changes: 98 additions & 0 deletions packages/tests/server/adapters/express.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Context, router } from './__router';
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client/src';
import * as trpc from '@trpc/server/src';
import * as trpcExpress from '@trpc/server/src/adapters/express';
import AbortController from 'abort-controller';
import express from 'express';
import http from 'http';
import fetch from 'node-fetch';

async function startServer() {
const createContext = (
_opts: trpcExpress.CreateExpressContextOptions,
): Context => {
const getUser = () => {
if (_opts.req.headers.authorization === 'meow') {
return {
name: 'KATT',
};
}
return null;
};

return {
user: getUser(),
};
};

// express implementation
const app = express();

app.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router,
createContext,
}),
);
const { server, port } = await new Promise<{
server: http.Server;
port: number;
}>((resolve) => {
const server = app.listen(0, () => {
resolve({
server,
port: (server.address() as any).port,
});
});
});

const client = createTRPCProxyClient<typeof router>({
links: [
httpBatchLink({
url: `http://localhost:${port}/trpc`,
AbortController: AbortController as any,
fetch: fetch as any,
}),
],
});

return {
close: () =>
new Promise<void>((resolve, reject) =>
server.close((err) => {
err ? reject(err) : resolve();
}),
),
port,
router,
client,
};
}

let t: trpc.inferAsyncReturnType<typeof startServer>;
beforeAll(async () => {
t = await startServer();
});
afterAll(async () => {
await t.close();
});

test('simple query', async () => {
expect(
await t.client.hello.query({
who: 'test',
}),
).toMatchInlineSnapshot(`
Object {
"text": "hello test",
}
`);
const res = await t.client.hello.query();
expect(res).toMatchInlineSnapshot(`
Object {
"text": "hello world",
}
`);
});
Loading

0 comments on commit be53d6a

Please sign in to comment.