2015-03-02 108 views
0

我正在嘗試使用Sinon和CasperJS來測試我的超時功能。此頁面顯示在數字標牌上,因此它不是典型的網頁 - 它具有很長的使用壽命,因此超時值很高。sinon.useFakeTimers不會觸發超時

下面是我試圖測試相關代碼:

RiseVision.Image = (function() { 
    // Private 
    function startTimer() { 
    setTimeout(function() { 
     var img = document.getElementById("image"); 
     img.style.backgroundImage = "url(http://s3.amazonaws.com/images/logo-small.png?" + new Date().getTime() + ")"; 
    }, 900000); 
    } 

    // Public 
    function ready() { 
    ... 
    } 

    return { 
    "ready": ready 
    }; 
})(); 

我使用CasperJS對我的測試中,像這樣:

var e2ePort = system.env.E2E_PORT || 8099; 
var url = "http://localhost:"+e2ePort+"/src/widget-e2e.html"; 
var clock; 

casper.test.begin("Image Widget - e2e Testing", { 
    test: function(test) { 
    casper.start(); 

    casper.thenOpen(url, function() { 
     test.assertTitle("Image Widget", "Test page has loaded"); 
    }); 

    casper.then(function() { 
     casper.waitFor(function waitForUI() { 
     return this.evaluate(function loadImage() { 
      // Wait for the background image to be set. 
      return document.getElementById("image").getAttribute("style") !== ""; 
     }); 
     }, 
     function then() { 
     // Do some assertions here. 

     casper.waitFor(function waitForTimer() { 
      return this.evaluate(function expireTimer() { 
      clock = sinon.useFakeTimers(); 
      clock.tick(900000); 

      return document.getElementById("image").getAttribute("style") !== 
      "background-image: url(http://s3.amazonaws.com/images/logo-small.png);"; 
      }); 
     }, 
     function then() { 
      // More assertions here. 
     }); 
     }); 
    }); 

    casper.run(function runTest() { 
     test.done(); 
    }); 
    } 
}); 

我知道這個功能被執行,因爲我可以成功地從它裏面記錄消息,但它不會觸發我的計時器。如果我公開startTimer函數,似乎沒有什麼區別。

任何想法?

Thx。

EDITED - 已更新以包含更多代碼。

+0

謝謝。更新我的問題以包含更多的澄清代碼。乾杯。 – donnapep 2015-03-03 14:11:52

回答

0

您可能是指使用一個時鐘實例,而不是每50毫秒創建一個(這就是waitFor所做的)。

casper.evaluate(function() { 
    window._fakeClock = sinon.useFakeTimers(); 
}); 

casper.waitFor(function waitForTimer() { 
    return this.evaluate(function expireTimer() { 
    window._fakeClock.tick(900001); 

    return document.getElementById("image").getAttribute("style") !== 
    "background-image: url(http://s3.amazonaws.com/images/logo-small.png);"; 
    }); 
}, 
function then() { 
    this.evaluate(function() { 
     window._fakeClock.restore(); 
    }); 

    // More assertions here. 
}); 
+0

有點晚了。這或多或少是黑暗中的一擊。 – 2015-03-04 19:53:38

+0

好點重新:創建多個定時器。修正了,但它仍然無法正常工作。我實際上不得不完全跳過這個測試,因爲我無法實現它的工作。 – donnapep 2015-03-06 20:00:34