Frazer Wilson
Frazer Wilson

Reputation: 161

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?

Upvotes: 2

Views: 2274

Answers (2)

pishpish
pishpish

Reputation: 2614

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));
 });

});

Upvotes: 4

Pavdro
Pavdro

Reputation: 427

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);

Upvotes: 0

Related Questions