CasperJS Can't find variable $

假如想象 提交于 2019-12-19 07:55:57

问题


I'm trying to inject jQuery in my test but I get the following error:

ReferenceError: Can't find variable: $

It is a ruby on rails application I'm trying to test, running on WEBrick. Here's all of the code:

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:


From the documentation it looks like you need to to use evaluate() to get a reference to the page that is loaded

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

However, note that you can only return simple objects , therefore you cannot access jQuery objects outside of the evaluate (that is, you can't return a JS object), so you'd have to return just what's required to be tested, like the following

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


来源:https://stackoverflow.com/questions/15981450/casperjs-cant-find-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!