2015-03-02 107 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