Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

jest-enzyme

FormidableLabs851.2kMIT7.1.2TypeScript support: included

Testing Matchers for Enzyme

javascript, shallow rendering, shallowRender, test, reactjs, react, flux, testing, test utils, assertion helpers, tdd, jest, enzyme

readme

jest-enzyme

npm version License

Quick Links

Setup

The best setup is to use our jest environment jest-environment-enzyme.

If you prefer not to use the environment, you can also do this:

// package.json
"jest": {
  "setupFilesAfterEnv": ['./node_modules/jest-enzyme/lib/index.js'],
}

Assertions

  • Not all assertions work with every rendering strategy. If you are wondering what rendering mechanism to use when, refer to enzyme's documentation.

toBeChecked()

render mount shallow
no yes yes

Ways to use this API:

expect().toBeChecked();

Assert that the given wrapper is checked:

import React from 'react'
import {mount, shallow} from 'enzyme'

function Fixture() {
  return (
    <div>
      <input id="checked" defaultChecked />
      <input id="not" defaultChecked={false} />
      <input id="tertiary" defaultChecked checked={false} />
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('#checked')).toBeChecked();
expect(wrapper.find('#not')).not.toBeChecked();

toBeDisabled()

render mount shallow
no yes yes

Ways to use this API:

expect().toBeDisabled();

Assert that the given wrapper is disabled:

import React from 'react'
import {mount, shallow} from 'enzyme'

function Fixture() {
  return (
    <div>
      <input id="disabled" disabled />
      <input id="not"/>
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('#disabled')).toBeDisabled();
expect(wrapper.find('#not')).not.toBeDisabled();

toBeEmptyRender()

render mount shallow
no yes yes

Ways to use this API:

expect().toBeEmptyRender();

Assert that the given wrapper has an empty render (null or false):

function EmptyRenderFixture() {
  return null;
}

function NonEmptyRenderFixture() {
  return (
    <div>
      <EmptyRenderFixture />
    </div>
  );
}

const wrapper = mount(<EmptyRenderFixture />); // mount/render/shallow when applicable

expect(wrapper.find('EmptyRenderFixture')).toBeEmptyRender();
expect(wrapper).not.toBeEmptyRender();

toExist()

render mount shallow
no yes yes

Ways to use this API:

expect().toExist();

Assert that the given enzyme wrapper has rendered content.

function Fixture() {
  return (
    <div>
      <span className="foo" />
      <span className="bar baz" />
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('span')).toExist();
expect(wrapper.find('ul')).not.toExist();

toContainMatchingElement()

render mount shallow
no yes yes

Ways to use this API:

expect().toContainMatchingElement('.foo');

Assert that the given wrapper contains at least one match for the given selector:

function User(props) {
  return (
    <span className={props.className}>
      User {props.index}
    </span>
  );
}

User.propTypes = {
  index: PropTypes.number.isRequired,
  className: PropTypes.string,
};

function Fixture() {
  return (
    <div>
      <ul>
        <li>
          <User index={1} className="userOne" />
        </li>
        <li>
          <User index={2} className="userTwo" />
        </li>
      </ul>
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper).toContainMatchingElement('.userOne');
expect(wrapper).not.toContainMatchingElement('.userThree');

toContainMatchingElements()

render mount shallow
no yes yes

Ways to use this API:

expect().toContainMatchingElements(2, '.foo');

Assert that the given wrapper contains a given number of matches for the given selector:

function User(props) {
  return (
    <span className={props.className}>
      User {props.index}
    </span>
  );
}

User.propTypes = {
  index: PropTypes.number.isRequired,
  className: PropTypes.string,
};

function Fixture() {
  return (
    <div>
      <ul>
        <li>
          <User index={1} className="userOne" />
        </li>
        <li>
          <User index={2} className="userTwo" />
        </li>
      </ul>
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper).toContainMatchingElements(2, 'User');
expect(wrapper).not.toContainMatchingElements(2, '.userTwo');

toContainExactlyOneMatchingElement()

render mount shallow
no yes yes

Ways to use this API:

expect().toContainExactlyOneMatchingElement('.foo');

Assert that the given wrapper contains exactly one match for the given selector:

function User(props) {
  return (
    <span className={props.className}>
      User {props.index}
    </span>
  );
}

User.propTypes = {
  index: PropTypes.number.isRequired,
  className: PropTypes.string,
};

function Fixture() {
  return (
    <div>
      <ul>
        <li>
          <User index={1} className="userOne" />
        </li>
        <li>
          <User index={2} className="userTwo" />
        </li>
      </ul>
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper).toContainExactlyOneMatchingElement('.userOne');
expect(wrapper).not.toContainExactlyOneMatchingElement('User');

toContainReact()

render mount shallow
no yes yes

Ways to use this API:

expect().toContainReact(<div>foo</div>);

Assert that the given wrapper contains the provided react instance:

class User extends React.Component {
  render () {
    return (
      <span>User {this.props.index}</span>
    )
  }
}

User.propTypes = {
  index: PropTypes.number.isRequired
}

class Fixture extends React.Component {
  render () {
    return (
      <div>
        <ul>
          <li><User index={1} /></li>
          <li><User index={2} /></li>
        </ul>
      </div>
    )
  }
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper).toContainReact(<User index={1} />);
expect(wrapper).not.toContainReact(<User index={9000} />);

toHaveClassName()

render mount shallow
no yes yes

Ways to use this API:

expect().toHaveClassName('foo');

Assert that the given wrapper has the provided className:

function Fixture() {
  return (
    <div>
      <span className="foo" />
      <span className="bar baz" />
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('.foo')).toHaveClassName('foo');
expect(wrapper.find('.foo')).not.toHaveClassName('baz');

expect(wrapper.find('.bar')).toHaveClassName('bar baz');
expect(wrapper.find('.bar')).toHaveClassName('baz');

toHaveDisplayName()

render mount shallow
no yes yes

Ways to use this API:

expect().toHaveDisplayName('div');

Assert that the wrapper is of a certain tag type:

function Fixture() {
  return (
    <div>
      <span id="span" />
    </div>
  );
}

const wrapper = mount(<Fixture />);

expect(wrapper.find('#span')).toHaveDisplayName('span');
expect(wrapper.find('#span')).not.toHaveDisplayName('div');

toHaveHTML()

render mount shallow
no yes yes

Ways to use this API:

expect().toHaveHTML('<div>html</div>');

Assert that the given wrapper has the provided html:

Note Quotations are normalized.

function Fixture() {
  return (
    <div id="root">
      <span id="child">Test</span>
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('#child')).toHaveHTML(
  '<span id="child">Test</span>'
);

toHaveProp()

render mount shallow
no yes yes

Ways to use this API:

expect().toHaveProp('foo', 'value');
expect().toHaveProp('foo');
expect().toHaveProp({foo: 'value'});

Assert that the given wrapper has the provided propKey and associated value if specified:

function User() { ... }
User.propTypes = {
  foo: PropTypes.string,
  bar: PropTypes.array,
};

function Fixture() {
  return (
    <div id="root">
      <User foo={'baz'} bar={[1,2,3]} />
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find(User)).toHaveProp('foo');
expect(wrapper.find(User)).toHaveProp('foo', 'baz');

expect(wrapper.find(User)).toHaveProp('bar');
expect(wrapper.find(User)).toHaveProp('bar', [1,2,3]);

expect(wrapper.find(User)).toHaveProp({
  bar: [1, 2, 3],
  foo: 'baz',
});

toHaveRef()

render mount shallow
no yes yes

Ways to use this API:

expect().toHaveRef('foo');

Assert that the mounted wrapper has the provided ref:

class Fixture extends React.Component {
  render() {
    return (
      <div>
        <span ref="child" />
      </div>
    );
  }
}

const wrapper = mount(<Fixture />);

expect(wrapper).toHaveRef('child');
expect(wrapper).not.toHaveRef('foo');

toHaveState()

render mount shallow
no yes yes

Ways to use this API:

expect().toHaveState('foo');
expect().toHaveState('foo', 'bar');
expect().toHaveState({ foo: 'bar' });

Assert that the component has the provided stateKey and optional value if specified:

class Fixture extends React.Component {
  constructor() {
    super();
    this.state = {
      foo: false,
    };
  }

  render() {
    return (
      <div />
    );
  }
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper).toHaveState('foo');
expect(wrapper).toHaveState('foo', false);
expect(wrapper).toHaveState({ foo: false });

toHaveStyle()

render mount shallow
no yes yes

Ways to use this API:

expect().toHaveStyle('height');
expect().toHaveStyle('height', '100%');
expect().toHaveStyle({ height: '100%' });

Assert that the component has style of the provided key and value:

function Fixture() {
  const style1 = { height: '100%' };
  const style2 = { flex: 8 };

  return (
    <div>
      <span id="style1" style={style1} />
      <span id="style2" style={style2} />
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('#style1')).toHaveStyle('height', '100%');
expect(wrapper.find('#style2')).toHaveStyle('flex', 8);

toHaveTagName()

Deprecated: Matcher toHaveTagName is deprecated. Use the replacement, toHaveDisplayName() instead.

toHaveText()

render mount shallow
no yes yes

Ways to use this API:

expect().toHaveText('bar');

Assert that the wrapper's text matches the provided text exactly, using a strict comparison (===).

function Fixture() {
  return (
    <div>
      <p id="full">Text</p>
      <p id="empty"></p>
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('#full')).toHaveText('Text');
expect(wrapper.find('#full')).not.toHaveText('Wrong');

expect(wrapper.find('#full')).toHaveText();
expect(wrapper.find('#empty')).not.toHaveText();

toIncludeText()

render mount shallow
no yes yes

Ways to use this API:

expect().toIncludeText('bar');

Assert that the wrapper includes the provided text:

function Fixture() {
  return (
    <div>
      <p id="full">Some important text</p>
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('#full')).toIncludeText('important');
expect(wrapper.find('#full')).not.toIncludeText('Wrong');

toHaveValue()

render mount shallow
no yes yes

Ways to use this API:

expect().toHaveValue('bar');

Assert that the given wrapper has the provided value:

function Fixture() {
  return (
    <div>
      <input defaultValue="test" />
      <input defaultValue="foo" value="bar" onChange={jest.genMockFunction()} />
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('input').at(0)).toHaveValue('test');
expect(wrapper.find('input').at(1)).toHaveValue('bar');

toMatchElement()

render mount shallow
no yes yes

Ways to use this API:

expect().toMatchElement(<Foo />);
expect().toMatchElement(<Foo />, { ignoreProps: false });
expect().toMatchElement(<Foo />, { ignoreProps: false, verbose: false });

Assert the wrapper matches the provided react instance. This is a matcher form of Enzyme's wrapper.matchesElement(), which returns a bool with no indication of what caused a failed match. This matcher includes the actual and expected debug trees as contextual information when it fails. Like matchesElement(), props are ignored. If you want to compare prop values as well, pass { ignoreProps: false } as options. Uses enzyme's debug() under the hood and compares debug strings, which makes for a human readable diff when expects fail.

Example:

function Fixture() {
  return (
    <div>
      <span id="foo" className="bar" />
    </div>
  );
}

const wrapper = shallow(<Fixture />); // mount/render/shallow when applicable

expect(wrapper).toMatchElement(<Fixture />);
expect(wrapper.find('span')).toMatchElement(<span />);
expect(wrapper.find('span')).toMatchElement(
  <span id="foo" className="bar" />,
  { ignoreProps: false }
);
expect(wrapper).not.toMatchElement(<div />);

toMatchSelector()

render mount shallow
no yes yes

Ways to use this API:

expect().toMatchSelector('.foo');

Assert that the wrapper matches the provided selector:

function Fixture() {
  return (
    <div>
      <span id="foo" className="bar" />
    </div>
  );
}

const wrapper = mount(<Fixture />); // mount/render/shallow when applicable

expect(wrapper.find('span')).toMatchSelector('span');
expect(wrapper.find('span')).toMatchSelector('#foo');
expect(wrapper.find('span')).toMatchSelector('.bar');

Jest Enzyme Environment

There is a special environment to simplify using enzyme with jest. Check it out here

Usage with Create React App

If you are using Create React App, instead of adding to your package.json as above, you will need to add a src/setupTests.js file to your app, to import jest-enzyme:

 // src/setupTests.js
 import 'jest-enzyme';

This is documented on Create React App at the bottom of the Testing Components section. There is also more information about Initializing Test Environment.

Usage with TypeScript

As with Create React App, when using jest-enzyme with TypeScript and ts-jest, you'll need to add a setupTests.ts file to your app that explicitly imports jest-enzyme, and point the setupFilesAfterEnv field in your package.json file towards it:

 // src/setupTests.ts
 import 'jest-enzyme';
"jest": {
  "setupFilesAfterEnv": ["./src/setupTests.ts"],
},

This ensures that the type definitions bundled with jest-enzyme (which add extra Jest matchers and globals like shallow and mount) are included in your TypeScript project.

changelog

7.1.2

  • Fix a typescript conflict with a recent Jest update. (@tobilen)
  • Internal cleanup with jest compatibility. (@vkrol)
  • Internal updates to latest Babel and Jest. (@vkrol)
  • Fix documentation linking issues (@harrykiselev)

7.1.1

  • Fix a flowtype regression. (@bz2)
  • Improve infra to prevent further flowtype regressions. (@bz2)

7.1.0

  • toContainMatchingElement and toContainMatchingElements now can take a list of Enzyme wrappers. (@GreenGremlin)
  • Improved messaging for toContainMatchingElement and toContainMatchingElements. (@GreenGremlin)

7.0.2

  • Update a security advisory within dependencies. (@tgaff)
  • Various package improvements. (@goldensunliu, @mulholio, @kahwee, @tgaff)
  • Fixing messaging for toHaveState and toHaveProp. (@GreenGremlin)

7.0.1

  • Fix a jest integration with toContainMatchingElement not returning an explicit boolean. (@blainekasten)

7.0.0

🛑 Breaking

  • Renamed toHaveTagName to toHaveDisplayName (GreenGremlin)
    • This was done because Tag name indicates an HTML entity, but the matcher works with React Components which uses an internalProp displayName
    • When updating to 7.0.0 you should be able to just do a simple search and replace for this matcher across your codebase.

🍾 Improvements

  • Add support for unboxed properties for toMatchElement. (@blainekasten)
  • Improve documentation for the entire repo. (@blainekasten)
  • Improve internal tests.

6.1.2

  • Try to fix a failed publish. (@blainekasten)

6.1.1

  • Fix duplicate typescript definition. (@GreenGremelin)

6.1.0

  • Added 3 new matchers! toContainMatchingElement, toContainMatchingElements and toContainMatchingElements (@GreenGremlin)

6.0.5

  • Fix typescript definitions for toMatchElement options argument. (@mayhewluke)

6.0.4

  • Fix global typescript definitions for jest-environment-enzyme. (@vkrol)

6.0.3

  • Add global typescript definitions for jest-environment-enzyme. (@astorije)
  • Allow multiline strings for toHaveHTML. (@astorije)
  • Print local error messages when jest-environment-enzyme has an issue. (@h.ayabe)

6.0.2

  • Loosen jest-envirnoment-enzyme react peerDependency to support testing other react versions. (@evocateur)

6.0.1

  • Fix jest-environment-enzyme to actually work with different react adapter versions. (@evocateur)

6.0.0

🛑 Breaking

  • jest-environment-enzyme now requires you to install your enzyme-adapter to your project root. (@blainekasten)
    • In 5.0.0 we wrongfully didn't require developers to do that hoping we could manage it internally.
    • This resulted in bloated dependencies, and peerDependency errors.
    • This fix requires a tiny bit more work from the user but is correct!

🍾 Improvements

  • Improve jasmine-enzymes error messages to not be contradicting. (@blainekasten)

5.0.3

  • Fix an internal flowtype issue. (@fernandopasik)

5.0.2

  • Improve the scope of what files eslint-config-jest-enzyme affects. (@blainekasten)

5.0.1

  • Remove unnecassary rAF polyfill. (@SimenB)
  • Fix flow typing for toHaveProp. (@theneva)
  • Remove unused dependency from jest-environment-enzyme. (@SimenB)

5.0.0

🛑 Breaking

  • Removed toBePresent and toBeEmpty in favor of a new matcher toExist. (@blainekasten)

🚀 New Features

  • New Package! jest-environment-enzyme (@blainekasten)
  • New Package! eslint-config-jest-enzyme (@blainekasten)
  • New Matcher toBeEmptyRender to assert when a component returns null or undefined. (@theneva)
  • toHaveStyle, toHaveProp and toHaveState now all can accept an object as a list of key,values to match against. (@blainekasten)
  • Using yarn workspaces locally now. (@blainekasten)

🍾 Improvements

  • Improved error message when using an enzyme-matcher assertion with a non-enzyme argument. (@blainekasten)
  • Improve the message output from toHaveClassName. (@theneva)
  • toBeChecked previously failed on undefined or null values, but is now fixed. (@pascalduez)

4.2.0

  • Handle an array of styles in the toHaveStyle assertion (@dennis-tra)

4.1.1

4.1.0

  • Internal CI fixes (@blainekasten)
  • Minor: toMatchElement ignores props by default now. This should not break anyones existing tests. If it does, please report it. If you want to test an element without matching the props, pass { ignoreProps: false } as a second argument. (@finnigantime)

4.0.2

  • Update enzyme-to-json to support React 16.2 (@rtymchyk)

4.0.1

  • Remove the dependency on @types/react (@Vinnl)

4.0.0

  • Support React 16 and Enzyme 3 (@blainekasten)
  • Remove beforeEnter call for jest-enzyme and just add the matchers once. (@mockdeep)

3.8.3

  • Fix missing flow annotation that caused issues with flow 0.54. (@fabiob)

3.8.2

  • Fix flow issues that cropped up from 3.8.1. (@blainekasten)

3.8.1

  • Fix a bug that prevents this library from working with Jest 21+. (@nigelzor)

3.8.0

  • Intentionally passing undefined to toHaveState and toHaveProps now compares on the undefined value. (@DianaSuvorova)

3.7.0

  • Fix pretty printing Proxy objects in components (@chris-divvito)
  • Fix negative messages in jasmine-enzyme (@blainekasten)
  • Address some internal issues that broke tests in CI (@blainekasten)

3.6.1

  • Fix a bad publish with 3.6.0 not including all documented changes

3.6.0

  • Implement jest asymettric matchers and jasmine partial matchers!! (@sfargier)
    • This means you can use API's like expect.any(String) in jest or jasmine.stringMatching('%')
  • Fix a bug with the transpiled code not runnable in browsers (@ek5000)
  • Make the typescript definition for jest-enzyme more accurate (@sfargier)
  • internal: enzyme-matchers is built in Prettier now! (@blainekasten)
  • internal: Fix a local issue with our yarn.lock (@blainekasten)

3.5.3

  • Point to lib TS file (@pascalduez)

3.5.2

  • Add the missing export of the toMatchElement assertion (@vkrol)

3.5.1

  • Fix the TS definition for toContainReact (@pselden)

3.5.0

  • Include TS definitions in exported library (@Dean177)
  • Fix a bug that can occur when you are mocking console.error in your tests. (@juanca)
  • [internal] Use babel-preset-env (@pascalduez)
  • [internal] Improve flowtype usage (@pascalduez)

3.4.0

  • Add toMatchElement TS Declaration (@pascalduez)
  • Prevented toHaveProps from mutating arguments (@moredip)
  • Ensure flowtypes are published as part of the packages (@pascalduez)

3.3.0

  • Fix typescript return types (@Dean177)
  • Fix Flowtype integration by not publishing src/ files (@SBoudrias)
  • NEW! Added toMatchElement(reactInstance) matcher (@finnigantime)

3.2.0

  • Publish types for Flow integration support
  • Fix an issue where console may not be available in certain environments
  • Expose matchers directly for jasmine-enzyme
    • This is particularily benefecial for jasmine v1 users
    • Access if found at jasmineEnzyme.enzymeMatchers
  • Fix an issue with using shallow wrappers when running tests in IE

3.1.1

  • Fix a bug when running tests in IE

3.1.0

  • Add Typescript definitions

3.0.1

  • Fix a failed version publish

3.0.0

  • This version updates the requirement for jest-enzyme to jest versions 19 or greater
  • Automatically inject a serializer for enzyme components to be snapshotted
  • Bugfix: Prevent shallow wrappers from being deeply rendered by our internal html utils

2.1.2

  • Remove dependency on colors package
  • Fix stringify to not crash on null values

2.1.1

  • Fix the way we looked up internals of react for latest version

2.1.0

  • Fix matcher messages from always sounding positive, even when negated

2.0.0

  • Changed project structure!
  • We are now using lerna to maintain 3 npm packages:

    • enzyme-matchers (simple functions to handle assertions)
    • jasmine-enzyme (implementation of enzyme-matchers in jasmine)
    • jest-enzyme (_implementation of enzyme-matchers in jest)
  • This is only breaking if you use Jest.

    • If you do, simply change to use the jest-enzyme package and everything should work.

1.2.0

  • Fixed negated matchers output message to sound negated.

1.1.0

  • Add toHaveText matcher

1.0.1

  • Include repository in package.json

1.0.0

  • Rename toContain to toContainReact to prevent core matcher overwrite
  • Rename toMatch to toMatchSelector to prevent core matcher overwrite

0.2.3

  • Remove jasmine from the peerDependencies list
    • Jasmine is implicity with the library
    • the peerDep caused issues with npm2 and jest

0.2.2

0.2.1 was a failed release

  • Fix flowtype issues

0.2.0

  • Add toHaveStyle matcher

0.1.0

  • Initial Implementation