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

Made with Slides.com