简体   繁体   English

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

[英]How to test a function that uses setTimeout() internally with mocha?

Consider the below function, 考虑以下功能,

function helloAfter100ms(){
  setTimeout(function(){
    console.log('hello');
  },100)
}

Test code with mocha, 使用mocha测试代码,

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

I think you're trying to test something that you shouldn't. 我想你正在尝试测试你不应该做的事情。 The name of your test suggests you don't trust that the setTimeout function calls the console.log only after the given timeout. 测试的名称表明您不相信setTimeout函数仅在给定的超时后调用console.log

Since this is not your code, you should probably not unit test it. 由于这不是您的代码,您可能不应该对其进行单元测试。 Furthermore, setTimeout is probable something you can be sure works properly. 此外, setTimeout很可能确保正常工作。

So what's left to test? 还有什么可以测试? Your code - the code that calls setTimeout . 您的代码 - 调用 setTimeout的代码。 You can make sure that you're calling setTimeout correctly. 您可以确保正确调用setTimeout。

As to how this is done - there are two sinon features you can use. 至于如何做到这一点 - 你可以使用两个sinon功能。 The first is useFakeTimers which gives you control of the clock. 第一个是useFakeTimers ,它可以让你控制时钟。 The second is a spy, which you should use on the console.log to make sure it was called. 第二个是间谍,你应该在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();
  }
}

Updated: like this: 更新:像这样:

describe('helloAfter100ms', function(){
   it('console logs hello ONLY after 100ms', function(done){
       setTimeout(function(){
           console.log('hello.');
           done();
       }, 100)
   })
})

Reference: https://mochajs.org/#asynchronous-code 参考: https//mochajs.org/#asynchronous-code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM