Convert Figma logo to code with AI

enzymejs logoenzyme

JavaScript Testing utilities for React

19,954
2,008
19,954
282

Top Related Projects

19,952

JavaScript Testing utilities for React

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

44,166

Delightful JavaScript Testing.

46,847

Fast, easy and reliable testing for anything that runs in a browser.

89,091

JavaScript API for Chrome and Firefox

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

Quick Overview

Enzyme is a JavaScript testing utility for React that makes it easier to test React Components' output. It allows you to manipulate, traverse, and in some ways simulate runtime given the output of your components.

Pros

  • Provides a simple and intuitive API for testing React components
  • Supports shallow rendering, full DOM rendering, and static rendering
  • Works well with Jest and other testing frameworks
  • Extensive documentation and community support

Cons

  • Not officially supported by the React team
  • Can be slower than other testing libraries for large component trees
  • May encourage testing implementation details rather than behavior
  • Requires additional setup and configuration compared to React Testing Library

Code Examples

  1. Shallow rendering a component:
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';

const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.my-class')).toHaveLength(1);
  1. Full DOM rendering and interacting with elements:
import { mount } from 'enzyme';
import Button from './Button';

const wrapper = mount(<Button onClick={jest.fn()}>Click me</Button>);
wrapper.find('button').simulate('click');
expect(wrapper.prop('onClick')).toHaveBeenCalled();
  1. Testing component state:
import { shallow } from 'enzyme';
import Counter from './Counter';

const wrapper = shallow(<Counter />);
expect(wrapper.state('count')).toBe(0);
wrapper.find('button').simulate('click');
expect(wrapper.state('count')).toBe(1);

Getting Started

  1. Install Enzyme and its adapter:
npm install --save-dev enzyme @wojtekmaj/enzyme-adapter-react-17
  1. Set up the adapter in your test setup file:
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';

Enzyme.configure({ adapter: new Adapter() });
  1. Write your first test:
import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
  it('renders correctly', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find('h1').text()).toBe('Hello, World!');
  });
});

Competitor Comparisons

19,952

JavaScript Testing utilities for React

Pros of enzyme

  • Well-established and widely adopted testing utility for React
  • Extensive documentation and community support
  • Supports shallow rendering for isolated component testing

Cons of enzyme

  • Not actively maintained, with the last release in 2019
  • Lacks support for newer React features and versions
  • May require additional configuration and adapters for modern React projects

Code Comparison

enzyme:

import { shallow } from 'enzyme';

const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.my-class')).toHaveLength(1);
expect(wrapper.state('myState')).toEqual(expectedValue);

enzyme:

import { shallow } from 'enzyme';

const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.my-class')).toHaveLength(1);
expect(wrapper.state('myState')).toEqual(expectedValue);

Summary

The comparison between enzyme and enzyme is not applicable, as they are the same repository. The provided information reflects the characteristics of the enzyme library itself. enzyme is a popular testing utility for React applications, offering features like shallow rendering and easy component traversal. However, its lack of recent updates and limited support for newer React versions are significant drawbacks. Users should consider alternative testing libraries that are actively maintained and compatible with modern React development practices.

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

Pros of react-testing-library

  • Encourages testing from a user's perspective, focusing on behavior rather than implementation details
  • Simpler API with fewer methods, making it easier to learn and use
  • Better support for testing accessibility and ARIA attributes

Cons of react-testing-library

  • Less flexibility for testing component internals and state
  • May require more setup for complex scenarios or edge cases
  • Limited support for shallow rendering, which can be useful for unit testing

Code Comparison

react-testing-library:

import { render, fireEvent } from '@testing-library/react';

test('button click', () => {
  const { getByText } = render(<Button />);
  fireEvent.click(getByText('Click me'));
  expect(getByText('Clicked!')).toBeInTheDocument();
});

Enzyme:

import { shallow } from 'enzyme';

test('button click', () => {
  const wrapper = shallow(<Button />);
  wrapper.find('button').simulate('click');
  expect(wrapper.text()).toContain('Clicked!');
});

The react-testing-library example focuses on user interactions and visible content, while the Enzyme example interacts directly with component elements and checks internal state.

44,166

Delightful JavaScript Testing.

Pros of Jest

  • Built-in test runner, assertion library, and mocking capabilities
  • Snapshot testing for UI components
  • Parallel test execution for faster performance

Cons of Jest

  • Steeper learning curve for complex configurations
  • Slower startup time for large projects
  • Less flexibility in choosing individual testing tools

Code Comparison

Jest:

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

Enzyme:

it('renders welcome message', () => {
  const wrapper = shallow(<Welcome />);
  expect(wrapper.find('h1').text()).toEqual('Welcome');
});

Key Differences

  • Jest is a complete testing solution, while Enzyme focuses on React component testing
  • Enzyme provides more detailed component manipulation and traversal
  • Jest offers better integration with Create React App and other popular frameworks

Use Cases

  • Jest: Full-stack JavaScript applications, React projects
  • Enzyme: Specialized React component testing, legacy React applications

Community and Ecosystem

Jest has a larger community and more frequent updates, while Enzyme has a more focused user base for React testing.

46,847

Fast, easy and reliable testing for anything that runs in a browser.

Pros of Cypress

  • Provides an all-in-one testing solution with built-in assertion library and mocking capabilities
  • Offers real-time browser testing with automatic waiting and retry mechanisms
  • Features a user-friendly interface for test debugging and time-travel

Cons of Cypress

  • Limited to testing web applications in Chrome-based browsers
  • Slower test execution compared to Enzyme due to running tests in a real browser
  • Steeper learning curve for developers familiar with traditional unit testing frameworks

Code Comparison

Cypress test example:

describe('Login', () => {
  it('should log in successfully', () => {
    cy.visit('/login')
    cy.get('#username').type('user@example.com')
    cy.get('#password').type('password123')
    cy.get('button[type="submit"]').click()
    cy.url().should('include', '/dashboard')
  })
})

Enzyme test example:

describe('Login', () => {
  it('should log in successfully', () => {
    const wrapper = mount(<Login />)
    wrapper.find('#username').simulate('change', { target: { value: 'user@example.com' } })
    wrapper.find('#password').simulate('change', { target: { value: 'password123' } })
    wrapper.find('button[type="submit"]').simulate('click')
    expect(wrapper.find(Dashboard)).toHaveLength(1)
  })
})
89,091

JavaScript API for Chrome and Firefox

Pros of Puppeteer

  • Provides a full browser environment for end-to-end testing
  • Supports screenshots and PDF generation
  • Can automate user interactions like clicking and typing

Cons of Puppeteer

  • Slower test execution compared to Enzyme
  • Requires more setup and resources
  • Less suitable for unit testing React components

Code Comparison

Enzyme (shallow rendering):

const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.my-class')).toHaveLength(1);
expect(wrapper.text()).toContain('Hello, World!');

Puppeteer (browser automation):

await page.goto('https://example.com');
await page.click('.my-button');
const text = await page.$eval('.my-class', el => el.textContent);
expect(text).toContain('Hello, World!');

Summary

Enzyme is primarily designed for unit testing React components, offering shallow rendering and easy component manipulation. It's fast and lightweight but limited to React-specific testing.

Puppeteer, on the other hand, provides a full browser environment for end-to-end testing. It's more versatile, supporting various web technologies and allowing for complex user interaction simulations. However, it's slower and requires more resources than Enzyme.

Choose Enzyme for quick, focused React component tests, and Puppeteer for comprehensive end-to-end testing or when you need to interact with a full browser environment.

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

Pros of Playwright

  • Cross-browser support for Chromium, Firefox, and WebKit
  • Built-in auto-wait functionality for improved test stability
  • Powerful API for handling modern web features like shadow DOM

Cons of Playwright

  • Steeper learning curve due to more comprehensive API
  • Larger package size and potentially slower installation

Code Comparison

Playwright:

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await browser.close();
})();

Enzyme:

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

const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.my-class')).toHaveLength(1);

Key Differences

  • Playwright focuses on end-to-end testing across browsers, while Enzyme specializes in React component testing
  • Playwright offers a more comprehensive solution for modern web applications, including mobile emulation
  • Enzyme provides a simpler API for shallow rendering and component isolation

Use Cases

  • Choose Playwright for full end-to-end testing of web applications across multiple browsers
  • Opt for Enzyme when focusing specifically on unit testing React components

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Enzyme

Join the chat at https://gitter.im/enzymejs/enzyme

npm Version License Build Status Coverage Status

Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components' output. You can also manipulate, traverse, and in some ways simulate runtime given the output.

Enzyme's API is meant to be intuitive and flexible by mimicking jQuery's API for DOM manipulation and traversal.

Upgrading from Enzyme 2.x or React < 16

Are you here to check whether or not Enzyme is compatible with React 16? Are you currently using Enzyme 2.x? Great! Check out our migration guide for help moving on to Enzyme v3 where React 16 is supported.

Installation

To get started with enzyme, you can simply install it via npm. You will need to install enzyme along with an Adapter corresponding to the version of react (or other UI Component library) you are using. For instance, if you are using enzyme with React 16, you can run:

npm i --save-dev enzyme enzyme-adapter-react-16

Each adapter may have additional peer dependencies which you will need to install as well. For instance, enzyme-adapter-react-16 has peer dependencies on react and react-dom.

At the moment, Enzyme has adapters that provide compatibility with React 16.x, React 15.x, React 0.14.x and React 0.13.x.

The following adapters are officially provided by enzyme, and have the following compatibility with React:

Enzyme Adapter PackageReact semver compatibility
enzyme-adapter-react-16^16.4.0-0
enzyme-adapter-react-16.3~16.3.0-0
enzyme-adapter-react-16.2~16.2
enzyme-adapter-react-16.1~16.0.0-0 || ~16.1
enzyme-adapter-react-15^15.5.0
enzyme-adapter-react-15.415.0.0-0 - 15.4.x
enzyme-adapter-react-14^0.14.0
enzyme-adapter-react-13^0.13.0

Finally, you need to configure enzyme to use the adapter you want it to use. To do this, you can use the top level configure(...) API.

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

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

3rd Party Adapters

It is possible for the community to create additional (non-official) adapters that will make enzyme work with other libraries. If you have made one and it's not included in the list below, feel free to make a PR to this README and add a link to it! The known 3rd party adapters are:

Adapter PackageFor LibraryStatus
enzyme-adapter-preact-purepreact(stable)
enzyme-adapter-infernoinferno(work in progress)

Running Enzyme Tests

Enzyme is unopinionated regarding which test runner or assertion library you use, and should be compatible with all major test runners and assertion libraries out there. The documentation and examples for enzyme use Mocha and Chai, but you should be able to extrapolate to your framework of choice.

If you are interested in using enzyme with custom assertions and convenience functions for testing your React components, you can consider using:

Using Enzyme with Mocha

Using Enzyme with Karma

Using Enzyme with Browserify

Using Enzyme with SystemJS

Using Enzyme with Webpack

Using Enzyme with JSDOM

Using Enzyme with React Native

Using Enzyme with Jest

Using Enzyme with Lab

Using Enzyme with Tape and AVA

Basic Usage

Shallow Rendering

import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import sinon from 'sinon';

import MyComponent from './MyComponent';
import Foo from './Foo';

describe('<MyComponent />', () => {
  it('renders three <Foo /> components', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find(Foo)).to.have.lengthOf(3);
  });

  it('renders an `.icon-star`', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find('.icon-star')).to.have.lengthOf(1);
  });

  it('renders children when passed in', () => {
    const wrapper = shallow((
      <MyComponent>
        <div className="unique" />
      </MyComponent>
    ));
    expect(wrapper.contains(<div className="unique" />)).to.equal(true);
  });

  it('simulates click events', () => {
    const onButtonClick = sinon.spy();
    const wrapper = shallow(<Foo onButtonClick={onButtonClick} />);
    wrapper.find('button').simulate('click');
    expect(onButtonClick).to.have.property('callCount', 1);
  });
});

Read the full API Documentation

Full DOM Rendering

import React from 'react';
import sinon from 'sinon';
import { expect } from 'chai';
import { mount } from 'enzyme';

import Foo from './Foo';

describe('<Foo />', () => {
  it('allows us to set props', () => {
    const wrapper = mount(<Foo bar="baz" />);
    expect(wrapper.props().bar).to.equal('baz');
    wrapper.setProps({ bar: 'foo' });
    expect(wrapper.props().bar).to.equal('foo');
  });

  it('simulates click events', () => {
    const onButtonClick = sinon.spy();
    const wrapper = mount((
      <Foo onButtonClick={onButtonClick} />
    ));
    wrapper.find('button').simulate('click');
    expect(onButtonClick).to.have.property('callCount', 1);
  });

  it('calls componentDidMount', () => {
    sinon.spy(Foo.prototype, 'componentDidMount');
    const wrapper = mount(<Foo />);
    expect(Foo.prototype.componentDidMount).to.have.property('callCount', 1);
    Foo.prototype.componentDidMount.restore();
  });
});

Read the full API Documentation

Static Rendered Markup

import React from 'react';
import { expect } from 'chai';
import { render } from 'enzyme';

import Foo from './Foo';

describe('<Foo />', () => {
  it('renders three `.foo-bar`s', () => {
    const wrapper = render(<Foo />);
    expect(wrapper.find('.foo-bar')).to.have.lengthOf(3);
  });

  it('renders the title', () => {
    const wrapper = render(<Foo title="unique" />);
    expect(wrapper.text()).to.contain('unique');
  });
});

Read the full API Documentation

React Hooks support

Enzyme supports react hooks with some limitations in .shallow() due to upstream issues in React's shallow renderer:

  • useEffect() and useLayoutEffect() don't get called in the React shallow renderer. Related issue

  • useCallback() doesn't memoize callback in React shallow renderer. Related issue

ReactTestUtils.act() wrap

If you're using React 16.8+ and .mount(), Enzyme will wrap apis including .simulate(), .setProps(), .setContext(), .invoke() with ReactTestUtils.act() so you don't need to manually wrap it.

A common pattern to trigger handlers with .act() and assert is:

const wrapper = mount(<SomeComponent />);
act(() => wrapper.prop('handler')());
wrapper.update();
expect(/* ... */);

We cannot wrap the result of .prop() (or .props()) with .act() in Enzyme internally since it will break the equality of the returned value. However, you could use .invoke() to simplify the code:

const wrapper = mount(<SomeComponent />);
wrapper.invoke('handler')();
expect(/* ... */);

Future

Enzyme Future

Contributing

See the Contributors Guide

In the wild

Organizations and projects using enzyme can list themselves here.

License

MIT

NPM DownloadsLast 30 Days