gpt4 book ai didi

javascript - CasperJS 找不到变量 $

转载 作者:数据小太阳 更新时间:2023-10-29 05:46:52 25 4
gpt4 key购买 nike

我试图在我的测试中注入(inject) 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');
});

最佳答案

从文档看来您需要使用 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');
});

关于javascript - CasperJS 找不到变量 $,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15981450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com