Имитация контекста и зависимостей в тестах tRPC
Изолируйте процедуры от реальных баз данных и служб, имитируя контекст tRPC, сеансы и внешние зависимости в тестах.
«Имитация контекста и зависимостей в тестах tRPC» — бесплатный урок tRPC End-to-End Type Safe APIs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения tRPC End-to-End Type Safe APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс tRPC End-to-End Type Safe APIs содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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.
Часто задаваемые вопросы
Урок «Имитация контекста и зависимостей в тестах tRPC» бесплатный?
Да — полный текст урока «Имитация контекста и зависимостей в тестах tRPC» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс tRPC End-to-End Type Safe APIs, подпишись на CoddyKit PRO. Курс tRPC End-to-End Type Safe APIs содержит 4 уроков всего.
Чему я научусь в уроке «Имитация контекста и зависимостей в тестах tRPC»?
Изолируйте процедуры от реальных баз данных и служб, имитируя контекст tRPC, сеансы и внешние зависимости в тестах. Ты практикуешь tRPC End-to-End Type Safe APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать tRPC End-to-End Type Safe APIs?
Предыдущий опыт не требуется. tRPC End-to-End Type Safe APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Имитация контекста и зависимостей в тестах tRPC»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке tRPC End-to-End Type Safe APIs?
Да. Каждый урок tRPC End-to-End Type Safe APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Модульное тестирование процедур tRPC
- Интеграционное тестирование маршрутизаторов tRPC
- Стратегии сквозного тестирования
- Имитация контекста и зависимостей в тестах tRPC