Created
August 18, 2012 05:54
-
-
Save d11wtq/3384727 to your computer and use it in GitHub Desktop.
RSpec style let() in Jasmine/Mocha
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get RSpec-style let() in your Mocha/Jasmine specs. | |
*/ | |
var let = function (callback) { | |
var value, called = false; | |
var memoizer = function() { | |
if (called) { | |
return value; | |
} else { | |
called = true; | |
} | |
return value = callback(); | |
}; | |
afterEach(function() { | |
value = undefined; | |
called = false; | |
}); | |
return memoizer; | |
}; | |
// example... | |
describe('Array', function(){ | |
var array = let(function(){ return[]; }); | |
describe('.length', function(){ | |
describe('when empty', function(){ | |
it('is zero', function(){ | |
assert.equal(array().length, 0); | |
}); | |
}); | |
describe('with two items', function(){ | |
beforeEach(function(){ | |
for (var i = 0; i < 2; ++i) { array()[i] = 'anything'; } | |
}); | |
it('is two', function(){ | |
assert.equal(array().length, 2); | |
}); | |
}); | |
}); | |
describe('#push()', function(){ | |
it('appends items to the array', function(){ | |
array().push('bob'); | |
assert.equal(array()[0], 'bob'); // note that the state has been reset | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment