Getting Started with JavaScript Testing Using Jest

Overview

Write JavaScript tests using Jest.

Preparation

Since we want to use jest and ESModules, install babel-preset-2015. (Note: babel-jest is included with jest.)

npm install --save-dev jest babel-preset-2015

The contents of .babelrc should look like this:

The package.json file should look like this:

The directory structure should look like this: tree -a -I "node_modules"

There are two patterns for creating test files:

  • Files located under a directory named __tests__ are considered test files.
  • Files with extensions *.spec.js or *.test.js are considered test files.

In this case, we will use the latter format and place the test files in the test directory.

Writing Tests for Native JavaScript

Implement functions for addition and subtraction.

./src/native/calc.js

Test whether each function returns the correct calculation result.

./test/native/calc.test.js

describe(name, fn) creates a block to group multiple tests into a test suite.

Run the test: npm test ./test/native/calc.test.js

Test results:

Writing Tests for JavaScript Using ESModules

Create a class that implements methods for addition and subtraction.

./src/esmodules/calc.js

Test whether each method returns the correct calculation result.

./test/esmodules/calc.test.js

Matchers

Refer to Jest - Expect.

Thoughts

I think Jest's API is well-organized and easy to understand, even for first-time users. The documentation was also easy to read. It was easier than expected to get started with testing, which makes me want to actively write JavaScript tests.

References