Enzyme in a
nutshell

  • Enzyme is a JavaScript Testing utility for React
  • Enzyme's API is intuitive and flexible by mimicking jQuery's API
  • unopinionated regarding which test runner or assertion library is used (chai, jasmine, jest...)

Rendering approaches

  • shallow
    Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components
     
  • mount
    Full DOM rendering is ideal for use cases where you have components that may interact with DOM APIs or need to test components that are wrapped in higher order components
     
  • render
    returns a wrapper very similar to the other renderers in enzyme, mount and shallow; however, render uses a third party HTML parsing and traversal library Cheerio

Useful methods

const wrapper = mount(
  <Header title="Title" description="Description" />,
);
wrapper.debug()

Returns an HTML-like string of the wrapper for debugging purposes. Useful to print out to the console when tests are not passing when you expect them to.

<Header>
  <div className="body">
    <h3 className="title">Title</h3>
    <p className="description">Description</p>
  </div>
</Header>

Useful methods

const wrapper = mount(
  <Header title="Title" description="Description" />,
);
wrapper.find()
// compound selector
expect(wrapper.find('div.some-class')).to.have.lengthOf(3);

// CSS id selector
expect(wrapper.find('#foo')).to.have.lengthOf(1);

// property selector
expect(wrapper.find('[htmlFor="checkbox"]')).to.have.lengthOf(1);

Finds every node in the render tree of the current wrapper that matches the provided selector.

Useful methods

const wrapper = mount(
  <Header title="Title" description="Description" />,
);
wrapper.props()
expect(wrapper.props().title).to.equal('Title');

Returns the props object for the root node of the wrapper. It must be a single-node wrapper.

The wrapper.props() method is especially useful when validating prop values for rendered component's children.

Useful methods

const wrapper = mount(
  <Header title="Title" description="Description" />,
);
wrapper.text()

Returns a string of the rendered text of the current render tree.

*Live coding slide*

*Our codebase example slide*

Q & A

Enzyme

By Dana Janoskova