我正在尝试在测试中注入(inject)jQuery,但出现以下错误:

ReferenceError:找不到变量:$

这是我正在尝试测试的,在WEBrick上运行的ruby on rails应用程序。
这是所有代码:

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()以获得对已加载页面的引用。


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

07-24 16:45