CasperJS无法找到变量$

时间:2013-04-12 21:51:47

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

1 个答案:

答案 0 :(得分: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');
});

但是,请注意,您只能返回简单对象,因此您无法访问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');
});