簡體   English   中英

摩卡咖啡等待測試setTimeout函數

[英]mocha wait before testing a setTimeout function

我有一個函數,在稍微延遲后會調用另一個函數:

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

這可以正確添加漸變類,然后在350ms之后添加“ displayNone”類並刪除元素。 在摩卡咖啡中,我可以模擬使用jsdom單擊元素並檢查'fade'類,但想等待350ms來檢查'dislpayNone'類。

我能找到的所有示例都與http請求的承諾有關,但我只想暫停一下-這里有解決方案嗎?

您必須向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));
 });

});

這是一個快速延遲功能,您可以使用它來暫停350 ms,然后在測試中聲明所需的內容。

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

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

tryDelay(350);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM