我尝试在测试中注入 jQuery,但出现以下错误:
ReferenceError:找不到变量:$
这是我正在尝试测试的 Ruby on Rails 应用程序,在 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');
});
从文档看来您需要使用评价()获取对已加载页面的引用
注意 在发现 CasperJS 时,此方法背后的概念可能是最难理解的。提醒一下,请将评估()方法视为 CasperJS 环境和您打开的页面之间的门户;每次将闭包传递给评估()时,您都会进入页面并执行代码,就像使用浏览器控制台一样。
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');
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)