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

如何使用Jest和Enzyme为简单React组件编写测试用例

如何用Jest和Enzyme测试你的React类组件?

嘿,这就来一步步教你给这个New_Component写测试用例,咱们从依赖准备到具体测试场景全覆盖,保证组件的行为符合预期~

第一步:确保依赖已安装

首先得确保你的项目里已经装了Jest、Enzyme,还有对应React版本的适配器(比如你用React 16的话,就装enzyme-adapter-react-16)。如果还没装,执行下面的命令:

npm install --save-dev jest enzyme enzyme-adapter-react-16 react-test-renderer

第二步:配置Enzyme适配器

在项目根目录或者src文件夹下创建setupTests.js文件,用来配置Enzyme的适配器,这样所有测试文件都会自动加载这个配置:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16'; // 换成你React版本对应的适配器

configure({ adapter: new Adapter() });

第三步:编写测试用例

创建测试文件New_Component.test.js,咱们覆盖三个核心测试场景:

1. 测试组件正确渲染所有Props内容

这是最基础的单元测试,验证组件能把传入的props正确渲染到对应的标签里:

import React from 'react';
import { shallow } from 'enzyme';
import New_Component from './New_Component';

describe('New_Component', () => {
  // 定义模拟的props数据
  const mockProps = {
    name: 'Pranami',
    mobile: 1234567890,
    address: '123 Test Street, Example City'
  };

  it('should render all prop values correctly', () => {
    // 用shallow渲染组件(只渲染当前组件,不涉及子组件,适合单元测试)
    const wrapper = shallow(<New_Component {...mockProps} />);

    // 验证h1标签显示正确的name
    expect(wrapper.find('h1').text()).toBe(mockProps.name);
    // 注意mobile是数字,要转成字符串再匹配
    expect(wrapper.find('h6').text()).toBe(mockProps.mobile.toString());
    // 验证p标签显示正确的address
    expect(wrapper.find('p').text()).toBe(mockProps.address);
  });

2. 测试PropTypes必填校验

你的组件定义了三个必填props,咱们要验证当这些props缺失时,React会抛出对应的警告(注意:PropTypes校验只在开发环境生效):

it('should trigger warnings when required props are missing', () => {
    // 先保存原始的console.error,避免测试影响控制台输出
    const originalConsoleError = console.error;
    // 用Jest mock掉console.error,方便捕获警告信息
    console.error = jest.fn();

    // 不传任何props渲染组件
    shallow(<New_Component />);

    // 验证是否触发了PropTypes的必填警告
    expect(console.error).toHaveBeenCalled();
    // 更精确地验证每个必填prop的警告都存在
    expect(console.error.mock.calls.some(call => 
      call[0].includes('name') && call[0].includes('isRequired')
    )).toBe(true);
    expect(console.error.mock.calls.some(call => 
      call[0].includes('mobile') && call[0].includes('isRequired')
    )).toBe(true);
    expect(console.error.mock.calls.some(call => 
      call[0].includes('address') && call[0].includes('isRequired')
    )).toBe(true);

    // 恢复原始的console.error
    console.error = originalConsoleError;
  });

3. 测试组件的DOM结构是否符合预期

验证组件的基本结构是否正确,比如包含一个div容器,以及对应的h1、h6、p标签:

it('should have the correct DOM structure', () => {
    const wrapper = shallow(<New_Component {...mockProps} />);
    
    expect(wrapper.find('div').exists()).toBe(true);
    expect(wrapper.find('h1').exists()).toBe(true);
    expect(wrapper.find('h6').exists()).toBe(true);
    expect(wrapper.find('p').exists()).toBe(true);
  });
});

最后:运行测试

在package.json里添加测试脚本(如果还没有的话):

{
  "scripts": {
    "test": "jest"
  }
}

然后执行npm test就能看到测试结果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:10:43