Page Object Pattern Implementation with CasperJS

▼魔方 西西 提交于 2019-11-30 18:17:34

问题


Is there anyone who have already implemented the famous "Page Object Pattern" with casperjs, it's very useful for test maintenability in the long term ?

It's very very cool to use that when you have to separe the mechanics and the purpose of your tests. it become more pleasurable to write your tests this way.

There are some examples with ruby and selenium:
http://blog.josephwilk.net/cucumber/page-object-pattern.html
https://code.google.com/p/selenium/wiki/PageObjects


回答1:


Here is an exemple of Page object pattern with CasperJS to test a login feature. The page object is in a file called LoginPage.js :

function LoginPage() {

  this.startOnLoginPage = function () {
    casper.echo("base url is : " + casper.cli.options.baseUrl);
    casper.start(casper.cli.options.baseUrl + '/login');
  };

  this.checkPage = function () {
    casper.then(function () {
      casper.test.assertUrlMatch('login', 'Is on login page');
      casper.test.assertExists('form[name="f"]', 'Login page form has been found');
    });
  };

  this.fillForm = function (username, password) {
    casper.then(function () {
      this.fill('form[name="f"]', {
        'j_username': username,
        'j_password': password
      }, false);
    });
  };

  this.submitForm = function () {
    casper.then(function () {
      this.click('form[name="f"] button[type="submit"]', 'Login submit button clicked');
    });
  };
}

Then you can use this Page Object on several tests. For example :

phantom.page.injectJs('LoginPage.js');
var loginPage = new LoginPage();

casper.test.begin('Should login', function (test) {
  loginPage.startOnLoginPage();
  loginPage.checkPage();
  loginPage.fillForm('scott', 'rochester');
  loginPage.submitForm();
});

For more details and a complete example : http://jsebfranck.blogspot.fr/2014/03/page-object-pattern-with-casperjs.html




回答2:


Using the example in your second link, you can convert this to a Javascript class-like object and encapsulate in its own module:

var LoginPage = function(casper) {
    this.casper = casper;
};

LoginPage.prototype.typeUsername = function(username) {

    this.evaluate(function() {
        __utils__.findOne('input.username').value = username;
    });
};

exports = LoginPage;

and then use it in your test:

var LoginPage = require("./LoginPage.js");
var login = new LoginPage(this);
login.typeUsername("geoff");


来源:https://stackoverflow.com/questions/21861903/page-object-pattern-implementation-with-casperjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!