-
What?
- [airbnb/enzyme: JavaScript Testing utilities for React](https://github.com/airbnb/enzyme)
- Enzyme uses several of the utilities provided by React to build its API, but provides a much different interface and several more methods to reduce boilerplate and reduce the coupling between your tests and your implementation.
- 技术雷达:我们非常享受Enzyme为React.js应用提供的快速组件级UI测试功能。与许多其他基于快照的测试框架不同,Enzyme允许开发者在不进行设备渲染的情况下做测试,从而实现速度更快,粒度更小的测试。在开发React应用时,我们经常需要做大量的功能测试,而Enzyme可以在大规模地减少功能测试数量上做出贡献。
- Enzyme是官方测试工具库(react-addons-test-utils)的封装,它模拟了jQuery的API,非常直观,易于使用和学习;enzyme 支持多种测试类库,比如Chai.js ,Mocha,或者Jasmine.
-
组件测试:我们最喜爱的库之一是由 AirBnb 所开发的 enzyme,可用于组件测试。非常神奇的是,它的浅渲染特性可以对组件的逻辑及其渲染输出进行测试。尽管它还不能替代你的 selenium 测试,但是将前端测试提升到了一个新的水平。
- 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
})
-
Airbnb has released a testing utility called Enzyme, which makes it easy to assert, manipulate, and traverse your React Components' output. If you're deciding on a unit testing utility to use together with Jest, or any other test runner, it's worth checking out: http://airbnb.io/enzyme/
- 项目实例
-
How?
-
Configuration
- [enzyme/mocha.md at master · airbnb/enzyme](https://github.com/airbnb/enzyme/blob/master/docs/guides/mocha.md)
- [enzyme/jsdom.md at master · airbnb/enzyme](https://github.com/airbnb/enzyme/blob/master/docs/guides/jsdom.md)
- [producthunt/chai-enzyme: Chai.js assertions and convenience functions for testing React Components with enzyme](https://github.com/producthunt/chai-enzyme)
- [React Native | Enzyme](http://airbnb.io/enzyme/docs/guides/react-native.html)
-
三种渲染方式
-
shallow(node[, options]) => ShallowWrapper
- shallow方法就是官方的shallow rendering的封装,只支持简单选择器
- shallow render只渲染出组件的第一层DOM,其嵌套的DOM不会渲染出来,这样渲染的效率更高,单元测试的速度更快,在做单元测试的时候建议使用shallow render的方式。
-
mount(node[, options]) => ReactWrapper
- mount方法用于将React组件加载为真实DOM节点。
- Full DOM rendering requires that a full DOM API be available at the global scope. This means that it must be run in an environment that at least "looks like" a browser environment. If you do not want to run your tests inside of a browser, the recommended approach to using mount is to depend on a library called jsdom which is essentially a headless browser implemented completely in JS.
-
render(node[, options]) => CheerioWrapper
- 将React组件渲染成静态的HTML字符串,然后分析这段HTML代码的结构,返回一个对象。
- render方法与shallow方法的API基本一致,主要的不同是采用了第三方HTML解析库Cheerio,它返回的是一个Cheerio实例对象。
-
测试方法
- 不但可以通过find方法查找DOM元素,还可以模拟DOM的事件,比如Click,Change等。
-
Selectors
- class syntax (.foo, .foo-bar, etc.)
tag syntax (input, div, span, etc.)
id syntax (#foo, #foo-bar, etc.)
prop syntax ([htmlFor="foo"], [bar], [baz=1], etc.);