Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created February 23, 2014 20:26
Show Gist options
  • Save MikeMKH/9176745 to your computer and use it in GitHub Desktop.
Save MikeMKH/9176745 to your computer and use it in GitHub Desktop.
Characterization tests using Mocha and expect.js to understand how underscore compose works.
var expect = require("expect.js"),
_ = require("underscore"),
increment = function(x){return ++x;};
// Characterization tests using Mocha and expect.js to understand how
// underscore compose works
// See http://comp-phil.blogspot.com/2014/02/bird-watching-with-javascript-bluebird.html
describe("Let's figure out how underscore's compose function works", function(){
describe("Simple function examples", function(){
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");
}),
it("Given an increment function it will return one more", function(){
var plus1 = _.compose(increment);
expect(plus1(42)).to.be.equal(43);
}),
it("Given an increment and identity function it will return one more", function(){
var plus1 = _.compose(_.identity, increment);
expect(plus1(42)).to.be.equal(43);
});
}),
describe("Complex functions", function(){
it("Given a absolute value and square root functions we can find positive square roots", function(){
var posSqrt = _.compose(Math.sqrt, Math.abs);
expect(posSqrt(-4)).to.equal(2);
}),
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();
}),
it("Given a greet and exclaim function we can really greet someone!", function(){
// based on example from http://underscorejs.org/#compose
var greet = function(name){ return "Hi " + name; },
exclaim = function(statement){ return statement + "!"; },
welcome = _.compose(greet, exclaim);
expect(welcome("Mr. Jack")).to.equal("Hi Mr. Jack!");
});
});
});
@MikeMKH
Copy link
Author

MikeMKH commented Feb 23, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment