CasperJS无法找到变量$

Cai*_*len 5 javascript jquery casperjs

我试图在我的测试中注入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');
});
Run Code Online (Sandbox Code Playgroud)

Jua*_*des 14

从文档中看起来您需要使用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');
});
Run Code Online (Sandbox Code Playgroud)

但是,请注意,您只能返回简单对象,因此您无法访问evaluate之外的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');
});    
Run Code Online (Sandbox Code Playgroud)

  • 注释来自文档:您不能使用HTTP协议注入脚本,实际上您必须使用脚本资源的相对/绝对文件系统路径 (2认同)