CasperJS找不到变量$ [英] CasperJS Can't find variable $

查看:88
本文介绍了CasperJS找不到变量$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

ReferenceError:找不到变量:$

ReferenceError: Can't find variable: $

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

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

推荐答案

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

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

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

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

但是,请注意,您只能返回简单的对象,因此您不能在评估对象之外访问jQuery对象(即,您不能返回JS对象),因此您必须返回所需的内容经过测试,如下所示

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

这篇关于CasperJS找不到变量$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆