2015-06-24 24 views
1

我目前使用注射CasperJS注入客戶端JavaScript未被完全加載?

casper.options.clientScripts.push('./include.js') 

這裏一個include.js真實include.js(這是確保所有Ajax請求完成:Using $.ajaxStop() to determine when page is finished loading in CasperJS

(function(){ 
    window._allAjaxRequestsHaveStopped = false; 
    var interval; 
    console.log('injecting include js') 
    $.ajaxSetup({'global':true}); 
    $(document).ajaxStop(function() { 
     console.log('NO MORE outstanding ajax calls'); 
     if (interval) { 
      clearInterval(interval); 
      interval = null; 
     } 
     interval = setTimeout(function() { 
      window._allAjaxRequestsHaveStopped = true; 
     }, 1000); 
    }); 
    $(document).ajaxStart(function() { 
     console.log('NEW ajax call'); 
     if (interval) { 
      clearInterval(interval); 
      interval = null; 
     } 
    }); 
    console.log('include js loaded'); 
})(); 

的問題是,有時ajaxStop & ajaxStart函數不會被加載,但它總是輸出第一個console.log'injecting include js'。

CasperJS腳本

casper.waitForAjax = (callback) -> 
    fn_wait = -> 
     casper.evaluate -> 
      return window._allAjaxRequestsHaveStopped 

    casper.waitFor fn_wait, callback 

casper.options.clientScripts.push('./include.js') 
casper.options.waitTimeout = 10000 

describe 'Main Test', -> 
    before -> 
     casper.start 'url', -> 
      phantom.clearCookies() 

    it 'Test Case 1', -> 
     casper.then -> 
      @click 'button' 
     casper.waitForAjax -> 
      // Move on with test 

所以有時候我的代碼將超時等待window._allAjaxRequestsHaveStopped把真正的,而其他時候,它會正常工作。我也在同一頁面上測試,我知道有一個Ajax請求。有誰知道如何解決這種不一致?

回答

0

Got it!所以看起來只有腳本的一部分被加載了,只要它到達$(document).ajaxStop(),就有一個錯誤,因爲jQuery沒有加載到頁面上。 CasperJS有時會在加載jQuery後注入包含文件,這就是爲什麼它有時會起作用。

通過下載jQuery和手動進固定它之前包括的文件:

casper.options.clientScripts.push('./jquery-2.1.4.min.js') 
casper.options.clientScripts.push('./include.js')