如何在方法上测试 setInterval?

How to test setInterval on a method?

我有一个class

class Dummy {
    constructor() {
        this.prop1 = null;
        this.prop2 = null;
        this.prop3 = setInterval(() => {
            this.method1()
        }, 1000);
    }

    method1() {
        // Method logic
    }
}

var dummyObject = new Dummy();
module.exports = dummyObject;

我想编写测试来验证 method1 每 1 秒后被调用一次。

以下是测试代码

const dummyObject = require('./dummy.js');

describe("Test setInterval", function () {
    it("Test setInterval", function () {
        const clock = sinon.useFakeTimers();
        const spy = sinon.spy(dummyObject, 'method1');

        clock.tick(1001);
        expect(spy.calledOnce).to.be.true;

        clock.restore();
    })
})

然而,当我 运行 测试时,我得到一个错误 'Expected false to equal to true' 并且在进一步挖掘时我意识到我无法监视通过 setInterval 调用的方法。

请分享关于我可以做些什么来测试这个场景的任何想法?

这不会按照您希望的方式工作,因为方法 (method1) 在您需要该模块时已经被调用,因此没有机会在您的测试之后监视它。

我建议重构您的模块以导出 class,而不是像这样的实例:

 module.exports = class Dummy {
      constructor() {
          this.prop1 = null;
          this.prop2 = null;
          this.prop3 = setInterval(() => {
              this.method1()
          }, 1000);
      }

      method1() {
          // Method logic
      }

  }

然后在你的测试中,需要 class 并在实例化之前监视方法:

  const sinon = require('sinon');
  const Dummy = require('./dummy.js');

  describe("Test setInterval", function () {
      it("Test setInterval", function () {
              const clock = sinon.useFakeTimers();
              // Spy on the method using the class' prototype
              const spy = sinon.spy(Dummy.prototype, 'method1');
              // Initialize the class and make sure its `constructor` is called after you spied on the method
              new Dummy();

              clock.tick(1001);

              expect(spy.calledOnce).to.be.true;

              clock.restore();

      })

  })