TDD with Node

Install Homebrew

We're going to start by installing Homebrew which will make installing everything else we need much easier.

Open a Terminal window and copy and paste the following into your terminal:

$ ruby -e "$(curl -fsSL"

Then ensure you have the latest version of Homebrew by typing the following:

$ brew update

And finally, ensure that Homebrew's environment is in a healthy state:

$ brew doctor

This may give you some commands to run in order to fix any problems, which you should do before continuing.

Install Node

Now we're ready to install Node on our system. We'll be using Homebrew to do that.

$ brew install node

Creating a Project

Let’s make a directory for our project:

$ mkdir piglatin-node
$ cd piglatin-node

Then lets set up dependency management for our project using npm:

$ npm init

Dependency Management

When building a software project you will often use libraries created by other people. In order to both specify and automatically download these dependencies you'll want to use a dependency management system.

Add Testing Framework

In order to express the requirements of our code we're going to use a testing framework. Testing frameworks, at their most basic, allow you to test the output of a function when given a certain input.

Now let’s install the Jasmine testing framework:

$ npm install --save-dev jasmine
$ npm install --global jasmine

Jasmine will then be added to both your project’s package.json (--save-dev) as well as globally (--global) so you can easilly use it from the command-line.

Now we’ll initialize our project to use Jasmine:

$ jasmine --init

Then run jasmine to ensure everything is set up correctly

Our First Failing Test

Let's create a test for our first requirement - translating apple to appleway.

Create the file test/odenay_test.js with the following contents:

describe("translateWord", function () {
  it("should translate the word", function () {
    var result = piglatin.translateWord("apple");

And then run your test using jasmine to see it fail:

$ jasmine

1) translateWorld should translate the word
    ReferenceError: piglatin is not defined
    ReferenceError: piglatin is not defined
        at Object.<anonymous> (/Users/bkelly/temp/piglatin-nodejs/spec/piglatin_spec.js:3:18)

1 spec, 1 failure
Finished in 0.005 seconds

Here it is complaining that it doesn’t know anything about a class named piglatin

Create the Piglatin Class

Create the Translate Word Method

Fix the Method Signature

Return the Correct Answer

Another Word

Some Actual Code

Let's add some code to actually do something with the word we are passed.

The Pig Latin rules state that when the word starts with a vowel we just add `way` to the end of it.

Since we only have tests for words starting with vowels, let's do the minimum amount of work to get our test passing - appending `way` to the word that's passed it.