简体   繁体   中英

mocha wait before testing a setTimeout function

I have a function which calls another after a slight delay:

const messageboxes = {    
    fade: target => {
        target.classList.add('fade');
        window.setTimeout(messageboxes.hide, 350, target);
    },
    hide: el => {
        el.classList.add('displayNone');
        el.parentNode.removeChild(el);
    }
};

This correctly adds the fade class then after 350ms adds 'displayNone' class and deletes element. In mocha i can simulate clicking the element with jsdom and check for the 'fade' class, but want to wait 350ms to check for the 'dislpayNone' class.

All the examples i can find relate to promises of http requests, but i just want a pause - is there a solution here?

You have to signal the end of execution to mocha:

describe('setTimeout test', function(){

 it('Use `done` callback', function(done){
   window.setTimeout(function(){
     // Assert here.
     done();
   }, 350);
 });

 it('Return promise', function(){
   return new Promise((resolve, reject) => window.setTimeout(function(){
     // Assert here.
     resolve();
   }, 350));
 });

});

Here's a quick delay function that you can use to pause for 350 ms and then Assert what you want in your test.

function tryDelay(delayMs){
  var startMs = Date.now();
  var curMs = Date.now();

  while((startMs + delayMs) > curMs)
  {
    curMs = Date.now();
  }
}

tryDelay(350);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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