Enzyme Testing

Valerie Kraucunas

Software Engineer, MassRoots

What i'll be covering

  • Brief Intro to Enzyme
  • Implement Enzyme on a new application

INTRO TO ENZYME

Started by Airbnb engineer Leland Richardson, since open sourced

Enzyme is a JavaScript Testing utility for React.

Making it easier to

  • assert
  • manipulate
  • traverse over

React components

INTRO TO ENZYME

Benefits of using Enzyme

  • Unopinionated
  • jQuery style DOM traversal
  • Mocking out components to test is clean

Makes asking questions about the rendered component easy and intuitive by providing a fluent interface.

INTRO TO ENZYME

Getting Started

npm i --save-dev enzyme
npm i --save-dev react-addons-test-utils
npm i --save-dev react-dom
npm i --save-dev chai-enzyme 
npm i --save-dev jasmine-enzyme
npm i --save-dev jest-enzyme
npm i --save-dev should-enzyme

Optional Assertion Libraries

*

INTRO TO ENZYME

Render All the Things!

Shallow

Render

Mount

  • Purest unit test
  • No children rendered!
  • Fastest rendering
  • Full DOM rendering
  • Includes most lifecycle methods
  • May need a headless browser package like jsdom
  • Renders static html, including children
  • Fewest lifecycle methods covered
  • Uses Cheerio

INTRO TO ENZYME

Example of basic test

import React from 'react';
import { shallow } from 'enzyme';
import ToDoList from '../components/ToDoList';

describe('<ToDoList />', () => {
  it('renders the entire list of items', () => {
    const items = [mockItem(), mockItem() /*, ... */];
    const wrapper = shallow(<ToDoList items={items} />);
    expect(wrapper.find(ToDoList)).to.have.length(items.length);
  });
});

Let's go do stuff

Best practices

  • Start with .shallow()
  • Always refresh your wrapper variable between tests
  • Only pass wrappers the required props for component to render
  • If you're having trouble writing a test for an existing component, consider rewriting the component to make it more testable
  • Pick an assertion syntax and stick to it

Thank you!

Valerie Kraucunas

valeriekraucunas@gmail.com

vkraucunas

RESOURCES

Enzyme Testing Lightning Talk

By Valerie Kraucunas

Enzyme Testing Lightning Talk

"Untested code is broken code." Enzyme, the testing utility for React, is flexible, intuitive, and compatible with most test runners. When matched with a test double library like Sinon.js, Enzyme becomes capable of unit testing both components and reducers. Together we'll cover the tradeoffs of the different rendering methods provided from Enzyme, best practices for writing test files, and upcoming features of Enzyme. (HTML5 Lightning Talks 3/2017)

  • 803