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

使用Enzyme和Jest测试Modal组件时找不到对应类名的解决办法

问题原因

  • 你在初始化测试用的Modal实例时没有传入active={true}属性,Modal组件逻辑为active为假值时直接返回null,没有渲染任何DOM节点,自然无法匹配到目标类名。
  • 你使用了enzyme的shallow渲染方法,该方法只会渲染当前组件的第一层节点,不会渲染子组件的内部内容。你的Modal核心内容全部包裹在FocusTrap组件内部,shallow模式下不会解析FocusTrap的子元素,就算传入了active={true}也找不到内部类名。

修复方案

推荐使用全量渲染的mount方法,同时传入必要的props保证组件正常运行,修正后的测试代码如下:

import React from 'react'
import { mount } from 'enzyme';
import Modal from '../Modal'

// 预设组件正常运行需要的必填props
const defaultProps = {
  active: true,
  onClickClose: jest.fn()
}

describe('Modal', () => {
    it('正常渲染modal背景层', () => {
        const wrapper = mount(<Modal {...defaultProps}/>)
        expect(wrapper.find('.gcs_modal__background')).toHaveLength(1);
    })
    it('active为false时不渲染任何内容', () => {
        const wrapper = mount(<Modal {...defaultProps} active={false}/>)
        expect(wrapper.find('.gcs_modal__background')).toHaveLength(0);
    })
})

如果你坚持要用shallow方法测试,可以通过dive()方法手动渲染FocusTrap的内部内容:

import React from 'react'
import { shallow } from 'enzyme';
import FocusTrap from 'focus-trap-react';
import Modal from '../Modal'

const defaultProps = {
  active: true,
  onClickClose: jest.fn()
}

describe('Modal', () => {
    it('正常渲染modal背景层', () => {
        const wrapper = shallow(<Modal {...defaultProps}/>)
        expect(wrapper.find(FocusTrap).dive().find('.gcs_modal__background')).toHaveLength(1);
    })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:45:00