If you plan to write your own modules in CasperJS then don’t worry, It is possible in very less effort. There are a lot of benefits to using modules instead of an interdependent codebase. Updating a single module is much easier and Reusability is also the main factor for modularized the code.
In this blog, we will learn how to write your own modules using CasperJS. For creating modules in CasperJS, you have to call the patchRequire()
function. We have two js files, one is Module.js and another is Root.js. Under Module.js file, I wrote the script for login and for adding product. From Root.js file, we can get our result. In Root.js file we have to require the Module.js.
/** * Webkul Software. * * @category Webkul * @package Webkul_CasperJS * @author Shikha Bhardwaj * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ // my module, stored in Module.js // patching phantomjs' require() var require = patchRequire(require); var utils = require('utils'); exports.login = function(casper, current) { current.fill('form', { username: 'admin', password: 'admin' }, true); casper.wait(2000, function() { val = this.getCurrentUrl(); val2 = val.split("token="); productadd(casper, current, val2[1]); current.capture('home.png'); current.echo(current.getTitle()); current.echo(val2[1]); current.echo(this.getCurrentUrl()); if (current.getTitle() == 'Dashboard') { return true; } else { console.log("Login"); } }); }; var productadd = function(casper, current, token) { current.capture('home2.png'); var url = 'http://example.com/admin/index.php?route=catalog/product/add&token=' + token; console.log(url); casper.start(url, function() { console.log(this.getCurrentUrl()); this.capture('home3.png'); this.fill('form#form-product', { 'product_description[1][name]': 'casper-test', 'product_description[1][meta_title]': 'casper-test', 'model': 'casper-test' }, true); casper.wait(2000, function() { this.capture('home4.png'); return this.getTitle(); }); }); };
Here is the root Casper script.
var obj = require('Module'); var casper = require('casper').create(); var url = 'http://example.com/admin/index.php?route=common/login'; casper.start(url, function() { loggedIn = obj.login(casper, this); //adds product named as casper-test }); casper.run();
Now you have to run a command on your terminal-
casperjs Root.js