Jest

Advertisement

Installation Installation

npm install jest
$ npm install jest
npm WARN deprecated request-promise-native@1.0.9: request-promise-native has been deprecated because it extends the now deprecated request package,
see https://github.com/request/request/issues/3142
npm WARN browser-sync-webpack-plugin@2.2.2 requires a peer of browser-sync@^2 but none is installed. You must install peer dependencies yourself.
npm WARN eslint-config-airbnb@18.2.0 requires a peer of eslint-plugin-react-hooks@^4 || ^3 || ^2.3.0 || ^1.7.0 but none is installed. You must install peer dependencies yourself.
npm WARN extract-text-webpack-plugin@3.0.2 requires a peer of webpack@^3.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN webpack-tutorial@1.0.0 No description
npm WARN webpack-tutorial@1.0.0 No repository field.

+ jest@26.4.2
added 399 packages from 166 contributors and audited 1825 packages in 140.326s

67 packages are looking for funding
  run `npm fund` for details

found 1 low severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details

Screenshot – https://i.imgur.com/o0idDeW.png

Top ↑

Configure Configure

Create jest.config.json and add below code:

{
    "testRegex": "((\\.|/*.)(test))\\.js?$"
}

Top ↑

Add Commands Add Commands

Open package.json and add below test and test:watch commands as below:

"scripts": {
    ..
    "test": "jest --config ./jest.config.json",
    "test:watch": "npm run test -- --watch"
},

Top ↑

Add first test Add first test

Create a file with *-test.js. E.g. I’m creating the index.test.js file.

Add below code within it:

test('Is TRUE?', () => {
    expect( true ).toBe( true );
});

Now, Execute npm run test:watch command.

You can see:

 PASS  src/index.test.js
  ? Is TRUE? (4 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.529 s
Ran all test suites related to changed files.

Another test Another test

test('Is 1 + 2 = 3 ?', () => {
    expect( 1 + 2 ).toBe( 3 );
});

test('Is 5 * 4 = 20 ?', () => {
    expect( 5 * 4 ).toBe( 20 );
});

Now our test automatically start. If not then execute npm run test:watch command.

You can see:

 PASS  src/index.test.js
  ? Is 1 + 2 = 3 ? (4 ms)
  ? Is 5 * 4 = 20 ? (1 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.411 s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.

Leave a Reply