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

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 and 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: ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.