MST

星途 面试题库

面试题:React组件测试中Jest和Enzyme的常用结合方式

在React组件测试场景下,阐述Jest和Enzyme如何配合使用来对一个简单的无状态函数组件进行渲染测试、交互模拟测试,假设该组件接收一个props属性并在界面上展示,请给出关键代码示例。
15.7万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试
  1. 安装依赖
    • 首先确保项目中安装了jestenzyme以及相关适配器。
    • 对于React项目,通常安装@testing - library/reactenzymeenzyme - adapter - react - 16(根据React版本选择合适的适配器)。
    npm install --save - dev jest @testing - library/react enzyme enzyme - adapter - react - 16
    
  2. 编写无状态函数组件
    • 假设组件名为SimpleComponent,接收一个text属性并展示在界面上。
    import React from'react';
    
    const SimpleComponent = ({ text }) => {
        return <div>{text}</div>;
    };
    
    export default SimpleComponent;
    
  3. 编写测试用例
    • 渲染测试
      • 使用@testing - library/reactrender函数或enzymeshallow函数进行渲染测试。
      • 使用jest来断言渲染结果。
    import React from'react';
    import { render } from '@testing - library/react';
    import SimpleComponent from './SimpleComponent';
    import { shallow } from 'enzyme';
    
    describe('SimpleComponent', () => {
        it('should render correctly with props', () => {
            // 使用@testing - library/react渲染
            const { getByText } = render(<SimpleComponent text="test text" />);
            expect(getByText('test text')).toBeInTheDocument();
    
            // 使用enzyme shallow渲染
            const wrapper = shallow(<SimpleComponent text="test text" />);
            expect(wrapper.text()).toContain('test text');
        });
    });
    
    • 交互模拟测试
      • 由于SimpleComponent是无交互的简单展示组件,这里假设它有一个点击事件处理函数。首先修改组件添加点击处理逻辑。
    import React from'react';
    
    const SimpleComponent = ({ text, onClick }) => {
        return <div onClick={onClick}>{text}</div>;
    };
    
    export default SimpleComponent;
    
    • 然后编写测试用例模拟点击交互:
    import React from'react';
    import { render } from '@testing - library/react';
    import SimpleComponent from './SimpleComponent';
    import { shallow } from 'enzyme';
    
    describe('SimpleComponent', () => {
        it('should call onClick function on click', () => {
            const mockOnClick = jest.fn();
            const wrapper = shallow(<SimpleComponent text="test text" onClick={mockOnClick} />);
            wrapper.find('div').simulate('click');
            expect(mockOnClick).toHaveBeenCalled();
        });
    });
    

在上述测试代码中:

  • 使用@testing - library/reactrender函数和getByText方法断言文本是否在文档中,进行渲染测试。
  • 使用enzymeshallow函数渲染组件,text方法获取组件文本内容进行渲染测试。
  • 使用enzymesimulate方法模拟点击事件,并使用jest.fn()创建模拟函数,通过toHaveBeenCalled断言模拟函数是否被调用,进行交互模拟测试。