Test Node-schedule With Sinon Faketimers
Solution 1:
@MPasman
What does your test look like? The node-schedule authors test their code with sinon so I don't see why this would be an issue.
I was able to test my job in angular 6 using jasmine's fakeAsync like so:
it('should call appropriate functions when cronJob is triggered, bad ass test',
fakeAsync(() => {
const channelSpy = spyOn(messengerService, 'createChannels');
const listenerSpy = spyOn(messengerService, 'createListener');
const messengerSpy = spyOn(messengerService.messenger,
'unsubscribeAll');
// reset your counts
channelSpy.calls.reset();
listenerSpy.calls.reset();
messengerSpy.calls.reset();
messengerService.cronJob.cancel();
// run cron job every second
messengerService.cronJobTime = '* * * * * *';
messengerService.scheduleMyJsCronJob();
tick(3150);
messengerService.cronJob.cancel();
expect(channelSpy.calls.count()).toEqual(3);
expect(listenerSpy.calls.count()).toEqual(3);
expect(messengerSpy.calls.count()).toEqual(3);
}));
The actual function in the service I am testing:
scheduleMyJsCronJob(): void {
this.cronJob = scheduleJob(this.cronJobTime, () => {
// logic to unsubscribe at midnightthis.messenger.unsubscribeAll();
// create new channelsthis.createChannels(
this.sessionStorageService.getItem('general-settings'));
this.createListener(
this.sessionStorageService.getItem('general-settings'));
});
}
The basic strategy is:
1) spy on functions that your cronJob should call when scheduled
2) cancel all previous Jobs if any (you could also do this in an afterEach, which runs after each unit test). Node-schedule also offers a function called scheduledJobs
which returns an object with all the functions scheduled. You can loop over it and cancel them all)
3) set the cronTime
to run every second for easier testing
4) tick the clock a little over a second (in my case i did a little over 3 seconds)
5) cancel the job to stop it (otherwise it will keep running and your test will timeout).
6) expect your function(s) to be called x amount of times
Hope this helps you.
Solution 2:
Basically sinon.useFakeTimers()
method replaces setInterval and setTimeout asynchronous methods with a built in synchronous methods that you can control using clock.tick()
clock.tick(time)
method invokes the replaced synchronous methods and basically forwards the time by time
specified.
node-schedule
on the other hand is a cron-like
job scheduler so it doesn't use setInterval and setTimeout
https://www.npmjs.com/package/node-schedule
https://sinonjs.org/releases/v1.17.6/fake-timers/
Hope this makes it a little more clear
Post a Comment for "Test Node-schedule With Sinon Faketimers"