0Pricing
Next.js 15 Fullstack Web Apps · 课时

模拟与测试服务器组件

通过模拟数据层和网络调用,测试异步服务器组件、服务器操作和路由处理器,让全栈 Next.js 测试保持快速可靠。

模拟与测试服务器组件 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

The Server Component Challenge

Server Components are async and run on the server, so classic client-render test tools do not fit perfectly. The key is to test their data dependencies in isolation and test the rendered output separately.

Separate Logic from Rendering

Extract data-fetching and business logic into plain functions. Pure functions are trivial to unit test without rendering anything.

export function formatPrice(cents) {
  return '$' + (cents / 100).toFixed(2);
}

Testing a Pure Helper

A pure helper is testable anywhere with no mocks at all.

function formatPrice(cents) {
  return '$' + (cents / 100).toFixed(2);
}
console.log(formatPrice(1999) === '$19.99');
console.log(formatPrice(500) === '$5.00');

Mocking the Data Layer

Server Components usually call a repository or ORM. Mock that module so tests do not hit a real database.

import { vi } from 'vitest';
import * as db from '@/lib/db';

vi.spyOn(db, 'getUser').mockResolvedValue({ id: 1, name: 'Ada' });

Rendering an Async Server Component

Because the component is async, you can await it to get its element tree, then assert on it with your render utility.

import { render, screen } from '@testing-library/react';
import Profile from '@/app/profile/page';

it('shows the name', async () => {
  render(await Profile());
  expect(screen.getByText('Ada')).toBeInTheDocument();
});

Mocking fetch with MSW

When a component fetches from an external API, intercept the request with Mock Service Worker (MSW) instead of stubbing fetch by hand.

import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('https://api.example.com/user', () =>
    HttpResponse.json({ name: 'Ada' })
  ),
];

Testing Server Actions

Server Actions are async functions. Call them directly with mocked dependencies and assert on side effects and return values.

import { createTodo } from '@/app/actions';
import * as db from '@/lib/db';

it('creates a todo', async () => {
  const spy = vi.spyOn(db, 'insertTodo').mockResolvedValue({ id: 1 });
  await createTodo('Write tests');
  expect(spy).toHaveBeenCalledWith('Write tests');
});

Mocking revalidatePath

Actions often call revalidatePath. Mock next/cache so the call does not throw outside a request scope, and assert it was invoked.

vi.mock('next/cache', () => ({
  revalidatePath: vi.fn(),
}));

Testing Route Handlers

Route handlers take a Request and return a Response. Build a request, call the handler, and inspect the response.

import { POST } from '@/app/api/todos/route';

it('returns 400 on empty body', async () => {
  const req = new Request('http://t/api/todos', { method: 'POST', body: '{}' });
  const res = await POST(req);
  expect(res.status).toBe(400);
});

Keep Tests Deterministic

Avoid flaky tests:

  • Reset mocks between tests (vi.clearAllMocks()).
  • Freeze time when testing dates.
  • Never call real networks or databases.

The Testing Pyramid

Balance your suite: many fast unit tests for logic, fewer integration tests for components plus data, and a small set of E2E tests (Playwright) for critical flows.

Quick Check

What is the recommended way to test an async Server Component that calls your ORM?

Recap

You learned to test fullstack Next.js code:

  • Separate pure logic for easy unit tests.
  • Mock the data layer and use MSW for network calls.
  • Await async Server Components; call Server Actions and route handlers directly.
  • Keep tests deterministic and follow the testing pyramid.

常见问题解答

「模拟与测试服务器组件」课时是免费的吗?

是的 — 「模拟与测试服务器组件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

「模拟与测试服务器组件」这节课中我会学到什么?

通过模拟数据层和网络调用,测试异步服务器组件、服务器操作和路由处理器,让全栈 Next.js 测试保持快速可靠。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack Web Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「模拟与测试服务器组件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 单元测试与集成测试
  2. 使用 Playwright 进行端到端测试
  3. 单体仓库与微前端
  4. 模拟与测试服务器组件
← 返回 Next.js 15 Fullstack Web Apps