Java script Testing Part-1
Step-1: Create a New Folder and run npm init to create package.json
Step 1: Run npm i — save-dev jest. This will install jest as dev dependency , and we want tests to be in development and not production environment.

Step 2: Create two JavaScript files, sum.js
and sub.js
, along with their corresponding test files. The test files must have the .test.js
extension. While you can name test files anything according to naming convention, they should ideally have the same name as the file they are testing.
Step3: Write simple Sum file and export it using Common JS module syntax ,which will be afterwards imported in your test file. See the below code for sum.js and sum.test.js, similarly you can create sub.js and sub.test.js tests.
Explanation:
We call test function with 2 arguments , first one is the string which represent the descriptive name we want to give to our test and second is a function in which our tests will be executed.
expect(sum(5,8)) returns a an expectation object. This expectation object has various methods (These methods are called matchers) and toBe() method is one such matcher which checks for exact equality. The value returned by sum function is wrapped by expectation object.
For more info on various matchers visit: Using Matchers · Jest

Step 4: After this in package.json file add test script by adding “test”: “jest — coverage”. when you will enter => npm run test in the cmd then jest — coverage will be executed. Here coverage paramter is to tell how much code is covered by our tests.

Step 5: Now when you will run the command npm run test , such an output will be genrated , depicting information about your test suite.

You can try changing with values to see how it will affect the Results.
Step 6: You can experiment like if you add function sum1 and you have no test for it then it means one function is not covered by your test and following result will be displayed.

In the Files section you could see there is coverage folder generate because of — coverage that we used , from where we can these statistics much more clearly. You can visit index.html to see it.


Clicking on sum.js will tell which code is being not tested, it will be shown in red.
