Chapter 6. Modules in JavaScript

A module is a function or object that presents an interface but that hides its state and implementation.

Douglas Crockford, JavaScript: The Good Parts (O’Reilly, 2008)

In this chapter, we’ll take several actions that clean up and improve our JavaScript code. We’ll separate our test code from our production code using JavaScript modules. There are several ways to write modules in JavaScript—we’ll look at four different styles and their applicability to our code. We’ll turn our attention to how our test code is organized, then improve how it runs and the output it produces. Finally, we’ll remove some redundancy in our tests. That’s a lot of work, so let’s get to it!

Separating Our Code into Modules

Let’s separate the Money and Portfolio classes from the test code. We create two new files named money.js and portfolio.js in the same folder as test_money.js and move the relevant code there. Here’s our new folder structure:

js
├── money.js
├── portfolio.js
└── test_money.js

This is how portfolio.js looks:

class Portfolio {
    constructor() {
        this.moneys = [];
    }

    add(...moneys) {
        this.moneys = this.moneys.concat(moneys);
    }

    evaluate(currency) {
        let total = this.moneys.reduce((sum, money) => {
            return sum + money.amount;
        }, 0);
        return new Money(total, currency);
    }
}

The file money.js, not shown here, similarly contains the Money class and its methods.

When we now run our tests by executing node js/test_money.js from the TDD_Project_Root folder, we get our ...

Get Learning Test-Driven Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.