使用 MochaJS 在 setInterval() 中测试对外部函数的回调

test a callback to an outside function with in setInterval() using MochaJS

我需要在 setInterval() 中测试对 destroyTask() 的调用 setInterval() 比较两个时间戳,它们在当前时间为 destroyTask() 时调用 destroyTask()等于 finishTime

 async jobTimeout() {
    if (!this.timeout || !this.timeunits) return;
    const startTime = moment();
    const finishTime = moment().add(this.timeout, this.timeunits);
    // console.log('Duration - ', this.timeout, ' ' ,this.timeunits);

    console.log(`Start Time: ${startTime}`);
    console.log(`Finish Time: ${finishTime}`);

    this._timer = setInterval(() => {
      console.log(moment());
      if (moment().isAfter(finishTime)) {
        console.log("The task didn't finish in time. ", this.destroyTask());
        clearInterval(this._timer); // the clearInterval() method clears a timer set with the setInterval() method
      }
    }, 1000);
  }

我正在使用 sinon 监视两个函数和假定时器来覆盖 setInterval。我的测试用例如下:

 describe('Generic Setup', () => {
    beforeEach(() => {
      // Overwrite the global timer functions (setTimeout, setInterval) with Sinon fakes
      this.clock = sinon.useFakeTimers();
    });

    afterEach(() => {
      // Restore the global timer functions to their native implementations
      this.clock.restore();
    });

    it('Job Should Timeout After Specified Duration', async () => {
      const task = new TASK(taskData, done);
      const result = sinon.spy(await task.jobTimeout());
      const destroyTask = sinon.spy(await task.destroyTask());

      setInterval(result, 1000);

      this.clock.tick(4000);
      expect(destroyTask).to.not.have.been.called;

      this.clock.tick(1000);
      expect(destroyTask).to.have.been.called;
    });
  });

我收到以下错误 TypeError: this.done is not a function。我认为它是由 destroyTask 引起的,但它是一个函数。

async destroyTask() {
    // TODO cleanup tmp directory - might want to collect stat on error
    clearInterval(this._timer);
    this.done();
  }

可能是什么原因?是否可以在另一个函数中测试对外部函数的回调?

不得不修改一些东西。我已经更改了间谍调用,将第二个 this.clock.tick() 增加到 2000 并且必须在 class 实例化中提供自定义 done 函数。

  describe('Generic Setup', () => {
    beforeEach(() => {
      // Overwrite the global timer functions (setTimeout, setInterval) with Sinon fakes
      this.clock = sinon.useFakeTimers();
    });

    afterEach(() => {
      // Restore the global timer functions to their native implementations
      this.clock.restore();
    });

    it('Job Should Timeout After Specified Duration', async () => {
      const task = new TASK(taskData, () => {});

      task.jobTimeout();

      const destroyTaskSpy = sinon.spy(task, 'destroyTask');

      this.clock.tick(4000);
      expect(destroyTaskSpy).to.not.have.been.called;

      this.clock.tick(2000);
      expect(destroyTaskSpy).to.have.been.called;

      // Remove the spy to prevent future errors
      destroyTaskSpy.restore();
    });
  });