Skip to content

Latest commit

 

History

History
137 lines (104 loc) · 2.95 KB

File metadata and controls

137 lines (104 loc) · 2.95 KB
title category updated weight deprecated_by
Enzyme v2
React
2017-10-12
-1
/enzyme

Getting started

{: .-three-column}

Introduction

{: .-intro}

(Deprecated) Enzyme lets you write unit tests for React components. This guide covers a previous version (v2.x).

Mounting

{: .-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

Jest

import toJson from 'enzyme-to-json'

{: .-setup}

it('works', () => {
  wrap = mount(<MyComponent />)
  expect(toJson(wrap)).toMatchSnapshot()
})

Converts an Enzyme wrapper to a format compatible with Jest snapshots. See: enzyme-to-json

Debugging

console.log(wrap.debug())

Shows HTML for debugging purposes. See: debug()

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.getNode()        // => ReactElement
wrap.getNodes()       // => Array<ReactElement>
wrap.getDOMNode()     // => DOMComponent

See: Full rendering API

Actions

wrap.simulate('click')

React components

wrap.setState({ ... })
wrap.setProps({ ... })
wrap.setContext({ ... })

wrap.state()            // => Any (get state)
wrap.props()            // => object (get props)
wrap.context()          // => Any (get context)

wrap.instance()         // => ReactComponent

Mount

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

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.containsMatchingElement(<div />)         // => boolean
wrap.containsAllMatchingElements([ <div /> ]) // => boolean
wrap.containsAnyMatchingElements([ <div /> ]) // => boolean

References