Mocking Context and Dependencies in tRPC Tests
Isolate procedures from real databases and services by mocking the tRPC context, sessions, and external dependencies in your tests.
Mocking Context and Dependencies in tRPC Tests is a free tRPC End-to-End Type Safe APIs lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the tRPC End-to-End Type Safe APIs learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Mock the Context
tRPC procedures receive a context holding the db client, the user session, and other services. Real tests should not hit a real database. Mocking the context keeps tests fast and deterministic.
What Lives in Context
A typical context includes:
db— the database clientsession— the authenticated userheaders— request metadata
Your createContext function builds this per request.
Building a Test Context
For tests, write a helper that returns a fake context shaped exactly like the real one.
function createTestContext(overrides = {}) {
return {
db: mockDb,
session: null,
...overrides,
};
}Mocking the Database
Replace the db with an object whose methods are test doubles. With Vitest you can use vi.fn().
const mockDb = {
user: { findUnique: vi.fn() },
};Calling a Procedure Directly
Create a caller from your router with the mock context, then invoke procedures like plain functions.
const caller = appRouter.createCaller(createTestContext());
const result = await caller.user.list();Simulating an Authenticated User
To test a protected procedure, pass a session in the context overrides.
const caller = appRouter.createCaller(
createTestContext({ session: { user: { id: 'u1' } } })
);Stubbing Return Values
Tell the mock what to return for a given call so you can assert on the procedure output.
mockDb.user.findUnique.mockResolvedValue({ id: 'u1', name: 'Ada' });Asserting the Call
Verify the procedure actually queried the db with the expected arguments.
expect(mockDb.user.findUnique).toHaveBeenCalledWith({ where: { id: 'u1' } });Testing Error Paths
Make the mock throw to confirm your procedure handles failures and maps them to the right tRPC error code.
mockDb.user.findUnique.mockRejectedValue(new Error('DB down'));
await expect(caller.user.get({ id: 'u1' })).rejects.toThrow();Mocking External Services
Email senders, payment gateways, and other side-effects should also be mocked. Inject them through the context so tests can supply fakes.
const mailer = { send: vi.fn() };
const caller = appRouter.createCaller(createTestContext({ mailer }));Best Practices
Keep mocked tests reliable:
- Mirror the real context shape exactly
- Reset mocks between tests with
vi.clearAllMocks() - Test both success and failure paths
- Assert on inputs, not just outputs
Quick Check
Test your mocking knowledge.
Recap
You learned to isolate tRPC procedures in tests:
- Build a fake context matching the real shape
- Mock the db and external services with
vi.fn() - Use
createCallerto call procedures directly - Stub return values and assert on inputs
Your unit tests are now fast and dependency-free.
Frequently asked questions
Is the “Mocking Context and Dependencies in tRPC Tests” lesson free?
Yes — the full text of “Mocking Context and Dependencies in tRPC Tests” is free to read here on the web, and the tRPC End-to-End Type Safe APIs course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the tRPC End-to-End Type Safe APIs course, upgrade to CoddyKit PRO.
What will I learn in “Mocking Context and Dependencies in tRPC Tests”?
Isolate procedures from real databases and services by mocking the tRPC context, sessions, and external dependencies in your tests. You practise tRPC End-to-End Type Safe APIs with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start tRPC End-to-End Type Safe APIs?
No prior experience is required. tRPC End-to-End Type Safe APIs on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Mocking Context and Dependencies in tRPC Tests” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this tRPC End-to-End Type Safe APIs lesson?
Yes. Every tRPC End-to-End Type Safe APIs lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Unit Testing tRPC Procedures
- Integration Testing tRPC Routers
- End-to-End Testing Strategies
- Mocking Context and Dependencies in tRPC Tests