Mockowanie kontekstu i zależności w testach tRPC
Izoluj procedury od rzeczywistych baz danych i usług, mockując w testach kontekst tRPC, sesje oraz zależności zewnętrzne.
Mockowanie kontekstu i zależności w testach tRPC to bezpłatna lekcja tRPC End-to-End Type Safe APIs na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej tRPC End-to-End Type Safe APIs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs tRPC End-to-End Type Safe APIs zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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.
Ucz się tRPC End-to-End Type Safe APIs dzięki korepetycjom AI — za darmo
Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.
- Kursy
- 10
- Lekcje
- 40
Często zadawane pytania
Czy lekcja „Mockowanie kontekstu i zależności w testach tRPC” jest bezpłatna?
Tak — pełny tekst „Mockowanie kontekstu i zależności w testach tRPC” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu tRPC End-to-End Type Safe APIs, przejdź na CoddyKit PRO. Kurs tRPC End-to-End Type Safe APIs zawiera 4 lekcji w sumie.
Co nauczysz się w „Mockowanie kontekstu i zależności w testach tRPC”?
Izoluj procedury od rzeczywistych baz danych i usług, mockując w testach kontekst tRPC, sesje oraz zależności zewnętrzne. Ćwiczysz tRPC End-to-End Type Safe APIs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć tRPC End-to-End Type Safe APIs?
Nie wymagamy żadnego doświadczenia. tRPC End-to-End Type Safe APIs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Mockowanie kontekstu i zależności w testach tRPC”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji tRPC End-to-End Type Safe APIs?
Tak. Każda lekcja tRPC End-to-End Type Safe APIs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Testy jednostkowe procedur tRPC
- Testy integracyjne routerów tRPC
- Strategie testów end-to-end
- Mockowanie kontekstu i zależności w testach tRPC