0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 课时

页面集成测试

为 Next.js 页面和 API 路由执行集成测试,确保应用的不同部分能够协同工作

页面集成测试 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

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

Intro to Integration Tests

Welcome! In this lesson, we'll explore integration testing for your Next.js applications.

Integration tests verify that different parts of your application work correctly together. Instead of isolated units, we check the flow between components, pages, and API routes.

Why Test Pages & Routes?

For Next.js, integration testing is crucial because it ensures:

  • Pages render correctly with their data.
  • User interactions (like form submissions) trigger the right backend logic.
  • API routes respond as expected when called from the frontend or other services.

It helps catch issues that unit tests might miss when components interact.

Tools: Jest, RTL, next/test-utils

We'll primarily use these tools for integration testing:

  • Jest: A popular JavaScript testing framework.
  • React Testing Library (RTL): For rendering React components (like your Next.js pages) and simulating user interactions.
  • @next/test-utils: Provides helpers specifically for testing Next.js features, like API routes.

Testing a Page Component

To test a Next.js page component, we can render it using React Testing Library. This allows us to assert if the correct content is displayed and interact with elements on the page.

You'll typically import the page component directly and render it in your test file.

Code: Simple Page Test

Here's how you might test a simple About page to ensure its heading is rendered.

// pages/about.js
export default function About() {
  return (
    <div>
      <h1>About Us</h1>
      <p>This is the about page.</p>
    </div>
  );
}

// __tests__/about.test.js
import { render, screen } from '@testing-library/react';
import About from '../pages/about';

describe('About Page', () => {
  it('renders the about page heading', () => {
    render(<About />);
    const heading = screen.getByRole('heading', { name: /About Us/i });
    expect(heading).toBeInTheDocument();
  });
});

User Interaction in Tests

Integration tests often involve simulating user behavior. React Testing Library provides utilities like fireEvent (or userEvent for more realistic interactions) to click buttons, type into inputs, and more.

This lets you verify that your page responds correctly to user input, just like a real user would.

// components/Counter.js
import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

// __tests__/counter.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from '../components/Counter';

describe('Counter Component', () => {
  it('increments count on button click', () => {
    render(<Counter />);
    const button = screen.getByRole('button', { name: /Increment/i });
    fireEvent.click(button);
    expect(screen.getByText(/Count: 1/i)).toBeInTheDocument();
  });
});

Testing Next.js API Routes

Next.js API routes are server-side functions. You can test them by importing their handler function and using createNextApiHandler from @next/test-utils to simulate requests.

This allows you to send mock requests and assert the status code and JSON response.

// pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' });
}

// __tests__/api/hello.test.js
import { createNextApiHandler } from '@next/test-utils';
import handler from '../../pages/api/hello';

describe('/api/hello', () => {
  it('returns a name', async () => {
    const testHandler = createNextApiHandler(handler);
    const res = await testHandler({ method: 'GET' });
    expect(res.statusCode).toBe(200);
    expect(await res.json()).toEqual({ name: 'John Doe' });
  });
});

Mocking External Calls in API

API routes often interact with databases or other external services. In integration tests, you should mock these external dependencies to ensure your tests are fast and predictable.

Jest's mocking capabilities are perfect for this, allowing you to control the return values of these external calls.

// lib/db.js (simplified)
export const getUser = async (id) => ({ id, name: 'Mock User' });

// pages/api/user/[id].js
import { getUser } from '../../../lib/db';

export default async function handler(req, res) {
  const { id } = req.query;
  const user = await getUser(id);
  res.status(200).json(user);
}

// __tests__/api/user.test.js
import { createNextApiHandler } from '@next/test-utils';
import handler from '../../pages/api/user/[id]';
import * as db from '../../lib/db';

describe('/api/user/[id]', () => {
  it('returns a user with mocked DB', async () => {
    jest.spyOn(db, 'getUser').mockResolvedValue({ id: '1', name: 'Test User' });

    const testHandler = createNextApiHandler(handler);
    const res = await testHandler({ method: 'GET', query: { id: '1' } });
    expect(res.statusCode).toBe(200);
    expect(await res.json()).toEqual({ id: '1', name: 'Test User' });

    jest.restoreAllMocks();
  });
});

Pages & Server Actions Integration

Testing pages that use Server Actions involves rendering the page, simulating a form submission, and asserting that the Server Action was called with the correct data.

You can mock the Server Action function itself to control its return value and verify it was invoked.

// app/actions.js
'use server';
export async function submitForm(formData) {
  const name = formData.get('name');
  return { success: true, message: `Hello, ${name}!` };
}

// app/page.js
import { submitForm } from './actions';

export default function Page() {
  return (
    <form action={submitForm}>
      <input type="text" name="name" defaultValue="Guest" />
      <button type="submit">Say Hello</button>
    </form>
  );
}

// __tests__/page.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import Page from '../app/page';
import * as actions from '../app/actions';

describe('Home Page with Server Action', () => {
  it('submits form and calls server action', async () => {
    const mockSubmitForm = jest.spyOn(actions, 'submitForm')
      .mockResolvedValue({ success: true, message: 'Hello, Test User!' });

    render(<Page />);

    const input = screen.getByRole('textbox', { name: /name/i });
    fireEvent.change(input, { target: { value: 'Test User' } });

    const button = screen.getByRole('button', { name: /Say Hello/i });
    fireEvent.click(button);

    expect(mockSubmitForm).toHaveBeenCalledWith(
      expect.any(FormData)
    );
    mockSubmitForm.mockRestore();
  });
});

Test Your Knowledge

Time for a quick check on integration testing!

Recap: Building Robust Apps

Great job! You've learned the fundamentals of integration testing in Next.js.

  • We covered how to test pages and API routes.
  • You saw how to simulate user interactions and mock external dependencies.
  • Tools like Jest, React Testing Library, and @next/test-utils are essential.

By writing integration tests, you build more robust applications and catch bugs earlier in the development process!

常见问题解答

「页面集成测试」课时是免费的吗?

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

「页面集成测试」这节课中我会学到什么?

为 Next.js 页面和 API 路由执行集成测试,确保应用的不同部分能够协同工作 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?

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

「页面集成测试」课时需要多长时间?

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

我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?

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

此课程中的所有课时

  1. 组件单元测试
  2. 页面集成测试
  3. 使用 Playwright/Cypress 进行端到端测试
  4. 模拟与测试 API 路由
← 返回 Next.js 15 Fullstack (App Router + Server Actions)