проверить обратный вызов внешней функции с помощью setInterval () с помощью MochaJS - PullRequest
0 голосов
/ 03 июля 2019

Мне нужно проверить вызов на destroyTask() с помощью setInterval(). setInterval() сравнивает две метки времени, и они вызывают 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();
  }

В чем может быть причина?Можно ли проверить обратный вызов внешней функции в другой функции?

1 Ответ

0 голосов
/ 04 июля 2019

Пришлось изменить несколько вещей. Я изменил шпионский вызов, увеличил вторую this.clock.tick() до 2000 и должен был дать пользовательскую функцию 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();
    });
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...