Enzyme是一个React的JavaScript测试工具,使React组件的输出更加容易extrapolate
。
Enzyme的API和jQuery操做DOM同样灵活易用。(由于其使用的是cheerio库来解析虚拟DOM,而cheerio的目标则是作服务器端的jQuery)
Enzyme兼容大多数断言库和测试框架,如chai
、mocha
、jasmine
等。html
npm i --save-dev enzyme
若是使用的是React 0.14
或React 15.x
,请确保如下模块已经安装react
npm i --save-dev react-addons-test-utils npm i --save-dev react-dom
import React from 'react'; import { shallow } from 'enzyme'; import sinon from 'sinon'; import MyComponent from './MyComponent'; import Foo from './Foo'; describe('<MyComponent />', () => { it('renders three <Foo /> components', () => { const wrapper = shallow(<MyComponent />); expect(wrapper.find(Foo)).to.have.length(3); }); it('renders an `.icon-star`', () => { const wrapper = shallow(<MyComponent />); expect(wrapper.find('.icon-star')).to.have.length(1); }); it('renders children when passed in', () => { const wrapper = shallow( <MyComponent> <div className="unique" /> </MyComponent> ); expect(wrapper.contains(<div className="unique" />)).to.equal(true); }); it('simulates click events', () => { const onButtonClick = sinon.spy(); const wrapper = shallow( <Foo onButtonClick={onButtonClick} /> ); wrapper.find('button').simulate('click'); expect(onButtonClick).to.have.property('callCount', 1); }); });
#### 完整的DOM渲染github
import React from 'react'; import sinon from 'sinon'; import { mount } from 'enzyme'; import MyComponent from './MyComponent'; import Foo from './Foo'; describe('<Foo />', () => { 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).to.have.property('callCount', 1); }); it('calls componentDidMount', () => { sinon.spy(Foo.prototype, 'componentDidMount'); const wrapper = mount(<Foo />); expect(Foo.prototype.componentDidMount).to.have.property('callCount', 1); Foo.prototype.componentDidMount.restore(); }); });
#### 静态渲染npm
import React from 'react'; import { render } from 'enzyme'; import Foo from './Foo'; describe('<Foo />', () => { it('renders three `.foo-bar`s', () => { const wrapper = render(<Foo />); expect(wrapper.find('.foo-bar').length).to.equal(3); }); it('renders the title', () => { const wrapper = render(<Foo title="unique" />); expect(wrapper.text()).to.contain('unique'); }); });
如今还不支持分层(hierarchical)选择器api
对于 shallow rendering,事件模拟有限制,事件传播也不支持,必须给出一个事件对象。服务器
不少react控件涉及表单输入框和复杂的鼠标交互,使用Enzyme提供的事件API来模拟显得笨重且不切实际。app