尝试使用cucumber.js实现页面对象模型时出错

时间:2015-11-21 04:34:03

标签: javascript selenium selenium-webdriver cucumberjs

我正在尝试使用selenium webdriver为我的cucumber.js测试自动化套件实现页面对象模式。但是,当我尝试从测试步骤调用页面对象时,我收到错误。我的文件夹结构如下:

features
|__pages - login_page.js
|__steps - login_steps.js
|__support - world.js

功能文件相当简单:

Feature File

Scenario: Login 
Given I browse to the login page
When I enter the username "test" and password "test"
Then I should be logged in successfully

我的登录页面如下:

'use strict';

exports.login = function () {
   this.driver.get('https://www.example.com/login');
   this.driver.findElement({ id: 'username' }).sendKeys('my username');
   this.driver.findElement({ id: 'password' }).sendKeys('my password');
   this.driver.findElement({ id: 'btn-login'}).click();
};

我的步骤定义文件是:

'use strict';

var expect = require('chai').expect;
var loginpage = require('../pages/LoginPage');


module.exports = function() {
   this.World = require('../support/world.js').World;

   this.Given(/^I enter the username "(.*)", and password (.*)"$/, function (username, password) {
//call page object
    loginpage.login();

    });


};

然而,当我运行测试时,我收到此错误消息:

TypeError: Cannot read property 'get' of undefined
      at Object.exports.login (/Users/Gerry/cuke/features/pages/LoginPage.js:9:16)

对应于以下行:this.driver.get(' https://www.example.com/login');

如果我将登录功能直接插入步骤(不调用页面对象),登录功能的上述步骤就可以正常工作。

有人知道我在这里做错了吗?

1 个答案:

答案 0 :(得分:0)

管理以解决这个问题。问题是步骤中“this”的上下文与页面对象中的上下文不匹配。我需要将'this'的当前上下文传递给页面函数。所以我的步骤现在看起来像这样:

'use strict';

var expect = require('chai').expect;
var loginpage = require('../../pages/LoginPage');
var World = require('../support/world.js').World;

module.exports = function() {
  this.World = World;
  this.Given(/^I enter the following login credentials "(.*)", and " (.*)"$/, function (username, password) {

    // We need to pass the current context of `this` so we can access
    // the driver in the page function
    loginpage.login(this, username, password);
});

我的登录页面功能现在看起来像这样:

'use strict';
exports.login = function (context, username, password) {
   context.driver.get('https://www.getturnstyle.com/login');
   context.driver.findElement({ id: 'username' }).sendKeys(username);
   context.driver.findElement({ id: 'password' }).sendKeys(password);
   context.driver.findElement({ id: 'btn-login'}).click();
};

module.exports = exports;