Enzyme 是一个用于 React 的 JavaScript 测试工具,它可以更轻松地断言、操作和遍历 React 组件的输出。它最初由 Airbnb 开发,后来转移到一个独立的组织。
Enzyme 的 API 旨在通过模仿 jQuery 的 DOM 操作和遍历 API 来实现直观和灵活。
Enzyme 对您使用的测试运行器或断言库没有偏好,应该与所有主要的测试运行器和断言库兼容。Enzyme 的文档和示例使用了mocha 和 chai,但是您可以将其应用到您选择的框架。
要开始使用 Enzyme,您可以使用 npm 简单地安装它:
npm i --save-dev enzyme
Enzyme 目前兼容 React 0.14.x
和 React 0.13.x
。为了实现这种兼容性,某些依赖项不能在我们的 package.json
中显式列出。
如果您使用的是 React 0.14
,除了 enzyme
之外,您还需要确保已安装以下 npm 模块(如果尚未安装):
npm i --save-dev react-addons-test-utils
npm i --save-dev react-dom
import { shallow } from 'enzyme';
describe('<MyComponent />', () => {
it('should render three <Foo /> components', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Foo)).to.have.length(3);
});
it('should render an `.icon-star`', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.icon-star')).to.have.length(1);
});
it('should render children when passed in', () => {
const wrapper = shallow(
<MyComponent>
<div className="unique" />
</MyComponent>
);
expect(wrapper.contains(<div className="unique" />)).to.be.true;
});
it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = shallow(
<Foo onButtonClick={onButtonClick} />
);
wrapper.find('button').simulate('click');
expect(onButtonClick.calledOnce).to.be.true;
});
});
阅读完整的API 文档
import {
describeWithDOM,
mount,
spyLifecycle,
} from 'enzyme';
describeWithDOM('<Foo />', () => {
it('calls componentDidMount', () => {
spyLifecycle(Foo);
const wrapper = mount(<Foo />);
expect(Foo.prototype.componentDidMount.calledOnce).to.be.true;
});
it('allows us to set props', () => {
const wrapper = mount(<Foo bar="baz" />);
expect(wrapper.props().bar).to.equal("baz");
wrapper.setProps({ bar: "foo" });
expect(wrapper.props().bar).to.equal("foo");
});
it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = mount(
<Foo onButtonClick={onButtonClick} />
);
wrapper.find('button').simulate('click');
expect(onButtonClick.calledOnce).to.be.true;
});
});
阅读完整的API 文档
import { render } from 'enzyme';
describe('<Foo />', () => {
it('renders three `.foo-bar`s', () => {
const wrapper = render(<Foo />);
expect(wrapper.find('.foo-bar').length).to.equal(3);
});
it('rendered the title', () => {
const wrapper = render(<Foo title="unique" />);
expect(wrapper.text()).to.contain("unique");
});
});
阅读完整的API 文档