0Pricing
tRPC End-to-End Type Safe APIs · 강의

tRPC 테스트에서 컨텍스트와 종속성 모킹하기

테스트에서 tRPC 컨텍스트, 세션, 외부 종속성을 모킹해 실제 데이터베이스와 서비스로부터 프로시저를 격리합니다.

tRPC 테스트에서 컨텍스트와 종속성 모킹하기은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 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.

자주 묻는 질문

“tRPC 테스트에서 컨텍스트와 종속성 모킹하기” 강의는 무료인가요?

네 — “tRPC 테스트에서 컨텍스트와 종속성 모킹하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“tRPC 테스트에서 컨텍스트와 종속성 모킹하기”에서 뭘 배우나요?

테스트에서 tRPC 컨텍스트, 세션, 외부 종속성을 모킹해 실제 데이터베이스와 서비스로부터 프로시저를 격리합니다. 브라우저에서 직접 실행하는 실습 코드로 tRPC End-to-End Type Safe APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

tRPC End-to-End Type Safe APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 tRPC End-to-End Type Safe APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“tRPC 테스트에서 컨텍스트와 종속성 모킹하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 tRPC End-to-End Type Safe APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 tRPC End-to-End Type Safe APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. tRPC 절차 단위 테스트
  2. tRPC 라우터 통합 테스트
  3. 종단 간 테스트 전략
  4. tRPC 테스트에서 컨텍스트와 종속성 모킹하기
← tRPC End-to-End Type Safe APIs(으)로 돌아가기