It's not entirely clear what you mean, because you (incorrectly) try to use injectJS which is for page context, but then pass a casper instance into myjs. So I provide 3 solutions.
Load into casper through require
If you want to load a remote file just as you would use require to load a local file into casper, then you should download it first:
var myjs;
casper.start(url)
casper.then(function(){
this.download('http://domain.com/test.js', 'test.js');
myjs = require('test'); // require the downloaded file
});
casper.then(function(){
// do your thing
var my_ = new myjs(casper);
name = my_.getName();
this.echo(name);
});
Doing that means that you have to export the function in the test.js file:
module.export = function(casper) {
this.getName = function(){
return 'this is a name';
};
};
If the test.js is located on another domain, then you need to start casperjs with --web-security=false flag.
Load into casper through eval
If you don't want to change test.js into a module then you could sent an ajax request to get the script and simply eval it.
var globalmyjs;
casper.start(url)
casper.then(function(){
var testJS = this.evaluate(function(){
return __utils__.sendAJAX('http://domain.com/test.js', 'GET', null, false); // synchronous
});
eval(testJS);
globalmyjs = myjs;
});
casper.then(function(){
// do your thing
var my_ = new globalmyjs(casper);
name = my_.getName();
this.echo(name);
});
If the test.js is located on another domain, then you need to start casperjs with --web-security=false flag.
Load into page context
Use this if myjs is to be executed in page context.
If you want to use the underlying phantomjs then it provides the includeJs(url, callback) function.
So you can use it like this:
var scriptLoaded = false;
casper.then(function() {
phantom.includeJs('http://domain.com/test.js', function(){
scriptLoaded = true;
});
casper.waitFor(function check() {
return scriptLoaded;
}, function then() {
this.evaluate(function(){
var my_ = new myjs(casper);
name = my_.getName();
console.log(name);
});
});
});
Though, you should use the casper.options.remoteScripts property.
So either inject the script on creation:
var casper = require("casper").create({
remoteScripts: [ 'http://domain.com/test.js' ]
});
or before a page load:
casper.options.remoteScripts.push('http://domain.com/test.js');
casper.start(url);
// or
casper.thenOpen(url);