2013-04-12 67 views
5

我想在我的測試注入jQuery的,但我得到了以下錯誤:

的ReferenceError:找不到變量:$

它在軌道上紅寶石應用程序我試圖測試,運行在WEBrick上。 這裏的所有代碼:

var casper = require('casper').create({ 
    clientScripts: ['jquery-1.9.1.min.js'] 
}); 

//make sure page loads 
casper.start('http://127.0.0.1:3000', function() { 
    this.test.assertTitle('EZpub', 'EZpub not loaded'); 
}); 

//make sure all 3 fridges are displayed 
casper.then(function() { 
    //get fridges 
    var fridges = $('a[href^="/fridges/"]'); 
    this.test.assert(fridges.length == 3, 'More or less than 3 fridge links shown'); 
}); 

casper.run(function() { 
    this.echo('Tests complete'); 
}); 

回答

14

從它看起來的文件像你需要使用evaluate()去被加載

Note The concept behind this method is probably the most difficult to understand when discovering CasperJS. As a reminder, think of the evaluate() method as a gate between the CasperJS environment and the one of the page you have opened; everytime you pass a closure to evaluate(), you're entering the page and execute code as if you were using the browser console.

casper.then(function() { 
    var fridges = casper.evaluate(function(){ 
     // In here, the context of execution (global) is the same 
     // as if you were at the console for the loaded page 
     return $('a[href^="/fridges/"]'); 
    }); 
    this.test.assert(fridges.length == 3, 'More or less than 3 fridge links shown'); 
}); 

然而,頁面的引用,注意你只能返回簡單的對象,因此你不能在評估之外訪問jQuery對象(也就是說,你不能返回一個JS對象),所以你只能返回需要測試的東西,如下面的

casper.then(function() { 
    var fridgeCount = casper.evaluate(function(){ 
     // In here, the context of execution (global) is the same 
     // as if you were at the console for the loaded page 
     return $('a[href^="/fridges/"]').length; 
    }); 
    this.test.assert(fridgeCount === 3, 'More or less than 3 fridge links shown'); 
});  
+1

我不認爲這是問題所在。如果我不正確地拼寫路徑,我得到的錯誤:失敗注入jquey-1.9.1.min.js客戶端,我沒有得到當前的代碼。 – Cailen

+0

@ Cailen,提出一個新的答案 –

+0

謝謝!將其包含在evaluate()中是正確的方法。 – Cailen