0
0
Node.jsframework~30 mins

Code coverage basics in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Code coverage basics
📖 Scenario: You are working on a small Node.js project. You want to check how much of your code is tested by your tests. This helps you find parts of your code that need more testing.
🎯 Goal: Set up a simple Node.js function and a test file. Then configure a code coverage tool to measure how much of your function is tested.
📋 What You'll Learn
Create a Node.js function in a file called math.js
Create a test file called math.test.js that tests the function
Add a configuration to enable code coverage using nyc
Run the tests with coverage and verify the coverage report
💡 Why This Matters
🌍 Real World
Code coverage is used in real projects to check how much code is tested. This helps developers find untested parts and improve test quality.
💼 Career
Many software jobs require writing tests and using coverage tools like nyc to ensure code quality and reliability.
Progress0 / 4 steps
1
Create the function to test
Create a file called math.js and write a function named add that takes two parameters a and b and returns their sum.
Node.js
Need a hint?

Define a function named add with parameters a and b. Return their sum. Export the function using module.exports.

2
Write a test for the function
Create a file called math.test.js. Import the add function from math.js. Write a test using test that checks if add(2, 3) returns 5.
Node.js
Need a hint?

Import add from math.js. Use test to check if add(2, 3) equals 5.

3
Configure code coverage with nyc
Create a file called .nycrc in your project root. Add JSON content with { "all": true } to enable coverage for all files. Also, add a script in package.json called test:coverage that runs nyc --reporter=lcov --reporter=text npm test.
Node.js
Need a hint?

Create a .nycrc file with { "all": true }. Add a test:coverage script in package.json to run tests with coverage using nyc.

4
Run tests with coverage and check report
Run the command npm run test:coverage in your terminal. This runs your tests and shows a coverage report in text format. Verify that the coverage report shows 100% coverage for statements, branches, functions, and lines.
Node.js
Need a hint?

Run npm run test:coverage in your terminal. Look for the coverage summary showing 100% coverage.