References
- Enzyme website (airbnb.io)
- Enzyme v2 cheatsheet (devhints.io) (old version) ### [ReactWrapper] Tests
wrap.debug() // → string
wrap.html() // → string
wrap.text() // → string
wrap.type() // → string | function
wrap.name() // → string
wrap.is('.classname') // → boolean
wrap.hasClass('class') // → boolean
wrap.exists() // → boolean
wrap.contains(<div />) // → boolean
wrap.contains([ <div /> ]) // → boolean
wrap.some('.child') // → boolean
wrap.someWhere(n => n.hasClass('foo'))
wrap.containsMatchingElement(<div />) // → boolean
wrap.containsAllMatchingElements([ <div /> ]) // → boolean
wrap.containsAnyMatchingElements([ <div /> ]) // → boolean
[ReactWrapper] Mount
wrap.mount()
wrap.unmount()
wrap.update() // calls forceUpdate()
[ReactWrapper] React components
wrap.setState({ ··· })
wrap.setProps({ ··· })
wrap.setContext({ ··· })
wrap.state() // get full state
wrap.props() // get full props
wrap.context() // get full context
wrap.state('key') // → any
wrap.prop('key') // → any
wrap.context('key') // → any
wrap.instance() // → ReactComponent
[ReactWrapper] Actions
wrap.simulate('click')
[ReactWrapper] Traversing
wrap.find('button') // → ReactWrapper
wrap.filter('button') // → ReactWrapper
wrap.not('span') // → ReactWrapper (inverse of filter())
wrap.children() // → ReactWrapper
wrap.parent() // → ReactWrapper
wrap.closest('div') // → ReactWrapper
wrap.childAt(0) // → ReactWrapper
wrap.at(0) // → ReactWrapper
wrap.first() // → ReactWrapper
wrap.last() // → ReactWrapper
wrap.get(0) // → ReactElement
wrap.getElement() // → ReactElement
wrap.getElements() // → Array<ReactElement>
wrap.getDOMNode() // → DOMComponent
See: Full rendering API
[Installing] Jest snapshots
npm install --save-dev enzyme-to-json
{: .-setup}
package.json
"jest": {
"snapshotSerializers": [
"enzyme-to-json/serializer"
]
}
Test
it('works', () => {
wrap = mount(<MyComponent />)
expect(wrap).toMatchSnapshot()
})
Optional, but recommended: This allows you to use Enzyme wrappers with Jest snapshots.
See: enzyme-to-json
[Installing] Initial setup
npm install --save-dev enzyme \
enzyme-adapter-react-16 \
react-test-renderer
{: .-setup}
test/setup.js
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
Enzyme.configure({ adapter: new Adapter() })
package.json
"jest": {
"setupFiles": [
"test/setup.js"
]
}
This configures Enzyme for React v16, and Jest to automatically configure Enzyme for you. There are other adapters in Enzyme's installation instructions.
See: Installation
[Examples] Simulating events
wrap.find('input').simulate('click')
With event object props
wrap.find('input').simulate('change', {
target: { value: 'hello' }
})
[Examples] Traversions
expect(
wrap.find('button').text()
).toEqual('Submit')
Use .find()
to traverse down to nodes. It will return wrapper objects, too.
Top comments (0)