2017-05-30 25 views
1

我正在使用PhantomXHR以及CasperJS來實現前端功能測試以及截斷的AJAX請求。PhantomXHR + CasperJS在頁面的生命週期早期

僞造的XHR請求和存根響應在已經初始化的頁面中工作良好,並且AJAX請求由用戶操作(如單擊或鍵入)觸發。

但是,當嘗試在加載頁面時初始化僞造的XHR請求時,我無法使其工作。這是一個錯誤,或者推薦的方法是什麼?

我在SPA和初始化模板時使用了Marionette和Backbone,如果滿足某些條件,就會發起AJAX調用。無論我做什麼,我都無法讓PhantomXHR僞造這個請求。

我已經打過電話casper.start('http://localhost:3000/my/foo/bar')之前初始化PhantomXHR和僞造的要求,我已經打過電話casper.start(),初始化PhantomXHR,然後做casper.open('http://localhost:3000/my/foo/bar'),似乎沒有任何工作。任何人都可以告訴我這樣做的正確方法嗎?

回答

1

原來這是一個範圍操作順序問題。通過在CasperJS甚至啓動之前定義變量fake,然後在page.initialized CasperJS事件中將該僞造初始化爲一個變量,然後我甚至可以在任何地方導航,fake變量的範圍是正確的,並且可以被我的測試訪問。

var fakes = require('../base_fakes.js') 
var fake = null 

// Ensure that posts are being properly loaded into the UI with a stubbed XHR request 
// to fetch the posts from the server 
casper.test.begin('Loading stuff in the thing works', 5, function suite(test) { 
    casper.start(); 
    casper.on('page.initialized', function(resource){ 
    xhr.init(casper.page, { 
     libraryRoot: '../../../node_modules/phantomxhr/' 
    }) 

    fake = xhr.fake(fakes.things_index) 
    }) 

    casper.then(function() { 
    casper.open('http://localhost:3000') 
    this.wait(2000, function() { 
     console.log("test") 
     console.log(fake.count()); 
     this.capture('screenshot1.png') 
    }) 
    })