最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Invoke JS method directly from CasperJS - Stack Overflow

programmeradmin1浏览0评论

I'm trying to test a page using CasperJS, in particular I want to poke the data model a bunch. Let's say I've got a basic function called taxes, and I want to ensure that it uses the right tax rate. So I'd like something like:

 this.test.assert(taxes(100, 'Ontario') === 15, "Check ontario tax rate");

Rather than filling out a form and seeing what it prints. That taxes method exists in the global scope, so I'm able to execute it quite easily from anywhere (including from the console in firebug or Chrome). But it's not in the right scope for that to work inside CasperJS (I think? I'm getting ReferenceError: Can't find variable: taxes.

It seems like I'm missing something simple.

TL;DR: How do I execute an on-page bit of JS directly inside a CasperJS test?

I'm trying to test a page using CasperJS, in particular I want to poke the data model a bunch. Let's say I've got a basic function called taxes, and I want to ensure that it uses the right tax rate. So I'd like something like:

 this.test.assert(taxes(100, 'Ontario') === 15, "Check ontario tax rate");

Rather than filling out a form and seeing what it prints. That taxes method exists in the global scope, so I'm able to execute it quite easily from anywhere (including from the console in firebug or Chrome). But it's not in the right scope for that to work inside CasperJS (I think? I'm getting ReferenceError: Can't find variable: taxes.

It seems like I'm missing something simple.

TL;DR: How do I execute an on-page bit of JS directly inside a CasperJS test?

Share Improve this question asked Dec 6, 2012 at 19:50 preinheimerpreinheimer 3,72222 silver badges34 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Have you tried using evaluate()?

relevant quote: "execute code as if you were using the browser console."

something along the lines of:

casper.evaluate(function(amount, province) {

    return taxes(amount, province);

}, {100, 'Ontario'});

Use assertEvalEquals() method.

If you're calling the method via a jQuery-style reference, make sure to explicitly include the library, lest you'll get the ReferenceError:

var casper = require('casper').create({ 
   clientScripts: ['js/jquery-1.7.2.js'] 
}); 

...

casper.start('foo.php', 
   function() { 
      console.log(this.evaluate(function() { 
         return $('taxes').text(); 
      }));
   }); 

casper.run();

See: https://groups.google./forum/#!msg/casperjs/2uyUOqdzShw/bHWrJYXni40J

If you're calling it implicitly in the global scope (i.e., straight javascript, rather than, for example, $('taxes')), you might have to explicitly prepend the window or document namespace to the reference:

document.querySelector('#taxes').value = taxes_text;
发布评论

评论列表(0)

  1. 暂无评论