Test-driven development (TDD) is an approach to development that consists of writing tests, followed by production code, and refactoring as needed. The tests are written to fail initially, and the developer writes code to fulfill the requirements of the test so they pass.

In this tutorial, we’ll learn how to implement the TDD process by developing a simple command line calculator app from scratch with Node.js. In case you’re unfamiliar, Node.js allows the use of JavaScript on the server side. Read the getting started article to get up to speed with Node.js. We’re going to set up tests with Mocha, a testing framework, for this app.

You’ll also learn how to use the built-in readline module in Node.js to send commands to the program via the command line.

Goals

  • The application should add, subtract, divide, and multiply any two numbers
  • The application should display a warning and exit if it receives any input that does not consist of numbers
  • The system will provide a command line interface that allows the end users to utilize program functionality

Now that we know what app should do, we can begin setting up the environment for testing and developing.

Prerequisites

Setting Up Our Environment

Since our application runs in Node.js, we will need to set up a local environment for our files and dependencies.

Create a new directory called calc. In the command prompt, navigate to the directory and initialize a new project using npm init, which will create a new package.json file for our program.

npm init

You will be prompted to enter the package name, version, description, and other common package details. We can enter the name calc.js, and continue along pressing ENTER for all the default items, giving a description if you’d like. When you reach test command, type mocha, which is the testing framework we will be using.

test command: mocha

Continue entering the defaults until the walkthrough is complete. The script will create a package.json file that looks like this:

package.js

{
  "name": "calc.js",
  "version": "1.0.0",
  "description": "A simple calculator application built with Node.js",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "author": "",
  "license": "ISC"
}

#javascript #testing

Unit Testing in JavaScript with Mocha
1.10 GEEK