Enzyme无法渲染组件:依赖未定义报错解决方案咨询
解决React组件测试中
TypeError: Cannot read property 'medium' of undefined的问题 你遇到的问题核心是测试环境下,自定义的media媒体查询模块没有被正确初始化或加载,导致styled-components调用media.medium时找不到对应属性。下面给你几个实用的解决方案:
方案1:在测试文件中直接Mockmedia模块
这是最直接的方式,用Jest的jest.mock方法模拟css模块的导出,让测试时使用我们自定义的media对象:
import React from 'react'; import { shallow } from 'enzyme'; import { css } from 'styled-components'; import MyComponent from 'components/MyComponent'; // Mock css模块的media对象,模拟其方法返回有效css片段 jest.mock('css', () => ({ media: { medium: (...args) => css`${css(...args)}`, large: (...args) => css`${css(...args)}` } })); describe('<MyComponent />', () => { it('should match the snapshot', () => { const snap = shallow(<MyComponent />); expect(snap).toMatchSnapshot(); }); });
这个方法仅对当前测试文件生效,不会干扰其他组件的测试。
方案2:创建全局Mock模块
如果多个组件都依赖这个media模块,可以创建全局Mock来避免重复代码:
- 在项目根目录下创建
__mocks__/css/index.js文件(路径要和你实际的css模块路径对应) - 在该文件中编写Mock的
media对象:
import { css } from 'styled-components'; export const media = { small: (...args) => css`${css(...args)}`, medium: (...args) => css`${css(...args)}`, large: (...args) => css`${css(...args)}` };
- 在测试文件中调用
jest.mock('css'),即可自动使用这个全局Mock:
import React from 'react'; import { shallow } from 'enzyme'; import MyComponent from 'components/MyComponent'; // 自动加载__mocks__目录下的css模块 jest.mock('css'); describe('<MyComponent />', () => { it('should match the snapshot', () => { const snap = shallow(<MyComponent />); expect(snap).toMatchSnapshot(); }); });
方案3:排查模块导入路径
有时候测试环境的模块解析规则和开发环境有差异,你可以尝试把import { media } from 'css'改成相对路径(比如import { media } from '../css'),确认是否是路径解析问题导致模块未正确加载。
另外,别忘了确认jest-styled-components和Enzyme适配器的配置是否正确——比如在测试启动文件(如setupTests.js)中已经引入jest-styled-components,并且Enzyme适配器已经配置完成,这些基础配置也会影响styled-components的测试表现。
内容的提问来源于stack exchange,提问作者Matt Greenberg
相关产品推荐
相关产品推荐

