Cypress Code Coverage

Profile picture for user arilio666

There is a testing metric in cypress called code coverage, which determines the number of codes successfully validated under a test procedure.

As more and more tests are written and pile up, there might be a question about whether some parts of the applications still need to be tested. Code coverage allows us to face common metrics like functional, statement, branches, condition, and line.

  • Function Coverage: Used to witness how many of the functions which have been defined have been called.
  • Statement Coverage: Used to witness how many statements in the program have been executed.
  • Branches Coverage: Used to witness how many branches have been executed in a control structure.
  • Condition Coverage: Used to witness boolean sub-expressions tested for true and false.
  • Line Coverage: Used to witness how many lines of source code are tested.

How Is Code Coverage Helpful?

  • It can help detect dead code and eliminate it.
  • For QA, it can help identify missed or uncovered test cases.
  • It can track the health status and quality of source code while paying attention to the uncaptured parts of the code.

Setting up code coverage takes three steps.

  1. First, we must instrument our code to know which statements are getting executed.
  2. We need to run that instrumented code to execute those statements.
  3. Finally, report and see how it got executed.

Instrumentation:

  • There are tools to instrument our code, like istanbul.js and nyc.
  • These are code instrumentation libraries.

Let us see how we can use these.

Example:

console.log('x')
if (true) {
   console.log('y')
}else{
   console.log('z')
}
console.log('a')
  • The output for this above code will be x, y, and a.
  • Since z is in the else part and the true condition is satisfied, we can conclude that body is neglected.
  • Let us see if nyc gives us this information.

Install nyc cli.

npm install -d nyc

Now run the code using nyc.

npx nyc node filename.js
NYC
  • It gives us a clear view of the statements it ran and the lines that are not covered.
  • We can also create an html report out of nyc.
npx nyc --reporter html --reporter text node ins.js
folder
  • We can see that an html file has been generated inside the coverage folder.
Report
  • This gives an excellent representation of what happened when the code ran.
     

Code Coverage for e2e web application codes will be covered in a separate article.