Javascript - Jest Test Runner

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > Javascript - Test

1 - About

Jest is a test runner from Facebook for client-side JavaScript applications and React applications specifically.

Jest ships with jsdom.

Advertising

3 - Installation

3.1 - Jest

  • Cli
yarn global add jest
npm install -g jest
  • Locally for the project
npm install # if jest is already in package.json
npm install --save-dev jest
+ [email protected]
added 388 packages, removed 112 packages and moved 1 package in 61.669s

3.2 - Es Grammar

Because JEST is node process, it doesn't understand ES6 modules (no import). Babel will be used to transpiler the import statement of Es6.

  • babel (npm > version 3)
npm install --save-dev babel-jest babel-core
  • Babel es2015
npm install --save-dev babel-cli babel-preset-es2015
  • .bablerc. babel-jest is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project.
{
  "presets": ["es2015"]
}

webpack 2 offers native support for ES modules. However, Jest runs in Node, and thus requires ES modules to be transpiled to CommonJS modules. As such, if you are using webpack 2, you most likely will want to configure Babel to transpile ES modules to CommonJS modules only in the test environment.

Advertising

3.3 - Idea

4 - Usage

https://facebook.github.io/jest/docs/en/cli.html

  • Init to create a jest.config.js
jest --init

5 - File Structure

Jest will look for test files with any of the following popular naming conventions:

  • Files with .js suffix in __tests__ folders.
  • Files with .test.js suffix.
  • Files with .spec.js suffix.

The .test.js / .spec.js files (or the __tests__ folders) can be located at any depth under the src top level folder.

It's recommended to collocate the test file with the source file (ie put the test files (or __tests__ folders) next to the code they are testing ) because of:

  • shorter relative imports (ie /Source)
  • searching the test is easier
Advertising

6 - Run

test is a global variable injected by Jest. You need to run your tests through jest

  • Test
test('3 equal 3', () => {
    expect(3).toBe(3);
});
  • Run
jest my-test --notify --config=config.json

7 - Documentation / Reference

web/javascript/test/jest.txt · Last modified: 2019/06/18 09:27 by gerardnico