Progressing time in the process baby in mocha
I am using node-cron to schedule a task to run once a day and I want to test this in mocha.
I am using child_process.spawn to run a script and I need to work through the internal clock of the created child. This is what I have so far:
it.only('Should run the script every 24 hours and trigger an event',function(done){
var clock = sinon.useFakeTimers(),
path = process.cwd() + '/cronjob/',
env = Object.create(process.env);
env.NODE_ENV = 'test';
var cronjob = child.spawn('node', ['index.js'], {
cwd: path,
env: env
});
cronjob.stdout.on('data',function(data){
console.log(data);
if (data.toString().trim() === 'Script ran successfully'){
cronjob.kill('SIGINT');
done();
}
});
cronjob.stderr.on('data',function(data){
done(new Error(data.toString()));
});
clock.tick(24*60*60*1000);
}
This only speeds up time in the mocha test instance, not index.js. Is there a way to pass a synon timer to a child process?
source to share
I'm not sure if this would be useful at all, but I did something similar using Node vm
. Here's a VERY simplified version of what I've done in the past.
Example index.js
:
setTimeout(function() {
console.log('ok');
}, 24*60*60*1000);
Example index.spec.js
var sinon = require('sinon');
var vm = require('vm');
var fs = require('fs');
describe('sample', function() {
it('Should detect if script runs 24 hours later',function(){
var clock = sinon.useFakeTimers();
var script = fs.readFileSync(require.resolve('../index.js'));
sinon.stub(console, 'log');
var result = vm.runInThisContext(script);
clock.tick(24*60*60*1000);
sinon.assert.calledOnce(console.log);
sinon.assert.calledWith(console.log, 'ok');
console.log.restore();
});
});
Output example:
sample
✓ Should run the script every 24 hours and trigger an event
1 passing (19ms)
In the above code example, I am doing the following:
- set up sinon timers fake
- stub
console.log()
so I can make assertions later - execute the sample
index.js
invm
using the current context but isolated from the local scope (index.js callsconsole.log()
after 24 hours) - travel time 24 hours using Sinon secret timers.
- make assertions on calls
console.log()
- restore
console.log()
(so Mocha reporters don't get upset)
Since I don't know what's going on in yours index.js
, it's hard to say if a solution like the one I outlined above might be helpful, but I hope so.
source to share