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

如何使用Jest和Enzyme测试React组件是否按props条件渲染?

首先确保你已经完成Jest、Enzyme以及对应React版本适配器的基础配置,我们可以通过浅渲染(shallow render)Parent组件,传入不同props后校验子组件是否存在来实现测试,测试文件命名为Parent.test.js,代码如下:

import React from 'react';
import { shallow } from 'enzyme';
import Parent from './Parent';
import Child1 from './Child1';
import Child2 from './Child2';

describe('Parent 组件渲染逻辑测试', () => {
  it('当传入props.number为"one"时,仅渲染Child1组件', () => {
    const wrapper = shallow(<Parent number="one" word="hello" />);
    // 校验Child1存在,Child2不存在
    expect(wrapper.find(Child1).exists()).toBeTruthy();
    expect(wrapper.find(Child2).exists()).toBeFalsy();
  });

  it('当传入props.number为"two"时,仅渲染Child2组件', () => {
    const wrapper = shallow(<Parent number="two" word="hello" />);
    // 校验Child2存在,Child1不存在
    expect(wrapper.find(Child2).exists()).toBeTruthy();
    expect(wrapper.find(Child1).exists()).toBeFalsy();
  });

  // 可选测试用例:传入其他number值时两个子组件都不渲染
  it('当传入props.number为非"one"/"two"值时,不渲染任何子组件', () => {
    const wrapper = shallow(<Parent number="three" word="hello" />);
    expect(wrapper.find(Child1).exists()).toBeFalsy();
    expect(wrapper.find(Child2).exists()).toBeFalsy();
  });
});

说明

  • 这里用shallow浅渲染是因为我们只需要校验Parent组件的逻辑,不需要关心Child1/Child2的内部渲染逻辑,性能更高也更符合单元测试的隔离原则
  • wrapper.find(组件构造函数).exists()是Enzyme提供的API,用来判断匹配的组件是否存在于渲染树中,返回布尔值,直接作为断言的判断依据即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:18:01