Enzyme Cheat Sheet

From WikiOD

Here is the cheatsheat of Enzyme and basic guide on how to use Enzyme

Getting started[edit | edit source]

Introduction[edit | edit source]

{: .-intro}

Enzyme lets you write unit tests for React components. This guide covers Enzyme 3.x.

Mounting[edit | edit source]

{: .-prime}

import {shallow, mount} from 'enzyme'

{: .-setup}

wrap = shallow(<MyComponent />)
wrap = mount(<MyComponent />)

Shallow wrapping doesn’t descend down to sub-components. A full mount also mounts sub-components.

See: Shallow rendering, Full rendering

Debugging[edit | edit source]

console.log(wrap.debug())

Shows HTML for debugging purposes.

See: debug()

Examples[edit | edit source]

{: .-three-column}

Basic example[edit | edit source]

{: .-prime}

import { shallow } from 'enzyme'
import MyComponent from '../MyComponent'

{: .-setup}

it('works', () => {
  const wrap = shallow(
    <MyComponent name='Groot' />
  )

  expect(wrap.text()).toEqual('I am Groot')
})

Props and state[edit | edit source]

Setting[edit | edit source]

wrap.setProps({ name: 'Moe' })
wrap.setState({ show: true })

Asserting[edit | edit source]

expect(wrap.prop('name')).toEqual('Moe')
expect(wrap.state('show')).toEqual(true)
expect('name' in wrap.props()).toEqual('Moe')
expect('show' in wrap.state()).toEqual(true)

Matching elements[edit | edit source]

expect(
  wrap.containsMatchingElement(
    <span>I am groot</span>
  )
).toBeTruthy()

containsMatchingElement() is probably the most useful assertion in Jest.

Snapshots[edit | edit source]

expect(wrap).toMatchSnapshot()

Be sure you’ve set up enzyme-to-json for snapshots (see Installing below).

Traversions[edit | edit source]

expect(
  wrap.find('button').text()
).toEqual('Submit')

Use .find() to traverse down to nodes. It will return wrapper objects, too.

Simulating events[edit | edit source]

wrap.find('input').simulate('click')

With event object props[edit | edit source]

wrap.find('input').simulate('change', {
  target: { value: 'hello' }
})

Installing[edit | edit source]

Initial setup[edit | edit source]

npm install --save-dev enzyme \
  enzyme-adapter-react-16 \
  react-test-renderer

{: .-setup}

test/setup.js[edit | edit source]

import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

Enzyme.configure({ adapter: new Adapter() })

package.json[edit | edit source]

"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

Jest snapshots[edit | edit source]

npm install --save-dev enzyme-to-json

{: .-setup}

package.json[edit | edit source]

"jest": {
  "snapshotSerializers": [
    "enzyme-to-json/serializer"
  ]
}

Test[edit | edit source]

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

ReactWrapper[edit | edit source]

Traversing[edit | edit source]

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

Actions[edit | edit source]

wrap.simulate('click')

React components[edit | edit source]

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

Mount[edit | edit source]

wrap.mount()
wrap.unmount()
wrap.update()      // calls forceUpdate()

Tests[edit | edit source]

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

References[edit | edit source]

  • Enzyme website (airbnb.io)
  • [[./enzyme@2|Enzyme v2 cheatsheet]] (devhints.io) (old version)

Credit:rstacruz