Setting up Enzyme with Mocha


How do we go about testing our React components?

A popular approach is to use Enzyme, which is a React testing utility. Let’s use it with Mocha, a Node.js test runner.

Install the dependencies:

npm install react react-dom react-addons-test-utils enzyme mocha

Add the following to your project’s .babelrc:

{ "presets": ["es2015", "react"] }

The above config will be used when you run babel.

Update package.json with the npm script for test.

You can either follow babel’s recommendation:

{
  "scripts": {
    "test": "mocha --compilers js:babel-register"
  }
}

Or mocha’s recommendation:

{
  "scripts": {
    "test": "mocha --require babel-register"
  }
}

In either scenario, babel will compile the JavaScript files based on your .babelrc.

Now you can run your tests:

npm test

Check out Enzyme’s repository for basic usage and examples.

Advanced

You can also specify a different directory to run your tests.

To run tests that match ./lib/*.js:

mocha --require babel-register lib/

Or even subdirectories with a glob pattern:

mocha --require babel-register lib/**/*.spec.js

For Windows compatibility, wrap the glob in quotes:

mocha --require babel-register 'lib/**/*.spec.js'


Please support this site and join our Discord!