Effortless Assertions and Testing with Enzyme Matchers 6

26 March 2018

Enzyme Matchers allows you to run common assertions on your React components using Enzyme in a Jest or Jasmine environment. With it, you can easily test styles, disabled states, stylesheet classes, text and more. With version 6.0, Enzyme Matchers simplifies setup of your test environment in Jest, making it even easier to get started with.

Built–In Matchers for Common Test Patterns

The assertions in Enzyme Matchers make it easier to test your React components, and can even simplify the testing of certain styles.

expect(wrapper.props().style).toEqual(expect.objectContaining({
  backgroundColor: 'red'
});

becomes:

expect(wrapper).toHaveStyle('backgroundColor', 'red');

You can also easily test if your mounted components contain other React components.

const List = () => (
  <ul>
    <li><Dog name="Leo" /></li>
    <li><Dog name="Dixie" /></li>
  </ul>
);

const wrapper = mount(<List />);

expect(wrapper).toContainReact(<Dog name="Leo" />);
expect(wrapper).not.toContainReact(<Dog name="Milo" />);

Assertions for matching classes, html markup, refs, state, and more are also included.

Simplified Test Environment Setup

With Enzyme Matchers 6, getting your Jest test environment running has never been easier. The React 16 Enzyme adapter is applied by default, so you no longer have to manually set one up. If you need to change the version, you can do so inside your package.json’s jest object. The jest-environment-enzyme package eliminates the need to import React, shallow, mount, or render to every test file. A corresponding eslint-config-jest-enzyme package takes care of any linting issues around those global variables.

How To Get Started

To start using Enzyme Matchers and the simplified test environment using yarn or npm install, add jest-enzyme jest-environment-enzyme to your dev dependencies. You can also install eslint-config-jest-enzyme if you’re using ESLint. The assertions in Enzyme Matchers are included with jest-enzyme.

All you have to add to your package.json is:

"jest": {
  "testEnvironment": "enzyme",
  "setupTestFrameworkScriptFile": "./node_modules/jest-enzyme/lib/index.js"
}

To learn more about Enzyme Matchers visit the GitHub repo or send a tweet to Blaine Kasten.

Related Posts

Hooked

We're very excited about what we learned at React Conf and we wanted to share our take on React Hooks, a new React API that gives React functional com ...

By
Jani Eväkallio

Jani Eväkallio

Matt HinkMatt Hink

Victory is Turning 30

Victory is making the change to major versions with the release of victory@30.0.0! This is an unusual version bump, and a major milestone for the proj ...

Screenshot Testing with Chromatic

Is this bubble chart correct? Answering this question with unit tests requires breaking it down into several smaller questions: Is the method responsi ...

Check out more of Carlos's blog posts