CasperJS实现自动化测试笔记(6)模块化

 

下面3个模块文件:echo.js、print.js、bonjour.js

//  filename: ModuleA/echo.js
exports.echo = function(o){ o.echo('echo, this is echo', 'debug'); }
//  filename: ModuleA/print.js
exports.print = function(){

        this.echo('print , this is print', 'debug');
}
//  filename: ModuleB/bonjour.js
exports.bonjour = function(){

        this.echo('bonjour, this is BONJOUR', 'debug');
} 

 

设置Caseper中Test对象选项,扩展出bind方法:

//  filename: ./testoption.js
exports.CaseOption = function(casper){ //function _CaseOption(){ casper.options.pageSettings = { loadImages: true, loadPlugins: true, userAgent: 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30' }; casper.options.stepTimeout = 1000 * 1000 * 120; casper.on('page.initialized', function(){ casper.evaluate(function(){ if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1),                    fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } }); }); }

 

执行步骤Case.js

var OPTION = require('./testoption');
var ECHO = require('ModuleA/echo');
var PRINT = require('ModuleA/print');
var BONJOUR = require('ModuleB/bonjour');

casper.test.begin("FirstCase", 1, function(test){

    this.logLevel = 'debug';

    casper.start("http://www.baidu.com/");

    casper.then(function(){
         OPTION.CaseOption(test);
    });

    casper.then(function(){
         ECHO.echo(this);
    }).then(function(){
         PRINT.print.call(this);
    }).then(function(){
         BONJOUR.bonjour.bind(this)();
    }).then(BONJOUR.bonjour.bind(this));

    casper.run(function(){
         this.echo("END ~~~");
         test.done();
         casper.exit(0);
    })
})

 

测试结果如下:

Test file: case.js
# FirstCase
echo, this is echo
print , this is print
bonjour, this is BONJOUR
END ~~~
FirstCase: 1 tests planned, 0 tests executed

 

casperjs有require功能,这个require应该可以实现模块化功能;模块写法和调用方法如上。

调用方法1:

casper对象作为参数:

比如,ECHO.echo(this);

调用方法2:

  call、apply方式绑定对象

  比如,PRINT.print.call(this);

调用方法3:

  bind方式绑定对象

  bind()调用方式封装在function里面,比如function(){ BONJOUR.bonjour.bind(this)(); },可以执行;放在then里面,比如then( BONJOUR.bonjour.bind(this) )却不能执行,奇怪~

 

posted @ 2015-03-27 17:06  FranklinYang  阅读(322)  评论(0)    收藏  举报