繁体   English   中英

使用sinon FakeTimers测试节点计划

[英]Test node-schedule with sinon FakeTimers

我想从node-schedule包中测试我的scheduleJob 使用sinon useFakeTimers()可以跳过时间。 不幸的是,我的调度程序似乎并没有“相信”假的时间。 当我将调度程序设置为1分钟时,它可以正常工作,因此我知道它可以工作。 我还尝试将假时间设置为通话前一分钟,这也是行不通的。

兴农:

let clock = sinon.useFakeTimers(moment().toDate());
                clock.tick(60*60*23);

我的预定工作:

 let job_2 = schedule.scheduleJob(new Date(date.toISOString()), function (user) {
        console.log("get's here..");
        if (user.status === 'pending') {
            user.remove(function (error) {
                if (!error) {
                    mid.addEvent({
                        action: 'deleted_user'
                    }, {
                        name: user.name
                    }, function (error) {
                        if (error) {
                            console.log("error: " + error);
                        }
                    });
                }
            });
        }
    }.bind(null, user));

有人知道吗?

基本上, sinon.useFakeTimers()方法用内置的同步方法替换setInterval和setTimeout异步方法,您可以使用clock.tick()控制。

clock.tick(time)方法调用替换的同步方法,并基本上按指定的时间转发time

另一方面, node-schedulecron-like作业调度程序,因此它不使用setInterval和setTimeout

https://www.npmjs.com/package/node-schedule

https://sinonjs.org/releases/v1.17.6/fake-timers/

希望这可以使它更加清晰

@MPasman

您的测试是什么样的? 节点计划作者使用sinon测试了他们的代码,所以我不明白为什么这会成为问题。

看到这个例子

我可以使用茉莉花的fakeAsync在角度6中测试我的工作,如下所示:

 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); })); 

我正在测试的服务中的实际功能:

  scheduleMyJsCronJob(): void { this.cronJob = scheduleJob(this.cronJobTime, () => { // logic to unsubscribe at midnight this.messenger.unsubscribeAll(); // create new channels this.createChannels( this.sessionStorageService.getItem('general-settings')); this.createListener( this.sessionStorageService.getItem('general-settings')); }); } 

基本策略是:

1)监视cronJob在计划时应调用的函数

2)取消所有以前的作业(如果有的话)(您也可以在afterEach中执行此操作,在每个单元测试之后运行)。 节点计划还提供了一个称为scheduledJobs的函数,该函数返回具有所有已调度函数的对象。 您可以对其进行循环并全部取消)

3)将cronTime设置为cronTime运行一次,以便于测试

4)将时钟滴答一秒多一点(在我的情况下我做了3秒多一点)

5)取消作业以使其停止(否则它将继续运行,并且测试将超时)。

6)期望您的函数被调用x次

希望这对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM