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

Enzyme+Jest如何为React组件div内调用的函数编写单元测试

问题原因

wrapper.instance() 返回null不是写法错误,核心原因是你使用的是函数式组件:Enzyme浅渲染的instance()方法仅对类组件有效,函数式组件不存在组件实例,调用这个接口必然返回null,自然也没法直接spy组件内部定义的renderError函数。

另外你的测试思路本身存在偏差:组件内部定义的私有函数属于实现细节,单元测试不需要单独验证内部函数有没有被调用,只需要验证不同输入下组件的渲染输出是否符合预期即可——就算后续你把renderError改成内联JSX、修改函数名,只要渲染行为不变,测试用例就不应该失败。

正确测试写法

你只需要传入不同的error状态,断言最终渲染的DOM结构是否符合逻辑即可,不需要直接访问内部方法,参考用例如下:

import { shallow } from 'enzyme';
import ActionButtons from '你的组件路径/ActionButtons';
import Notification from '你的组件路径/Notification'; // 替换为项目内Notification组件的实际引入路径

describe('ActionButtons 错误提示渲染逻辑', () => {
  it('isError为true且错误来源为fromDraft时,渲染对应警告提示', () => {
    const testErrMsg = '草稿内容提交失败';
    const wrapper = shallow(
      <ActionButtons
        {...defaultProps}
        error={{
          isError: true,
          errorMessage: testErrMsg,
          errorFromWhere: 'fromDraft'
        }}
      />
    );

    // 验证错误容器存在
    const errorWrap = wrapper.find('.action-button-error');
    expect(errorWrap.exists()).toBeTruthy();

    // 验证Notification组件参数正确
    const notice = errorWrap.find(Notification);
    expect(notice.exists()).toBeTruthy();
    expect(notice.prop('type')).toBe('warning');
    expect(notice.prop('text')).toBe(testErrMsg);
  });

  it('不满足错误展示条件时,不渲染错误提示', () => {
    // 场景1:isError为false
    const wrapper1 = shallow(
      <ActionButtons
        {...defaultProps}
        error={{
          isError: false,
          errorMessage: 'test',
          errorFromWhere: 'fromDraft'
        }}
      />
    );
    expect(wrapper1.find('.action-button-error').exists()).toBeFalsy();

    // 场景2:错误来源不是fromDraft
    const wrapper2 = shallow(
      <ActionButtons
        {...defaultProps}
        error={{
          isError: true,
          errorMessage: 'test',
          errorFromWhere: 'otherSource'
        }}
      />
    );
    expect(wrapper2.find('.action-button-error').exists()).toBeFalsy();
  });
});
补充说明

如果你的error状态不是从props传入,而是从redux、useContext等钩子获取,只需要在测试时mock对应钩子的返回值即可,整体测试逻辑不变:控制错误状态的不同取值,验证最终渲染结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 03:51:24