tRPC End-to-End Type Safe APIs · Lezione

Mocking del contesto e delle dipendenze nei test tRPC

Isoli le procedure da database e servizi reali simulando nei test il contesto tRPC, le sessioni e le dipendenze esterne.

Lezione 4 di 413 passaggi

Mocking del contesto e delle dipendenze nei test tRPC è una lezione tRPC End-to-End Type Safe APIs gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento tRPC End-to-End Type Safe APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso tRPC End-to-End Type Safe APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 client
  • session — the authenticated user
  • headers — 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 createCaller to call procedures directly
  • Stub return values and assert on inputs

Your unit tests are now fast and dependency-free.

Gratis per iniziare

Impara tRPC End-to-End Type Safe APIs con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
10
Lezioni
40

Domande Frequenti

La lezione «Mocking del contesto e delle dipendenze nei test tRPC» è gratuita?

Sì — il testo completo di «Mocking del contesto e delle dipendenze nei test tRPC» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso tRPC End-to-End Type Safe APIs, passa a CoddyKit PRO. Il corso tRPC End-to-End Type Safe APIs include 4 lezioni in totale.

Cosa imparerò in «Mocking del contesto e delle dipendenze nei test tRPC»?

Isoli le procedure da database e servizi reali simulando nei test il contesto tRPC, le sessioni e le dipendenze esterne. Eserciti tRPC End-to-End Type Safe APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare tRPC End-to-End Type Safe APIs?

Non è richiesta alcuna esperienza precedente. tRPC End-to-End Type Safe APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Mocking del contesto e delle dipendenze nei test tRPC»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione tRPC End-to-End Type Safe APIs?

Sì. Ogni lezione tRPC End-to-End Type Safe APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Unit test delle procedure tRPC
  2. Test di integrazione dei router tRPC
  3. Strategie di test end-to-end
  4. Mocking del contesto e delle dipendenze nei test tRPC
← Torna a tRPC End-to-End Type Safe APIs