Testing a Micro-Frontend, BFF and tRPC Stack
On this page
The test plan
Combine the test strategies from the three courses, one per layer:
| Layer | Test | Runs |
|---|---|---|
| tRPC routers in the BFF | Server-side caller, mocked downstream services | Every pull request, in seconds |
| Types across packages | tsc -p . at the root | Every pull request |
| Micro-frontends | Component tests, plus the mount contract harness | Each team's pipeline |
| Sign-in, CSRF, sessions | BFF route tests with inject and an attacker page | Platform pipeline |
| The composed app | A few Playwright journeys through real sign-in | Before deploy, on staging |
The first two catch most mistakes, cost almost nothing, and run on every change.
Router tests with a caller
A server-side caller runs procedures in-process with a context you build by hand, so tests can be anyone. undici's MockAgent intercepts the downstream fetch calls. Here are the tasks team's tests:
// packages/bff/src/trpc/routers/tasks.test.ts
const createCaller = createCallerFactory(appRouter);
const ada = (): Context => ({
session: { id: 's1', data: { user: { sub: 'ada', name: 'Ada' },
tokens: { accessToken: 'tok', expiresAt: Date.now() + 60_000 }, createdAt: Date.now() } },
getAccessToken: async () => 'tok-ada',
requestId: 'req-42',
});
test('list shapes downstream tasks and forwards token and request id', async () => {
agent.get('http://localhost:4810').intercept({ path: '/tasks' }).reply((opts) => {
seen.push(opts.headers as Record<string, string>);
return { statusCode: 200, data: { items: [{ id: 't1', title: 'A', done: false, owner: 'ada' }] } };
});
assert.deepEqual(await createCaller(ada()).tasks.list(), [{ id: 't1', title: 'A', done: false }]);
assert.equal(seen[0].authorization, 'Bearer tok-ada');
assert.equal(seen[0]['x-request-id'], 'req-42');
});
test('a slow service becomes GATEWAY_TIMEOUT', async () => {
agent.get('http://localhost:4810').intercept({ path: '/tasks' }).reply(200, { items: [] }).delay(3000);
await assert.rejects(createCaller(ada()).tasks.list(), (e: any) => e.code === 'GATEWAY_TIMEOUT');
});The full suite:
ok 1 - list shapes downstream tasks and forwards token and request id
ok 2 - signed-out callers get UNAUTHORIZED
ok 3 - a failing service becomes BAD_GATEWAY
ok 4 - a slow service becomes GATEWAY_TIMEOUT
ok 5 - empty titles never reach the service
# pass 5These five tests cover the shaping (no owner field), the token and request id forwarding, the middleware, the error mapping from Day 4 and the Zod validation. They need no browser, no identity provider and no tasks API.
The beforeEach hook installs the mock agent with disableNetConnect(), so any unmocked call fails the test. The router's create procedure publishes to Redis, so the test re-enables just that one connection with agent.enableNetConnect('localhost:6390'), and runs against a local Redis.
Contract tests for the micro-frontends
The mount contract harness from the micro-frontends course applies unchanged: load a page with the real import map, mount each micro-frontend with fixture props, unmount it, and check that the element is empty and no window listeners leaked.
One addition for this stack: mock the BFF in the harness with Playwright's page.route('/trpc/', ...), returning canned tRPC responses. The micro-frontend then renders real data shapes without a running BFF. Keep the canned responses in the BFF package, generated from its test fixtures, so they can't drift from the real router's output.
End-to-end journeys through real sign-in
A few Playwright tests run the whole stack: a local identity provider, the tasks API, Redis, two BFF instances and the built micro-frontends. This course's development setup does exactly that from one script. The suite covers the journeys that cross the most boundaries:
1 signed out: Please sign in to see your tasks.
2 after sign-in: url /tasks | header: Ada Lovelace
3 tasks: [ '[ ] Wire up tRPC' ] | validation: Title is required
4 other instance, live: [ '[ ] Wire up tRPC', '[ ] Seen on instance two' ]
5 header after rename: Ada L.
7 dialog: Your session has ended. Please sign in again.
7 redirected to identity provider: 127.0.0.1:4800
errors: noneThat one run proves sign-in with a returnTo, a typed query and mutation through the CSRF check, Zod messages reaching the UI, live updates across BFF instances, a cross-team event updating the shell, and the session-expiry flow. It also caught the shared-encryption-key bug from Day 7, which no unit test would have found.
Keep the end-to-end suite small. These tests are slow and need the whole environment, so reserve them for journeys where the risk is in how the pieces connect.
Security tests
Add the attacker tests from the BFF course to the platform pipeline, adjusted for tRPC:
POST /trpc/tasks.createwithoutx-csrfreturns403.- A cross-site page's
fetchto/trpc/tasks.createwithcredentials: 'include'and the header is blocked by the preflight. - A cross-site form
POSTto/trpc/tasks.createreturns403. - An event-stream
GETwithout the header passes the CSRF check by design, so confirm it can only read: it returnsUNAUTHORIZEDwithout a session, and no procedure reachable that way changes data.
appRouter the micro-frontends' types come from. If a test needs a fake router, the test is checking something other than what ships.Check yourself
They run procedures in-process with a hand-built context and mocked downstream calls, so they need no HTTP server, browser, identity provider or real services.
Any downstream call the test forgot to mock fails loudly instead of silently reaching a real service, where it could pass or fail by luck or even change real data. The router tests re-enable exactly one connection, the local Redis on port 6390, because create publishes events there.
The second BFF instance couldn't decrypt sessions, because each instance generated its own random token encryption key. No unit test could see it, since it only appears when two real instances share one Redis. That's exactly the kind of wiring bug end-to-end tests are for.
Mocking lets each micro-frontend be mounted and checked in a browser without a running BFF. The canned responses should come from the BFF package's own test fixtures, so they always match the real router's output shapes instead of drifting.
For example: a POST /trpc/tasks.create without the x-csrf header must return 403, and a cross-site page's fetch with the header must be blocked by the preflight. These tests make sure nobody weakens the CSRF hook or adds CORS by accident.