Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import other javascript module in PhantomJS or CasperJS

I'm trying to build a functional test using CasperJS. caseperjs is run by a backend test suite using the following command:

PHANTOMJS_EXECUTABLE=../client/node_modules/phantomjs/bin/phantomjs  ../client/ext_modules/casperjs/bin/casperjs test ../client/test/functional/init.coffee

In init.coffee I want to import/include other module (file) which seats just next to it. How to do it?

The following doesn't works:

require("user")

All I want is to get a content from other file into init.coffee

like image 221
Robert Zaremba Avatar asked Jul 16 '13 10:07

Robert Zaremba


3 Answers

After trying a number of the other suggestions (each expected to work in the context of their corresponding environments), hit on this solution:

phantom.page.injectJs( 'script.js');
like image 107
Mark Simon Avatar answered Nov 05 '22 20:11

Mark Simon


As of 1.1, CasperJS relies on PhantomJS’ native require():
https://groups.google.com/forum/#!topic/phantomjs/0-DYnNn_6Bs

Injecting dependencies

While injecting additional modules, CasperJS looks for path relative to cur directory (the place where we run a casperjs command) We can inject dependency using clientScripts option. However the injected dependencies can't use require "globally". They are injected immediately to every page loaded.

casper.options.clientScripts = ["path/relative/to/cur/dir"]

Also we can inject modules using commandline args:

casperjs test --includes=foo.js,bar.js path/to/the/test/file

Using require

To import user modules use:

require "./user-module.coffee"

Then in user modules you can also use require. Using require paths are resolved relative to the current file (where require is called).
If in user module you want to import casper libs, then you need to patch require, check: https://casperjs.readthedocs.org/en/latest/writing_modules.html

like image 8
Robert Zaremba Avatar answered Nov 05 '22 20:11

Robert Zaremba


There's a section about that in the docs

var require = patchRequire(global.require);
require('./user');

In your case you should use global.require since you're using CoffeeScript.

like image 2
Alberto Zaccagni Avatar answered Nov 05 '22 19:11

Alberto Zaccagni