2013-07-25 40 views
1

casper.on(「resource.requested」),我們可以捕獲資源請求並執行評估檢查。casper.click()

在頁面加載時,我們將所有網絡請求URL推送到數組中,然後遍歷數組以查找對GOOGLE Analytics的調用次數(即_utm.gif)。

// google analytics calls testing 
casper.test.begin('Test Container Tags', function suite(test) { 

    casper.start("http://www.viget.com/", function() { 

    }); 

    var urls = [], 
     links = []; 

    casper.on('resource.requested', function(requestData, resource) { 
     urls.push(decodeURI(requestData.url)); 
    }); 

    casper.then(function() { 
     var index = -1; 
     var found = 0; 
     for (var i = 0; i < urls.length; i++) 
     { 
      index = urls[i].indexOf('__utm.gif'); 
      if (index > -1) 
       found = found+1; 
     } 
     casper.echo('found' + found); 
     test.assert(found > 0, 'Page Load Test Complete'); 
    }); 

    //Emit "resource.requested" to capture the network request on link click 
    casper.then(function(self) { 
     var utils = require('utils'); 
     var x = require('casper').selectXPath; 
     casper.click(x("//a[data-type]")); 
     casper.emit('resource.requested'); 
    }); 

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

但是,現在下一個Ask是驗證超鏈接點擊事件的網絡資源請求。試圖做到這一點casper.emit(「resource.requested」)但沒有成功。

已經花了一整天的時間找到相同的解決方法。任何反饋將讚賞在這一點上。

回答

1

你可以在點擊後使用casper.waitForResource()並在那裏進行驗證。

casper.test.begin('Test Container Tags', function suite(test) { 

casper.start("http://www.viget.com/", function() { 

}); 

var urls = [], 
    links = []; 

casper.on('resource.requested', function(requestData, resource) { 
    urls.push(decodeURI(requestData.url)); 
}); 

casper.then(function() { 
    var index = -1; 
    var found = 0; 
    for (var i = 0; i < urls.length; i++) 
    { 
     index = urls[i].indexOf('__utm.gif'); 
     if (index > -1) 
      found = found+1; 
    } 
    casper.echo('found' + found); 
    test.assert(found > 0, 'Page Load Test Complete'); 
}); 

//Emit "resource.requested" to capture the network request on link click 
casper.then(function(self) { 
    var utils = require('utils'); 
    var x = require('casper').selectXPath; 
    casper.click(x("//a[data-type]")); 

}); 

casper.waitForResource(function testResource(resource) { 
    console.log('----->' + resource.url); 
}); 

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

});