0Pricing
tRPC End-to-End Type Safe APIs · درس

محاكاة السياق والتبعيات في اختبارات 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 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) وفتح باقي دورة 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 يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. اختبار وحدات إجراءات tRPC
  2. اختبار تكامل أجهزة توجيه tRPC
  3. استراتيجيات الاختبار من البداية إلى النهاية
  4. محاكاة السياق والتبعيات في اختبارات tRPC
← العودة إلى tRPC End-to-End Type Safe APIs