Monday, December 31, 2018

Configuring JEST and running test cases to get the coverage report

Test Driven Development became the basis of all the modern projects. That means people write the test cases first and then write the actual code to pass those test cases afterward.

Due to this, the demand for different testing frameworks is getting more and more.

Some of the testing frameworks that are most popular, under the category of Unit Testing, are:
  1. Mocha
  2. Jest
  3. Ava
These are some of the names that are too popular and are widely accepted in the Javascript Community.

I tried Mocha and found some difficulties in configuring it with my project and tried Jest, that comes with coverage report via Istanbul, and yeah it did well.

Today, we will see a basic project with 3 modules inside src, namely, add, mul and square with the functionality of adding, multiply and square.

Now in order to test these 3 modules, we created a directory called test in the main directory and will create the same folder structure as the src has.

For reference here is the snapshot of the folder structure.



By default, JEST picks the files that are under the test named folder and runs every file, with all the unit test cases, mentioned inside them.

Also, we have configured the JEST inside the package.json (line no: 18)only. Here is, package.json


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
{
  "name": "demo-mocha-nyc",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node src/index.js",
    "test": "./node_modules/.bin/jest",
    "test:watch": "./node_modules/.bin/jest --watch",    
    "test:coverage": "./node_modules/.bin/jest --coverage --colors"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "chai": "^4.2.0",
    "jest": "^23.6.0"
  },
  "jest": {
    "collectCoverage": true,
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}",
      "!**/node_modules/"
    ],
    "coverageReporters": [
      "json",
      "html",
      "text",
      "json-summary"
    ]
  }
}


For further properties, you can check out JEST docs, here.

In this example, we told Jest to cover anything under src/ folder and ignore all the files of node_modules/ folder. Also just fyi, test folder is by default picked for test case files and is auto ignored while coverage report.

I have created a demo project here, to explain the above example

Happy Coding :)

No comments:

Post a Comment