如何在Mocha内部测试使用setTimeout()的函数?

kal*_*lpa 4 javascript mocha.js

考虑以下功能,

function helloAfter100ms(){
  setTimeout(function(){
    console.log('hello');
  },100)
}
Run Code Online (Sandbox Code Playgroud)

用摩卡测试代码,

describe('#helloAfter100ms()',function(){
  it('console logs hello ONLY after 100ms',function(){
    // what should go here
  })
})
Run Code Online (Sandbox Code Playgroud)

Kra*_*log 8

我认为您正在尝试测试您不应该测试的东西。测试的名称表明您不相信该setTimeout函数console.log仅在给定的超时后才调用。

由于这不是您的代码,因此您可能不应该对其进行单元测试。此外,setTimeout您可以肯定某些东西可以正常工作。

那么还剩下什么要测试?您的代码- 调用 的代码setTimeout。您可以确保正确调用setTimeout。

至于如何完成-您可以使用两个sinon功能。第一个是useFakeTimers让您控制时钟。第二个是间谍,您应该在该间谍上使用console.log它以确保已被调用。

describe('#helloAfter100ms()',function(){
  it('console logs hello ONLY after 100ms',function(){
    const clock = sinon.useFakeTimers();
    const logSpy = sinon.spy(console, 'log');
    helloAfter100ms();
    expect(logSpy).to.not.have.been.called;
    clock.tick(100);
    expect(logSpy).to.have.been.calledOnce;
    logSpy.restore();
    clock.restore();
  }
}
Run Code Online (Sandbox Code Playgroud)