面试题答案
一键面试- 安装依赖:
- 首先确保项目中安装了
jest
、enzyme
以及相关适配器。 - 对于React项目,通常安装
@testing - library/react
、enzyme
、enzyme - adapter - react - 16
(根据React版本选择合适的适配器)。
npm install --save - dev jest @testing - library/react enzyme enzyme - adapter - react - 16
- 首先确保项目中安装了
- 编写无状态函数组件:
- 假设组件名为
SimpleComponent
,接收一个text
属性并展示在界面上。
import React from'react'; const SimpleComponent = ({ text }) => { return <div>{text}</div>; }; export default SimpleComponent;
- 假设组件名为
- 编写测试用例:
- 渲染测试:
- 使用
@testing - library/react
的render
函数或enzyme
的shallow
函数进行渲染测试。 - 使用
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/react
的render
函数和getByText
方法断言文本是否在文档中,进行渲染测试。 - 使用
enzyme
的shallow
函数渲染组件,text
方法获取组件文本内容进行渲染测试。 - 使用
enzyme
的simulate
方法模拟点击事件,并使用jest.fn()
创建模拟函数,通过toHaveBeenCalled
断言模拟函数是否被调用,进行交互模拟测试。