【问题标题】:Can I test setInterval with Jasmine?我可以用 Jasmine 测试 setInterval 吗?
【发布时间】:2018-06-15 22:43:26
【问题描述】:

我的代码中有这个语句,我想知道如何使用 Jasmine 测试 setInterval。

const x = setInterval(() => {
    const countdown = getElementById('countdownWrapper');
    const systemTime = ...
    const now = new Date().getTime();
    const endTime = systemTime - now;

    countdown.querySelector('.countdown-time').innerHTML = time();

    if (endTime < 0) {
        clearInterval(x);
        countdown.classList.remove('countdown-time--show');
    }
}, 1000);

systemTime 由 HTML 中的 DATA-CONTENT 属性中的 epoch 值提供。

任何帮助将不胜感激

【问题讨论】:

标签: javascript jasmine clock


【解决方案1】:
beforeEach(function() {
  timerCallback = jasmine.createSpyObj("setInterval");
  jasmine.clock().install();
});

afterEach(function() {
  jasmine.clock().uninstall();
});

it("causes a timeout to be called", function() {
  setTimeout(function() {
    timerCallback();
  }, 1000);

  expect(setInterval).not.toHaveBeenCalled();

  jasmine.clock().tick(1001);

  expect(setInterval).toHaveBeenCalled();
});

【讨论】:

  • 我在哪里调用我正在测试的代码,因为我在 SpyOn 之前的 beforeEach 中尝试过,我还在 beforeEach 之前创建了let timerCallback,但我仍然得到createSpyObj requires a non-empty array or object of method names to create spies for thrown. Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got undefined. 这个听起来函数没有触发
  • 太棒了,感谢您的帮助,但是在什么时候我应该调用我的脚本进行测试?我已将它放在 beforeEach 中,但出现此错误 createSpyObj requires a non-empty array or object of method names to create spies for thrown Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got Function. Usage: expect(&lt;spyObj&gt;).toHaveBeenCalled()
  • 我正在使用 Headless Chrome 运行单元测试,这会有所不同吗?
【解决方案2】:

更正本尼的回答:

timerCallback = jasmine.createSpyObj("test", {setInterval: 0});
AND
expect(timerCallback.setInterval).not.toHaveBeenCalled();

此外,这不会测试 setInterval,这在此处已被嘲笑。这会测试 setTimeout!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多