tRPCテストでのコンテキストと依存関係のモック
テストでtRPCのコンテキスト、セッション、外部依存関係をモックし、プロシージャを実際のデータベースやサービスから分離します。
「tRPCテストでのコンテキストと依存関係のモック」はCoddyKit上の無料tRPC End-to-End Type Safe APIsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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 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時間対応のAIチューター)、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時間対応の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フィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- tRPCプロシージャの単体テスト
- tRPCルーターの統合テスト
- エンドツーエンドテスト戦略
- tRPCテストでのコンテキストと依存関係のモック