Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Characterization tests using Mocha and expect.js to understand how functional references in JavaScript work
var expect = require("expect.js");
// Characterization tests using Mocha and expect.js to understand how
// functional references in JavaScript work
// See http://comp-phil.blogspot.com/2014/02/fun-with-function-references-in.html
// examples based on https://leanpub.com/javascript-allonge/read#recursive
describe("Let's play around with function references", function(){
describe("Simple function examples", function(){
var alwaysOne;
beforeEach(function(done){
alwaysOne = function(){return 1;};
done();
});
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());
}),
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);
});
}),
describe("Recursive function examples", function(){
var even;
beforeEach(function(done){
even = function(x){return x === 0 || !even(x-1);};
done();
});
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);
}),
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/);
});
});
});
@MikeMKH

This comment has been minimized.

Copy link
Owner Author

@MikeMKH MikeMKH commented Feb 17, 2014

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