Sunday, February 23, 2014

Bird Watching with JavaScript -- The Bluebird

"The first sparrow of spring! The year beginning with younger hope than ever! The faint silvery warblings heard over the partially bare and moist fields from the bluebird, the song sparrow, and the red-wing, as if the last flakes of winter tinkled as they fell! What at such a time are histories, chronologies, traditions, and all written revelations? The brooks sing carols and glees to the spring."
-- Henry David Thoreau
Walden, page 160

The Open Woodlands


Music all around.  A slight breeze is gently rustling the grass and leaves.  The song of the bluebird fills the air.  You call out X.  It sings back X.  You call out Y.  It sings back Y and X.  You call out Z.  It sings back Z, Y, and X.

The Bluebird




One of the first higher order functions that people learn is the composite function.


In combinatory logic the composite function is known as the B combinator.

B f g x = f (g x)

It also goes by the name given to it in To Mock a Mocking Bird, the bluebird.

Compose in Haskell


One of the things I love about Haskell is that if you look at a method signature you can pretty much tell what the function does.

Here is the definition of the compose function taken from the Haskell source.

(.)    :: (b -> c) -> (a -> b) -> a -> c
(.) f g = \x -> f (g x)



Looking at the definition we see that we need two functions, one goes from b to c and the other goes from a to b.  When given the value a the output is value c.

Looking at the actual function we see we have f (g x).  Meaning take the 2nd function I gave you (a -> b) and apply that to the argument a that I gave you.  Now take the result of (a -> b) and apply the 1st function I gave you (b -> c) against that.  The result of applying the (b -> c) function is the result I want returned.

Compose in Underscore


We see that compose is built into Haskell but what about JavaScript?  Reading Reginald Braithwaite's excellent book JavaScript AllongĂ© we see a definition of compose but we do find anything built into JavaScript (reading this book is what prompted me to write this post).  Luckily Underscore.js has us covered!

_.compose(*functions) 

Looking at the functional definition we see that we can pass in any number of functions and have compose create a function which applies all of them to the argument given to it.

  _.compose = function() {
    var funcs = arguments;
    return function() {
      var args = arguments;
      for (var i = funcs.length - 1; i >= 0; i--) {
        args = [funcs[i].apply(this, args)];
      }
      return args[0];
    };
  };

In fact looking at the annotation source we see that it applies all of the function we give it to how ever many arguments we give it!

Characterization Test of Underscore's compose



it("Given a bunch of identity functions it will return the value given", function(){
var ids = _.compose(_.identity, _.identity, _.identity, _.identity);
expect(ids("Mike Harris")).to.be.equal("Mike Harris");
})

We verify that we can apply compose however many times we wish to the identity function, which is also known as the I combinatory or the idiot bird, and we will get the same value back, f(x) = x.

it("Given an increment function it will return one more", function(){
var plus1 = _.compose(increment);
expect(plus1(42)).to.be.equal(43);
})

We see we can also pass in only one function and have that function applied to the argument we give it.

it("Given a absolute value and square root functions but used in the wrong order " +
"we cannot find positive square roots", function(){
var wrongPosSqrt = _.compose(Math.abs, Math.sqrt);
expect(_.isNaN(wrongPosSqrt(-4))).to.be.ok();
// even better
var failedPosSqrt = _.compose(_.isNaN, wrongPosSqrt);
expect(failedPosSqrt(-4)).to.be.ok();
// or
var showWhenFailed = _.compose(function(x){return !x;}, failedPosSqrt);
expect(showWhenFailed(2)).to.be.ok();
expect(showWhenFailed(-2)).to.not.be.ok();
})

We also verify that the order does matter.  When we use compose we need to think of it as applying the functions given in the order that we would read it if we wrote it out.

function wrongPosSqrt (x) = {return Math.abs(Math.sqrt(x));};

is very different from

function posSqrt (x) = {return Math.sqrt(Math.abs(x));};

The End


The bluebird can be thought of as a gateway to the larger world of functional programming.  With the simple concept of applying function together we see that we can built up simple existing functions to larger more complex functions.  This is one of the core concepts of functional programming.

Monday, February 17, 2014

Fun with Function References in JavaScript

"With his weak function. How am I then a villain"
-- Shakespeare, Othello
Act II, Scene III, Line 338

Characterization Tests


Whenever I find code of any kind that I do not understand I like to play around with it to see how it actually works.  Seldom do I find that the documentation gives me what I actual want to know, so I end up reading the source code (if I can) and playing around with some simple example code to figure out how the code I am going to use works.  It was not until I read Michael Feathers' Working Effectively with Legacy Code that I learned there is an actual term for this, it is called a Characterization Test.

The idea behind a characterization test is simple.  Treat the code that you are going to work with like a black box.  In order to discover how the code actually works write tests to prove out the functionality.  This is very similar to TDD except for one big difference, you are not going to fix the code to make the test pass.  Unlike in TDD with Characterization Tests you do not own the code, so you cannot modify it.

The goal of Characterization Testing is figure out how the code actually works, not how you would like it to work.

JavaScript Function References


What does any of this have to do with JavaScript function references?  Well, while reading Reginald Braithwaite's JavaScript AllongĂ© I came across a section about how function references work in JavaScript.  I had a little bit of trouble fully wrapping my head around the examples so I figured I'd do some Characterization Testing with them to fully figure out what was going on.

Using Node.js, Mocha, and expect.js I came up with the following characterization tests using a BDD style (this is my first gist on github).




Simple function examples


Given the following function:

alwaysOne = function(){return 1;};

We can show the following.

it("Given a function with two references with different names " +
"they will be equal", function(){
var one = alwaysOne;
expect(alwaysOne).to.be.equal(one);
}),
it("Given a function with two references with different names " +
"the results will be equal", function(){
var one = alwaysOne;
expect(alwaysOne()).to.be.equal(one());
}),

The first thing we find is that when given two different functional reference to the same function they are equal.  In the code above we see that alwaysOne and one are equal as references and they produce the same results.  This is what you would expect to happen.

it("Given a function with two references with different names " +
"changes to the reference of one will not affect the other", function(){
var one = alwaysOne;
expect(alwaysOne()).to.be.equal(one());
alwaysOne = void 0; // always is not forever :)
expect(alwaysOne).to.not.be.equal(one);
expect(alwaysOne).to.be.eql(void 0);
expect(one()).to.be.equal(1);
});

Next we see that if we alter where one of the references point to it leaves the other alone.  Makes sense.


Recursive function examples



Given the following recursive function:

even = function(x){return x === 0 || !even(x-1);};

We can show the following.

it("Given a recursive function with one reference " +
"changes to the reference will change the reference", function(){
expect(even(0)).to.be.ok();
expect(even(1)).to.not.be.ok();
expect(even(8)).to.be.ok();
even = void 0;
expect(even).to.be.eql(void 0);
})

If we have one reference to the function when we change the reference we get the new functionality referred to (in this case void 0 is returned).  I know and birds go tweet, so what?  This is will make more sense to check given the next test.

it("Given a recursive function with two reference with different name " +
"changes to the reference will break it", function(){
var divisableByTwo = even;
expect(even(0)).to.be.equal(divisableByTwo(0));
expect(even(1)).to.be.equal(divisableByTwo(1));
expect(even(8)).to.be.equal(divisableByTwo(8));
even = void 0;
expect(even).to.be.eql(void 0);
expect(divisableByTwo(0)).to.be.ok();
expect(function(){return divisableByTwo(8);})
.to.throwError(); // throws TypeError
expect(function(){return divisableByTwo(0);})
.not.to.throwError(); // to prove above works
expect(function(){return divisableByTwo(8);})
.to.throwException(function(e){expect(e).to.be.a(TypeError);});
expect(function(){return divisableByTwo(8);})
.to.throwException(/undefined is not a function/);
})

If we have two different references and we change the reference referred to by the recursive call we get some interesting behavior.  We see that the calls to even after the reassignment conform how we would expect them to.

We see an interesting behavior on the calls to divisableByTwo after the reassignment.  We see that the functionality continues to work as long as the recursive call to the altered named reference even is not made.  Thus, the call using 0 will work fine since no recursive call is made, but any other call will fail since even is now referred to void 0 which is not a function.

To get around this issue you want to name the anonymous function that even is referring to.

even = function even(x){return x === 0 || !even(x-1);};

Now the recursive call made to even in the function will refer to the function named even and not the reference named even.

Saturday, February 8, 2014

On Undefined

"At first there will be, as this time, something undefined kept back, and then she will get used to it."
-- Leo Tolstoy, Anna Karenina
Part 6, Chapter 25

Problem Statement


What does it mean for something to be undefined?  This question sounds like a kĹŤan:

If you meet the Buddha, kill him.
-- Linji Yixuan

Great Master Ba was seriously ill. The chief priest of the temple asked him,
"Master, how are you feeling these days?"
Great Master said,
"Sun-face Buddha, Moon-face Buddha"

-- The Blue Cliff Record
Case 3: Master Ba Is Ill

(Note, the "Sun-face Buddha" is said to have a life of 1800 years, the "Moon-face Buddha" lives 24 hours)

Functional Point-of-view


In programming having a function return undefined is a bit like saying, "I did not think that this would happen, but here we are."  In college I was both a Mathematics and Computer Science major, I remember the first time I came across undefined it was in Linear Algebra with Dr. Beachy, I was stuck on a homework problem, flipping ahead in the textbook I notice a an example that was basically the same problem that I was stuck on.  I talked to Dr. Beachy about the problem and how I planned on solving it, he said that could be a great way to solve the problem but that the property I was going to use was not defined to work with the problem I had.  This was the first time in my life that I came across undefined as output of applying something.

In programming terms, undefined is what you would get if you have functional input contract which is broken.  I believe I hear an example would be nice, so here it is.

DEFINE foo = FUNCTION(x)
  RETURN 8 / x
when x does not equal 0

If we call foo with 1 we would get 8.  Likewise if we call foo with 2 we would get 4.  What should happen if we call foo with 0?  Should we even be allowed to call foo with 0?  

If we are using a language or framework that supports programming-by-contract then the answer to what should happen if we call foo with 0 is easy, the call would fail.  What would happen if we call foo in a language that does not support programming-by-contract?

If we are not using a language of framework that supports programming-by-contract we have two options:
  1. set up guards in the function which filter out unsupported input (returning null, IllegalArgumentException, or whatever makes sense in the language we are using)
  2. have the language return some type of unknown value
Option 1 requires us to think about what to allow and not allow ahead of time.

Option 2 is interesting and is the point of this post.

JavaScript and undefined


JavaScript is very interesting since it includes undefined as part of its language.

> undefined
undefined

I know so what, any call without a return value in the Node.js REPL will return undefined.  Yes, but what is that actually telling us?

> 2 + 2;
4
> console.log('2 + 2 = ' + (2 + 2));
2 + 2 = 4
undefined

We see that the call to console.log sends the string to the console be has the return value of undefined, interesting.  Let's play around if return values from functions and see if we can find anything of interest.

> (function(){return 2;})();
2
> (function(){return 'Hello World';})();
'Hello World'
> (function(){return 2 + 2;})();
4
> (function(x){return x;})(2);
2

Nothing interesting yet, how about ...

> (function(){})();
undefined

Now that is a bit interesting.  What happen there?  We do not have a return value so JavaScript has given us one of undefined.  Let's play with this a little more.

> (function(x){if (x % 3 === 0) return "Fizz"})(9);
'Fizz'
> (function(x){if (x % 3 === 0) return "Fizz"})(1);
undefined
> (function(x){if (x % 3 === 0) return "Fizz"})("Mike Harris");
undefined

(I did not retype that but instead use the up arrow, don't judge me.)

Hmmm, we see that if we have undefined pathways through are code we have the value of undefined returned.  Looking back at our foo example from before, JavaScript would give us the following results.

> var foo = function(x){return 8 / x;};
undefined
> foo(1);
8
> foo(2);
4
> foo(0);
Infinity
> foo();
NaN
> foo('Mr. Jack');
NaN
> foo('');
Infinity
> foo(Infinity);
0
> foo(NaN);
NaN
> foo([]);
Infinity
> foo((function(){}));
NaN

We see that JavaScript returns what is mathematically an acceptable answer for the input of 0, but we get some very interesting output for values that are treated the same way as 0 in JavaScript (like the empty string and empty array).  The value for the input of Infinity are interesting.  Some people would say 8/infinity = 0 is correct or close enough other would say 8/infinity = 0 is just plain wrong.

One last thing to check, does undefined equal undefined in JavaScript?

> undefined === undefined
true
> ((function(){})()) === undefined
true
> ((function(){})()) === ((function(){})())
true
> ((function(){})()) === ((function(){})('something'))
true
> ((function(){2})()) === ((function(){})())
true
> ((function(){})()) === void 0
true
> ((function(x){if (x === 2) return x;})(3)) === ((function(){})())
true

It seems that JavaScript considers undefined to be equal to undefined.

F# and undefined


F# is a strongly typed language, let's see what happens with our foo example from before.


> let foo x = 8 / x;;
  
  foo 1;; // 8
  foo 2;; // 4
  foo 0;; 

val foo : x:int -> int

> val it : int = 8
> val it : int = 4
> System.DivideByZeroException: [Arg_DivideByZero]
Arguments: 
Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=5.1.20913.00&File=mscorlib.dll&Key=Arg_DivideByZero
   at .$FSI_0004.main@()
   at main@dm()
Stopped due to error

Nice we get a DivideByZeroExpection for calling foo with 0.

How about our conditional return statement lambda that only handles numbers divisible by 3?

> (fun x -> if x % 3 = 0 then "Fizz") 2;;
  (fun x -> if x % 3 = 0 then "Fizz") 3;

  (fun x -> if x % 3 = 0 then "Fizz") 2;;
  ----------------------------^^^^^^

stdin(13,29): error FS0001: This expression was expected to have type
    unit    
but here has type
    string    
  (fun x -> if x % 3 = 0 then "Fizz") 3;
  ----------------------------^^^^^^

stdin(14,29): error FS0001: This expression was expected to have type
    unit    
but here has type
    string    

That did not even compile right and makes sense based on what the MSDN documentation says about conditional expressions in F#. "The types of the values produced in each branch must match. If there is no explicit else branch, its type is unit.

How about pattern matching?

> (fun x ->  match x with  _ when x % 3 = 0 -> "Fizz") 2;;
  (fun x ->  match x with  _ when x % 3 = 0 -> "Fizz") 3;;

  (fun x ->  match x with  _ when x % 3 = 0 -> "Fizz") 2;;
  -----------------^

stdin(16,18): warning FS0025: Incomplete pattern matches on this expression.
Microsoft.FSharp.Core.MatchFailureException: The match cases were incomplete
   at .$FSI_0011.main@()
   at main@dm()
Stopped due to error
  (fun x ->  match x with  _ when x % 3 = 0 -> "Fizz") 3;;
  -----------------^

stdin(17,18): warning FS0025: Incomplete pattern matches on this expression.
val it : string = "Fizz"
> > 

Well that did not work either, it seems that the pattern matching must cover all paths.

It seems that an undefined value is not possible in F# unless you make one up.

Pseudo-Conclusion


With undefined what we are saying is here there be dragons.

Sunday, February 2, 2014

Setting Up Continuous Testing with Grunt and Mocha

"To grunt and sweat under a weary life"
-- Shakespeare, Hamlet
Act III, Scene 1, Line 77

Prelude


My first experience of continuous testing was using NCrunch, it was funny how quickly this change the way I wrote software.

What is Continuous Testing


In a typical TDD style of programming you do the following.



  • Write a failing test.
  • Stop and run test to prove that test is failing.
  • Write code to pass failing test.
  • Stop and run test to prove that test is now passing (and make sure nothing is broken).
  • Refactor code.
  • Stop and run test to prove nothing as been broken by refactoring.
  • Repeat.

Notice anything interesting?  Yep, there is a whole lot of stopping in the cycle.  This stopping is one of the common complaints one hears from people just starting out in TDD (I know most of my readers are well past that point, but there are a LOT of programmers that do not do TDD, so this issue is still relevant).

How can we fix this?  It would be nice if we had something running in the background which ran our test for us and would notify us of any failures as they came up, this could work like a word processor's spell check.

I remember when I first started writing on a computer using WordPerfect (yep, I am 33).  Using a word processor back in the dark days when one would start Windows from DOS, one would find themselves following a similar process with a spell checker.  You would do the following.

  • Write some text.
  • Stop and run the spell checker.
  • Fix any issues.
  • Write some more.
  • Stop and run the spell checker again.
  • Fix any issues.
  • Repeat.

This looks a like like the typical TDD session.

Continuous testing is testing in which the test are always running.  It works a lot like a spell checker in a modern word processor.  As you write code your test are continuously running and given you feedback on your code.

With continuous testing, TDD looks like the following.

  • Write a failing test.
  • Write code to pass the test.
  • Refactor.
  • Repeat.

Yep, coding without stopping.  The first time I used NCrunch for a whole day, I noticed when I went to check my code into source control that I had not saved it yet!  The way that NCrunch works it automatically builds and tests your code for you, so you do not even notice that you have not saved yet.  Depending on how much you trust your computer and power supply this may or may not be a good thing, but it shows how a tool can change the way that you work.

The team that I work with have fallen in love with continuous testing so much that when NCrunch went from free to pay we took a quick poll and found that everyone would rather drop their ReSharper licence in order to get a NCrunch licence if push-came-to-shove (ReSharper is a great tool and I would not want to do .Net programming without it, in fact I have a ReSharper T-shirt on as I am typing this (do not judge me), but continuous testing is that important).  Luckily for us, we did not have to follow through with that choice and are now enjoying NCrunch along with ReSharper.

How to Setup Grunt


Enough about NCrunch this post is actually about how to set up a continuous testing environment for Node.js using Grunt and Mocha.  First thing first, you'll need to have Node.js installed if you do not already have it.

Assuming that you have Node.js installed let's look at getting Grunt setup.

The easiest way to install Grunt is via npm (Node Package Manager), fire up the console.

C:\kata>npm install -g grunt-cli


This will install the Grunt Command Line Interface and will add grunt to your system path.

Adding Grunt to Your Projecting

Now that we have the Grunt Command Line Interface install we can add Grunt to our Node.js code.

Let's create a new Grunt Hello World project.

C:\kata>mkdir gruntHelloWorld

C:\kata>cd gruntHelloWorld

C:\kata\gruntHelloWorld>mkdir src

C:\kata\gruntHelloWorld>mkdir test

We now have a directory called gruntHelloWorld which has a src folder for our source code and a test folder for our tests, feel free to code these what you want you'll just have to modify the instructions a bit from here on out.

We are now ready to create a package.json file to hold our Node project dependencies (you can skip this if you want).

npm init will give you a prompt like the following.

C:\kata\gruntHelloWorld>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (gruntHelloWorld)

Follow the prompt (do not worry you can fix any issues you have later).  Here is what I used incase you want to copy.  Note, for the name you cannot have spaces.  Also note that you can hit enter to just use the default values.

name: (gruntHelloWorld) HelloWorld
version: (0.0.0) 0.0.1
description: A simple example of continuous testing using Grunt and Mocha.
entry point: (index.js) hello.js
test command: grunt
git repository:
keywords: example grunt mocha hello world
author: Mike Harris
license: (BSD-2-Clause)
About to write to C:\kata\gruntHelloWorld\package.json:

{
  "name": "HelloWorld",
  "version": "0.0.1",
  "description": "A simple example of continuous testing using Grunt and Mocha.",
  "main": "hello.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "grunt"
  },
  "keywords": [
    "example",
    "grunt",
    "mocha",
    "hello",
    "world"
  ],
  "author": "Mike Harris",
  "license": "BSD-2-Clause"
}


Is this ok? (yes) y

C:\kata\gruntHelloWorld>

What did we just do?  We create a file which will hold all of our dependencies for our Node project, this file is called package.json.

C:\kata\gruntHelloWorld>type package.json
{
  "name": "HelloWorld",
  "version": "0.0.1",
  "description": "A simple example of continuous testing using Grunt and Mocha.",
  "main": "hello.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "grunt"
  },
  "keywords": [
    "example",
    "grunt",
    "mocha",
    "hello",
    "world"
  ],
  "author": "Mike Harris",
  "license": "BSD-2-Clause"
}

Let's add Grunt to this project.


C:\kata\gruntHelloWorld>npm install grunt --save-dev


Notice the --save-dev on the npm command, this will add a dependency on grunt to our package.json file, which will allow us to our project dependencies with others.

C:\kata\gruntHelloWorld>type package.json
{
  "name": "HelloWorld",
  "version": "0.0.1",
  "description": "A simple example of continuous testing using Grunt and Mocha.",
  "main": "hello.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "grunt"
  },
  "keywords": [
    "example",
    "grunt",
    "mocha",
    "hello",
    "world"
  ],
  "author": "Mike Harris",
  "license": "BSD-2-Clause",
  "devDependencies": {
    "grunt": "~0.4.2"
  }
}

Now that we have Grunt setup, we need to create the Gruntfile.js file.

Adding in the Gruntfile.js


The Gruntfile.js tells Grunt what to do, think of it as an Apache Ant build file for Grunt, but instead of being stored in XML and limited to just building, it is written in JavaScript and is used for tasks (which can include "building").

Create a new file called Gruntfile.js at the root of the project (right next to package.json), I will use the text editor Sublime Text to do this (since it is current favorite text editor, but vim or notepad or ... would work just as well).

Our Gruntfile.js will need to export a function which takes a single argument.

C:\kata\gruntHelloWorld>type Gruntfile.js
module.exports = function(grunt) {
  // add task here
};


Now that we have our wrapper function setup we can add tasks to it.

Adding in Mocha


First let's get the latest version of Mocha from npm.

C:\kata\gruntHelloWorld>npm install mocha --save-dev

Now we will the Grunt plugin grunt-mocha-test to run our Mocha tests.

C:\kata\gruntHelloWorld>npm install grunt-mocha-test --save-dev


Now we'll initialize the configuration of Grunt by adding in a method called grunt.initConfig (which is an alias for grunt.config.init) to the function we are exporting.

module.exports = function(grunt){
  grunt.initConfig({
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          clearRequireCache: true
        },
        src: ['test/*.js']
      },
    }
  });

  grunt.loadNpmTasks('grunt-mocha-test');

  grunt.registerTask('default', ['mochaTest']);
};

We call grunt.initConfig with an object containing a name property of mochaTest (you should be able to call it whatever you want), this property has an object with a property of test which in turn has options which is where we place our options to Mocha.  We set the reporter to use spec and to clear the require cache (I find this makes life a lot easier).  Next we load the npm tasks (this could have been done earlier) and lastly we register mochaTest as part of default to Grunt.

C:\kata\gruntHelloWorld>grunt


If we want we could register a task just for testing.

module.exports = function(grunt){
  grunt.initConfig({
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          clearRequireCache: true
        },
        src: ['test/*.js']
      },
    }
  });

  grunt.loadNpmTasks('grunt-mocha-test');

  grunt.registerTask('default', ['mochaTest']);
  grunt.registerTask('test', ['mochaTest']);
};

Now we can call grunt with test and it will execute mochaTest task.

C:\kata\gruntHelloWorld>grunt test



Let's look at adding in continuous testing.

Adding in Watch


We'll now add a watcher which will call our mochaTest task on any changes to our files.

We'll add the plugin grunt-contrib-watch.

C:\kata\gruntHelloWorld>npm install grunt-contrib-watch --save-dev


We now add watch to our Gruntfile.js

module.exports = function(grunt){
  grunt.initConfig({
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          clearRequireCache: true
        },
        src: ['test/*.js']
      },
    },

    watch: {
      js: {
        options: {
          spawn: true,
          interrupt: true,
          debounceDelay: 250,
        },
        files: ['Gruntfile.js', 'src/*.js', 'test/*.js'],
        tasks: ['mochaTest']
      }
    }
  });

  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['mochaTest']);
  grunt.registerTask('test', ['mochaTest']);
};

I find these options work best for me, but you may want to read the documentation to find what will work best for you.

The files property is where we say what files to watch in this case the Gruntfile.js and anything under our src and test folder which is a JavaScript file.

The task property says which task to run when the watch detects a change in the files it is watching, in this case we want to run our Mocha tests (and thus create a continuous testing environment).

Start up the watcher with grunt watch.

C:\kata\gruntHelloWorld>grunt watch


We are now ready for some continuous testing TDD goodness.

Hello World


Let's add in expect.js for testing our code (feel free to use whatever you prefer).

C:\kata\gruntHelloWorld>npm install expect.js --save-dev



(If you have been following along you'll need to Ctrl+c out of the watch first.)

We'll start off with the following in our newly created helloSpec.js file.

var sut = require("../src/hello"),
 expect = require("expect.js");

describe("Hello World using TDD", function(){
  it("Given nothing then Hello is returned", function(){
    expect(sut.helloer()).to.be.equal("Hello");
  });
});


Running the test we'll have something like the following.

C:\kata\gruntHelloWorld>grunt test


We can now create the hello.js file with the following to pass the test.

exports.helloer = function(){
  return "Hello";
}

We now can start the watch up and do some TDD.

C:\kata\gruntHelloWorld>grunt watch


Boom!  We now have a continuous testing environment set up!

We can now set up a failing test around adding in a name to say hello to.

We add the following test to helloSpec.js in our test folder and watch the watch detect the change and report the failure.

var sut = require("../src/hello"),
 expect = require("expect.js");

describe("Hello World using TDD", function(){
  it("Given nothing then Hello is returned", function(){
    expect(sut.helloer()).to.be.equal("Hello");
  }),
  it("Given Mike then Hello Mike is returned", function(){
    expect(sut.helloer("Mike")).to.be.equal("Hello Mike");
  });
});


Nice!  Now we can make it pass (this is what I've added to hello.js).

exports.helloer = function(name){
  var ret = "Hello";

  if (name) ret += " " + name;

  return ret;
}




Now we have a fully operational continuous testing environment.

Allude


Here is what we got now in terms of files.

package.json


{
  "name": "HelloWorld",
  "version": "0.0.1",
  "description": "A simple example of continuous testing using Grunt and Mocha.",
  "main": "hello.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "grunt"
  },
  "keywords": [
    "example",
    "grunt",
    "mocha",
    "hello",
    "world"
  ],
  "author": "Mike Harris",
  "license": "BSD-2-Clause",
  "devDependencies": {
    "grunt": "~0.4.2",
    "mocha": "~1.17.1",
    "grunt-mocha-test": "~0.9.0",
    "grunt-contrib-watch": "~0.5.3",
    "expect.js": "~0.2.0"
  }
}

Gruntfile.js


module.exports = function(grunt){
  grunt.initConfig({
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          clearRequireCache: true
        },
        src: ['test/*.js']
      },
    },

    watch: {
      js: {
        options: {
          spawn: true,
          interrupt: true,
          debounceDelay: 250,
        },
        files: ['Gruntfile.js', 'src/*.js', 'test/*.js'],
        tasks: ['mochaTest']
      }
    }
  });

  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['mochaTest']);
  grunt.registerTask('test', ['mochaTest']);
};

src\hello.js


exports.helloer = function(name){
  var ret = "Hello";

  if (name) ret += " " + name;

  return ret;
}

test\helloSpec.js


var sut = require("../src/hello"),
 expect = require("expect.js");

describe("Hello World using TDD", function(){
  it("Given nothing then Hello is returned", function(){
    expect(sut.helloer()).to.be.equal("Hello");
  }),
  it("Given Mike then Hello Mike is returned", function(){
    expect(sut.helloer("Mike")).to.be.equal("Hello Mike");
  });
});