React / 系统课时

编写组件测试

编写组件测试

本课使用 Vitest、jsdom 和 React Testing Library 测试一个客户端计数器,覆盖初始渲染、按钮交互和上限状态,并坚持从用户可见行为而不是组件内部实现细节断言结果。

学习目标

  • 配置 Next.js 项目的 Vitest 测试环境
  • 使用可访问角色查询组件元素
  • 覆盖渲染、交互和边界状态

配置测试环境

安装 vitest、jsdom、@vitejs/plugin-react、vite-tsconfig-paths、@testing-library/react、@testing-library/dom 和 @testing-library/jest-dom。随后创建根目录 vitest.config.mts。

ts
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vitest/config'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [tsconfigPaths(), react()],
  test: {
    environment: 'jsdom',
    globals: true,
    setupFiles: ['./vitest.setup.ts'],
  },
})

创建 vitest.setup.ts,加载 DOM 断言扩展。

ts
import '@testing-library/jest-dom/vitest'

这两个文件属于测试配置。运行测试时能识别 JSX、@/ 路径别名和 toBeInTheDocument 等匹配器,即表示配置生效。

编写待测组件

创建 app/components/counter.tsx。组件允许从初始值递增到指定上限,到达上限后禁用按钮。

tsx
'use client'

import { useState } from 'react'

type CounterProps = {
  initialValue?: number
  max?: number
}

export function Counter({
  initialValue = 0,
  max = 3,
}: CounterProps) {
  const [count, setCount] = useState(initialValue)
  const reachedMax = count >= max

  return (
    <section aria-label="计数器">
      <p aria-live="polite">当前计数:{count}</p>
      <button
        type="button"
        disabled={reachedMax}
        onClick={() => setCount((value) => value + 1)}
      >
        {reachedMax ? '已到上限' : '增加'}
      </button>
    </section>
  )
}

aria-live 让计数变化更容易被辅助技术感知,按钮文案和禁用状态也为测试提供稳定的用户可见依据。

编写行为测试

创建 app/components/counter.test.tsx。测试不读取 Hook 状态,也不查找内部类名,而是通过文本和按钮角色模拟真实用户。

tsx
import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { Counter } from './counter'

describe('Counter', () => {
  it('渲染初始值并在点击后递增', () => {
    render(<Counter initialValue={1} max={3} />)

    expect(
      screen.getByText('当前计数:1'),
    ).toBeInTheDocument()

    fireEvent.click(
      screen.getByRole('button', { name: '增加' }),
    )

    expect(
      screen.getByText('当前计数:2'),
    ).toBeInTheDocument()
  })

  it('达到上限时禁用按钮', () => {
    render(<Counter initialValue={2} max={2} />)

    expect(
      screen.getByRole('button', { name: '已到上限' }),
    ).toBeDisabled()
  })
})

第一个测试覆盖正常交互,第二个测试直接构造边界状态。这样失败时能判断是渲染、事件还是边界规则发生变化。

运行并读取结果

在项目根目录执行一次性测试。

bash
npx vitest run

预期结果为两个测试全部通过,文件路径和耗时会随环境变化。

text
✓ app/components/counter.test.tsx (2 tests)

Test Files  1 passed
Tests       2 passed
Duration    <TIME>

若测试找不到元素,先检查实际可访问名称,而不是立即改用脆弱的 CSS 选择器。若出现 document is not defined,说明测试环境没有正确设置为 jsdom。

确定组件测试边界

组件测试适合验证同步 Server Component、Client Component、纯函数和局部交互。涉及真实路由、Cookie、数据库或多个页面跳转的流程,更适合端到端测试。

异步 Server Component 往往依赖框架运行时,直接放进 jsdom 测试会增加大量模拟。此时可把纯展示部分拆成同步组件单测,把真实数据加载留给浏览器测试验证。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

编写组件测试

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通