admin管理员组

文章数量:1287163

Consider the below function,

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

Test code with mocha,

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

Consider the below function,

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

Test code with mocha,

describe('#helloAfter100ms()',function(){
  it('console logs hello ONLY after 100ms',function(){
    // what should go here
  })
})
Share Improve this question asked Oct 15, 2017 at 11:34 kalpakalpa 6973 gold badges11 silver badges23 bronze badges 1
  • I suggest you to use also sinon with mocha, which offers you ways for spying/mocking stuff and times manipulation for these cases of timeout for example: github./mochajs/mocha/wiki/Spies – quirimmo Commented Oct 15, 2017 at 11:42
Add a ment  | 

2 Answers 2

Reset to default 11

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.

Since this is not your code, you should probably not unit test it. Furthermore, setTimeout is probable something you can be sure works properly.

So what's left to test? Your code - the code that calls setTimeout. You can make sure that you're calling setTimeout correctly.

As to how this is done - there are two sinon features you can use. The first is useFakeTimers which gives you control of the clock. The second is a spy, which you should use on the console.log to make sure it was called.

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/#asynchronous-code

本文标签: javascriptHow to test a function that uses setTimeout() internally with mochaStack Overflow