Testing with TypeScript, Enzyme, and React

TypeScript and Enzyme can provide a friendly, typesafe alternative to React’s own testing facilities. While we’ve previously looked at testing TypeScript with Jest and React’s own ShallowRenderer, it’s little trouble to add Enzyme’s rich selector syntax to the mix.

Setting up Jest

If you’ve already configured Jest via the earlier tutorial or the create-react-app bootstrap, skip ahead to the next section. Otherwise, let’s make sure the runner is installed!

$ npm install --save-dev raf jest ts-jest @types/jest

We’ll also need to configure jest to compile TypeScript files and prepare it for Enzyme. Add a "jest" entry in package.json with the following:

  "jest": {
    "moduleFileExtensions": ["ts", "tsx", "js"],
    "transform": {
      "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "setupFiles": [
      "raf/polyfill"
    ],
    "testRegex": "/__tests__/.*\\.(ts|tsx|js)$",
    "setupTestFrameworkScriptFile": "<rootDir>src/setupTests.ts"
  }

That’s it! We’re ready to go.

Just add Enzyme

Enzyme installation with TypeScript barely changes from vanilla JavaScript. Just grab the package, a react adapter, and the corresponding type definitions:

$ npm install --save-dev enzyme enzyme-adapter-react-16
$ npm install --save-dev @types/enzyme @types/enzyme-adapter-react-16

We’ll need to configure Enzyme to use the adapter, which we can do in Jest’s bootstrap file. Except for a wildcard import, this looks exactly as it would in JavaScript:

// src/setupTests.ts
import * as Enzyme from 'enzyme'
import * as Adapter from 'enzyme-adapter-react-16'

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

Finally, if we want to take advantage of what might be Jest’s knockout feature, we’ll also need an enzyme-compatible snapshot serializer:

$ npm install --save-dev enzyme-to-json

Add the serializer to the jest configuration in package.json, and we’re ready to get on to the tests.

{
  "jest": {
    "snapshotSerializers": ["enzyme-to-json"]
  }
}

Start Testing

Let’s put Enzyme’s shallow renderer to work to make sure everything is up and running:

// __tests__/hello_world.test.js
import { shallow } from 'enzyme'

describe('Hello, Enzyme!', () => {
  it('renders', () => {
    const wrapper = shallow(<div>
      <h1>Hello, Enzyme!</h1>
    </div>)
    expect(wrapper.find('h1').html()).toMatch(/Hello, Enzyme/)
  })

  it('renders snapshots, too', () => {
    const wrapper = shallow(<div>
      <h1>Hello, Enzyme!</h1>
    </div>)
    expect(wrapper).toMatchSnapshot()
  })
})

Hit “run”, and it’s all green. We’re set up and ready to begin testing with Enzyme!

Find a demo of Enzyme testing several common React patterns in the React with TypeScript repository on Github.

Featured