การจำลองและการทดสอบเส้นทาง API
ทดสอบตัวจัดการเส้นทางและการกระทำฝั่งเซิร์ฟเวอร์ของ Next.js แบบแยกอิสระ ด้วยการจำลองฐานข้อมูล การเรียกเครือข่าย และบริการภายนอกด้วย Jest และ MSW
การจำลองและการทดสอบเส้นทาง API เป็นบทเรียน Next.js 15 Fullstack (App Router + Server Actions) ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 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.mockandmockResolvedValue - 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.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 22
- บทเรียน
- 88
คำถามที่พบบ่อย
บทเรียน “การจำลองและการทดสอบเส้นทาง API” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การจำลองและการทดสอบเส้นทาง API” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack (App Router + Server Actions) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack (App Router + Server Actions) มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การจำลองและการทดสอบเส้นทาง API”
ทดสอบตัวจัดการเส้นทางและการกระทำฝั่งเซิร์ฟเวอร์ของ Next.js แบบแยกอิสระ ด้วยการจำลองฐานข้อมูล การเรียกเครือข่าย และบริการภายนอกด้วย Jest และ MSW คุณปฏิบัติ Next.js 15 Fullstack (App Router + Server Actions) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 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) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การทดสอบหน่วยของคอมโพเนนต์
- การทดสอบการผสานรวมหน้า
- การทดสอบตั้งแต่ต้นจนจบด้วย Playwright/Cypress
- การจำลองและการทดสอบเส้นทาง API