0
0
Node.jsframework~30 mins

Why testing matters in Node.js - See It in Action

Choose your learning style9 modes available
Why Testing Matters in Node.js
📖 Scenario: You are building a simple Node.js module that calculates the total price of items in a shopping cart. To make sure your code works correctly and keeps working as you add features, you will write tests.
🎯 Goal: Build a Node.js module with a function to sum item prices and write a basic test to check it works correctly.
📋 What You'll Learn
Create a list of item prices as numbers
Create a variable to hold the total price starting at 0
Write a function that sums all prices in the list
Write a simple test using Node.js assert to check the function output
💡 Why This Matters
🌍 Real World
Testing helps catch mistakes early and keeps your code working as you add new features, just like checking your work in school before submitting.
💼 Career
Writing tests is a key skill for software developers to ensure code quality and reliability in real projects.
Progress0 / 4 steps
1
Create the list of item prices
Create a variable called prices and set it to an array with these exact numbers: 10, 20, 30
Node.js
Need a hint?

Use const to create an array named prices with the numbers 10, 20, and 30 inside square brackets.

2
Create a variable to hold the total price
Create a variable called total and set it to 0 to start counting the sum of prices
Node.js
Need a hint?

Use let to create a variable named total and set it to 0.

3
Write a function to sum all prices
Write a function called calculateTotal that takes the prices array and returns the sum of all prices using a for loop with price as the iterator variable
Node.js
Need a hint?

Define a function named calculateTotal that loops over prices using for (const price of prices) and adds each price to a sum variable, then returns sum.

4
Write a simple test to check the function
Import Node.js assert module and write a test using assert.strictEqual to check that calculateTotal(prices) equals 60
Node.js
Need a hint?

Use import assert from 'assert' at the top and then write assert.strictEqual(calculateTotal(prices), 60) to check the function returns 60.