Enzyme 是一个用于测试 React 组件的 JavaScript 库。它提供了一组 API,可以让开发人员在不渲染整个应用程序的情况下测试单个组件的行为和输出。Enzyme 是由 Airbnb 开发的,已经成为 React 生态系统中最受欢迎的测试工具之一。
安装 Enzyme
要使用 Enzyme,我们需要将它作为一个依赖项添加到我们的项目中。我们可以使用 npm 或 yarn 安装它:
npm install --save-dev enzyme enzyme-adapter-react-16
或
yarn add --dev enzyme enzyme-adapter-react-16
注意:Enzyme 有多个适配器,需要根据使用的 React 版本选择适配器。在这个例子中,我们选择了适配器 enzyme-adapter-react-16,因为我们使用的是 React 16。
配置 Enzyme
Enzyme 需要一个适配器来与 React 一起使用。我们需要在测试文件中配置 Enzyme,以便它知道使用哪个适配器。在我们的测试文件中添加以下代码:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });渲染组件
要测试一个组件,我们需要将其渲染成一个虚拟 DOM。Enzyme 提供了三种渲染组件的方法:
shallow()
这是 Enzyme 中最常用的方法。它将组件渲染成一个浅层次的虚拟 DOM,只渲染组件本身而不渲染其子组件。这使得测试变得更快,因为它不需要渲染整个组件树。
import { shallow } from 'enzyme';
const wrapper = shallow(<MyComponent />);mount()
这将组件渲染成一个完整的虚拟 DOM。它会渲染组件及其子组件,并返回一个包含整个组件树的包装器。
import { mount } from 'enzyme';
const wrapper = mount(<MyComponent />);render()
这将组件渲染成一个静态 HTML 字符串。它不会返回一个包装器,而是返回一个普通的字符串。
import { render } from 'enzyme';
const wrapper = render(<MyComponent />);测试组件行为和输出
一旦我们有了一个组件的包装器,我们就可以使用 Enzyme 的 API 来测试其行为和输出。
查找元素
我们可以使用 Enzyme 的 find() 方法来查找组件中的元素。它接受一个选择器作为参数,并返回一个包含所有匹配元素的包装器。
const wrapper = shallow(<MyComponent />);
const element = wrapper.find('.my-class');模拟事件
我们可以使用 simulate() 方法来模拟事件。它接受一个事件类型作为参数,并可以传递一个事件对象作为第二个参数。
const wrapper = shallow(<MyComponent />);
wrapper.find('button').simulate('click');断言输出
我们可以使用 Enzyme 的 API 来断言组件的输出。以下是一些常见的方法:
.text()
返回包装器中包含的文本。
const wrapper = shallow(<MyComponent />);
expect(wrapper.text()).toEqual('Hello World');.html()
返回包装器中包含的 HTML。
const wrapper = shallow(<MyComponent />);
expect(wrapper.html()).toEqual('<div>Hello World</div>');.prop()
返回包装器中指定属性的值。
const wrapper = shallow(<MyComponent />);
expect(wrapper.prop('disabled')).toEqual(true);示例代码
下面是一个简单的示例,演示了如何使用 Enzyme 测试一个 React 组件。
// www.javascriptcn.com code example
import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
function Button(props) {
return (
<button disabled={props.disabled} onClick={props.onClick}>
{props.label}
</button>
);
}
describe('Button', () => {
it('should render a button with the label "Click me"', () => {
const wrapper = shallow(<Button label="Click me" />);
expect(wrapper.text()).toEqual('Click me');
});
it('should disable the button when disabled prop is true', () => {
const wrapper = shallow(<Button disabled={true} />);
expect(wrapper.prop('disabled')).toEqual(true);
});
it('should call the onClick prop when the button is clicked', () => {
const onClick = jest.fn();
const wrapper = shallow(<Button onClick={onClick} />);
wrapper.find('button').simulate('click');
expect(onClick).toHaveBeenCalled();
});
});在这个例子中,我们测试了一个简单的按钮组件。我们使用 shallow() 方法来渲染组件,并使用 Enzyme 的 API 来断言组件的输出和行为。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d11b3ca941bf7134259133