How to use sugar.js with CasperJS?

75 Views Asked by At

To be clear, I want to use sugar.js extensions in my casperJS script (as distinct from it being part of the web site being tested).

I am using casperJS in test mode (i.e. casperjs test myscript.js) if that makes any difference.

2

There are 2 best solutions below

3
Artjom B. On BEST ANSWER

Sugar is basically a support library. It does not export any function, but adds functions to the various types of objects of a JavaScript runtime.

Steps:

  1. Place sugar.min.js in the script directory or some other directory,
  2. require("sugar.min"); to execute the file directly or from another directory require("./relativePath/sugar.min");.

The following complete script shows that it works:

casper.test.begin("sugar1", function suite(test){
    test.assertTrue(![1,2,3].average, "average function does not exist");
    require("sugar.min");
    test.assertFalse(![1,2,3].average, "average function does exist");
    test.assertTrue([1,2,3].average() === 2, "average function works");
    test.done();
});

require is usually for loading modules, but since Sugar does not export anything it is just executed. An alternative would be reading the file with fs.read and eval.

0
Darren Cook On

Just an addendum to Artjom's answer; when using SlimerJS as the engine it hangs when using require. I got it working (with both PhantomJS and SlimerJS) using the following:

var fs = require('fs');
var sugarJS = fs.read("/path/to/sugar.min.js");
eval(sugarJS);

as a drop-in replacement for:

require("/path/to/sugar.min");