0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · درس

محاكاة واختبار مسارات API

اختبر Route Handlers وServer Actions في Next.js بشكل معزول عبر محاكاة قاعدة البيانات، واستدعاءات الشبكة، والخدمات الخارجية باستخدام Jest وMSW.

محاكاة واختبار مسارات API درس مجاني في Next.js 15 Fullstack (App Router + Server Actions) على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Next.js 15 Fullstack (App Router + Server Actions)، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Next.js 15 Fullstack (App Router + Server Actions) 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why Mock?

Tests should be fast, deterministic, and isolated. Mocking replaces slow or external dependencies — databases, payment APIs, email senders — with controllable stand-ins so a single failure does not break unrelated tests.

What to Mock

Good mock targets in a Next.js app:

  • The database client (Prisma)
  • External HTTP calls (Stripe, OpenAI)
  • Auth/session helpers

Keep the route's own logic real so you actually test it.

A Simple Route Handler

Here is a route we want to test. It reads a query param and returns JSON.

// app/api/user/route.ts
import { prisma } from '@/lib/prisma';
export async function GET(req: Request) {
  const users = await prisma.user.findMany();
  return Response.json(users);
}

Mocking Prisma with Jest

jest.mock replaces a module. Mock the Prisma module so calls return fixed data instead of hitting a real database.

jest.mock('@/lib/prisma', () => ({
  prisma: {
    user: { findMany: jest.fn() }
  }
}));

Setting Return Values

In each test, tell the mock what to resolve with using mockResolvedValue. This drives the route down a specific path.

import { prisma } from '@/lib/prisma';
(prisma.user.findMany as jest.Mock).mockResolvedValue([
  { id: 1, name: 'Ada' }
]);

Invoking the Handler

Route Handlers are plain functions. Call them directly with a Request and assert on the returned Response.

import { GET } from '@/app/api/user/route';
const res = await GET(new Request('http://test/api/user'));
const data = await res.json();
expect(data[0].name).toBe('Ada');

Asserting Call Behavior

Verify the mock was used correctly with matchers like toHaveBeenCalledWith. This confirms your route passes the right arguments.

expect(prisma.user.findMany).toHaveBeenCalledTimes(1);

Mocking External HTTP with MSW

For outbound calls, MSW (Mock Service Worker) intercepts requests at the network layer. Define handlers that return canned responses.

import { http, HttpResponse } from 'msw';
export const handlers = [
  http.get('https://api.stripe.com/v1/charges', () =>
    HttpResponse.json({ amount: 500 })
  )
];

Starting the Mock Server

Boot the MSW server in your test setup so every test runs against the mocked network. Reset handlers between tests for isolation.

import { setupServer } from 'msw/node';
const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Testing Error Paths

Make mocks reject or return errors to test how your route handles failures, ensuring it returns the right status code.

(prisma.user.findMany as jest.Mock).mockRejectedValue(new Error('db down'));
const res = await GET(new Request('http://test/api/user'));
expect(res.status).toBe(500);

Best Practices

Keep mocked tests trustworthy:

  • Mock the edges, keep logic real
  • Reset mocks between tests
  • Cover success and error paths
  • Use MSW for realistic network mocking

Quick Check

Test your mocking knowledge.

Recap

You learned to test routes in isolation:

  • Mock the Prisma client with jest.mock and mockResolvedValue
  • Call Route Handlers directly and assert on the Response
  • Intercept outbound HTTP with MSW
  • Cover error paths by making mocks reject

Your API tests are now fast and reliable.

الأسئلة الشائعة

هل درس «محاكاة واختبار مسارات API» مجاني؟

نعم — نص درس «محاكاة واختبار مسارات API» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Next.js 15 Fullstack (App Router + Server Actions)، انتقل إلى CoddyKit PRO. تتضمن دورة Next.js 15 Fullstack (App Router + Server Actions) 4 دروس في المجموع.

ماذا ستتعلم في «محاكاة واختبار مسارات API»؟

اختبر Route Handlers وServer Actions في Next.js بشكل معزول عبر محاكاة قاعدة البيانات، واستدعاءات الشبكة، والخدمات الخارجية باستخدام Jest وMSW. تتمرن على Next.js 15 Fullstack (App Router + Server Actions) مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Next.js 15 Fullstack (App Router + Server Actions)؟

لا تُشترط خبرة سابقة. Next.js 15 Fullstack (App Router + Server Actions) على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «محاكاة واختبار مسارات API»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Next.js 15 Fullstack (App Router + Server Actions) هذا؟

نعم. كل درس في Next.js 15 Fullstack (App Router + Server Actions) يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

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

  1. اختبار الوحدات للمكوّنات
  2. اختبار التكامل للصفحات
  3. اختبارات شاملة باستخدام Playwright/Cypress
  4. محاكاة واختبار مسارات API
← العودة إلى Next.js 15 Fullstack (App Router + Server Actions)