You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为复选框错误验证编写Jest+React Testing Library单元测试用例

用Jest和React Testing Library实现条款同意校验的单元测试

测试场景

当用户未勾选“同意条款”复选框就点击Next按钮时,页面需显示错误提示Please agree the terms before proceeding;勾选复选框后点击Next,错误提示不显示。

测试代码(Terms.test.tsx)

import { render, screen, fireEvent } from '@testing-library/react';
import Terms from './Terms';

describe('Terms Component', () => {
  test('未同意条款时点击Next显示错误提示', () => {
    render(<Terms />);
    
    // 获取Next按钮并模拟点击
    const nextButton = screen.getByRole('button', { name: /next/i });
    fireEvent.click(nextButton);
    
    // 断言错误提示已渲染
    const errorMessage = screen.getByText(/Please agree the terms before proceeding/i);
    expect(errorMessage).toBeInTheDocument();
  });

  test('同意条款后点击Next不显示错误提示', () => {
    render(<Terms />);
    
    // 勾选同意条款复选框
    const termsCheckbox = screen.getByRole('checkbox');
    fireEvent.click(termsCheckbox);
    
    // 点击Next按钮
    const nextButton = screen.getByRole('button', { name: /next/i });
    fireEvent.click(nextButton);
    
    // 断言错误提示未渲染
    const errorMessage = screen.queryByText(/Please agree the terms before proceeding/i);
    expect(errorMessage).not.toBeInTheDocument();
  });
});

关键逻辑说明

  • 渲染组件:使用render(<Terms />)挂载待测试组件
  • 元素查询:采用React Testing Library推荐的getByRole、getByText等查询方式,模拟用户实际交互视角定位元素
  • 事件模拟:通过fireEvent.click模拟用户点击复选框和按钮的操作
  • 断言判断:
    • getByText用于确认元素存在(找不到会抛出错误)
    • queryByText用于确认元素不存在(找不到返回null,适合否定断言)

运行测试

确保项目已安装@testing-library/react、@testing-library/jest-dom及Jest依赖(Create React App默认已配置),执行以下命令运行测试:

npm test
# 或
yarn test

内容的提问来源于stack exchange,提问作者KnightCrawler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:32:11