【问题标题】:CasperJS Can't find variable $CasperJS找不到变量$
【发布时间】:2013-04-13 06:40:08
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery casperjs


    【解决方案1】:

    从文档看来,您需要使用evaluate() 来获取对已加载页面的引用

    注意这个方法背后的概念可能是发现 CasperJS 时最难理解的。提醒一下,将 evaluate() 方法视为 CasperJS 环境和您打开的页面之间的一道门;每次将闭包传递给 evaluate() 时,您都在进入页面并执行代码,就像使用浏览器控制台一样。

    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');
    });    
    

    【讨论】:

    • 我不认为这是问题所在。如果我不正确拼写路径,我会收到错误:注入 jquey-1.9.1.min.js 客户端失败,我没有使用当前代码。
    • @Cailen,提出一个新的答案
    • 谢谢!将其包裹在 evaluate() 是正确的方法。
    • 来自文档的注释:您不能使用 HTTP 协议注入脚本,您实际上必须使用脚本资源的相对/绝对文件系统路径
    • 我在搜索时遇到了这个问题,我的问题有点模糊。您只需将函数 object 传递给评估调用,不要执行该函数。我知道这一点,并且在这种情况下忽略了它,花了一段时间才注意到。打电话给evaluate(function),而不是evaluate(function())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多