在进行 React 前端开发的过程中,多数情况下都需要使用测试框架对组件进行单元测试、集成测试等类型的测试。此时,我们需要选择适合当前项目的测试框架,在 React 场景下,Enzyme 无疑是测试组件的首选。
Enzyme 是一个 React 组件测试工具库,由 Airbnb 开源并维护。Enzyme 工具提供了三种方法find、filter、closest,用于从被渲染的 React 组件上查找元素。
1. find 方法
find 方法可以在指定的 React 组件内查找子组件。它会返回包含一个或多个 DOM 元素的实例。
1.1 使用方法
在进行单元测试时,我们要判断 React 组件是否正确渲染出 DOM 元素,此时,我们可以借助 find 方法,指定需要查找的元素,如下所示:
const wrapper = shallow(<MyComponent />);
wrapper.find('button');这样可以返回当前渲染的 MyComponent 组件内的所有 button 元素实例。
1.2 示例代码
// www.javascriptcn.com code example
import React from 'react';
import { shallow } from 'enzyme';
describe('<MyComponent />', () => {
it('renders a button', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('button').length).toBe(1);
});
});2. filter 方法
filter 方法可以根据条件筛选 React 组件内的子组件,返回筛选后的子组件实例。
2.1 使用方法
当我们想要查找具有指定属性或状态的元素时,可以使用 filter 方法进行筛选。例如,需要查找拥有指定属性的元素,如下所示:
const wrapper = shallow(<MyComponent />);
wrapper.find('button').filter({ disabled: true });这样可以返回 MyComponent 组件中符合条件的 button 元素实例,属性 disabled 为 true。
2.2 示例代码
// www.javascriptcn.com code example
import React from 'react';
import { shallow } from 'enzyme';
describe('<MyComponent />', () => {
it('renders the disabled button', () => {
const wrapper = shallow(<MyComponent />);
const disabledButton = wrapper.find('button').filter({ disabled: true });
expect(disabledButton.length).toBe(1);
});
});3. closest 方法
closest 方法可以在子组件内查找最近的匹配元素。如果元素不存在,将返回一个空的元素实例。
3.1 使用方法
当我们需要在特定组件内查找元素时,可以使用 closest 方法。例如,需要在当前组件内查找符合条件的 div 元素,如下所示:
const wrapper = shallow(<MyComponent />);
wrapper.find('button').closest('div');这样将返回 MyComponent 组件中与查找 button 元素相邻的 div 元素实例。
3.2 示例代码
// www.javascriptcn.com code example
import React from 'react';
import { shallow } from 'enzyme';
describe('<MyComponent />', () => {
it('renders the nearest div', () => {
const wrapper = shallow(<MyComponent />);
const nearestDiv = wrapper.find('button').closest('div');
expect(nearestDiv.length).toBe(1);
});
});总之,在使用 Enzyme 进行组件测试时,使用 find、filter、closest 方法是非常方便的。掌握这三种方法的使用方法和区别,将使我们的测试更加高效、准确。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d6fcdba941bf7134cd843c