Skip to content

Instantly share code, notes, and snippets.

@vojtajina
Created August 7, 2012 09:14
Show Gist options
  • Save vojtajina/3283670 to your computer and use it in GitHub Desktop.
Save vojtajina/3283670 to your computer and use it in GitHub Desktop.
Example of predictableNextTick
var fs = require('fs');
var getLastModified = function(files, done) {
var timestamps = new Array(files.length);
var pending = files.length;
files.forEach(function(file, idx) {
fs.stat(file, function(err, stat) {
timestamps[idx] = stat.mtime;
if (!--pending) {
done(null, timestamps);
}
});
});
};
var fs = require('fs');
var getLastModified = function(files, done) {
var timestamps = [];
files.forEach(function(file) {
fs.stat(file, function(err, stat) {
timestamps.push(stat.mtime);
if (timestamps.length === files.length) {
done(null, timestamps);
}
});
});
};
// Jasmine Syntax
//
// Install npm dependencies first:
// npm install mocks
//
// Then, run unit test:
// jasmine-node .
describe('getLastModified', function() {
var mocks = require('mocks');
var mockery = {
// reate a fake in-memory FS
fs: mocks.fs.create({
'one.js': mocks.fs.file('2012-01-01'),
'two.js': mocks.fs.file('2012-02-02'),
'three.js': mocks.fs.file('2012-02-02')
})
};
// load the module (using fake FS)
var getLastModified = mocks.loadFile('get-last-modified-fixed.js', mockery).getLastModified;
it('should return last modified timestamps for every file', function() {
var spy = jasmine.createSpy('done').andCallFake(function(err, timestamps) {
expect(timestamps).toEqual([
new Date('2012-01-01'), new Date('2012-02-02'), new Date('2012-02-02')
]);
});
mocks.predictableNextTick.pattern = [1, 0];
getLastModified(['/one.js', '/two.js', '/three.js'], spy);
// wait for done callback
waitsFor(function() {return spy.callCount;});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment