-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Node.js Design Patterns - Fourth Edition
By :
We’ve extensively covered the wide world of testing, discussed the different types of tests, and highlighted guiding principles that help shape our testing mindset. Now, it’s finally time to roll up our sleeves and write some code!
Let’s start with a simple example using an e-commerce function. We’ll build a function called calculateBasketTotal() that takes a basket object as input. The basket contains an array of items, where each item has a name, unitPrice, and quantity. A little spoiler – our initial implementation contains a subtle bug that our test will later expose:
// calculateBasketTotal.js
export function calculateBasketTotal(basket) {
let total = 0
for (const item of basket.items) {
total += item.unitPrice
}
return total
}
For our initial test, we are going to write a simple script that uses Node.js’s built-in assert library to validate our code:
// test...