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

Error when attempting to implement page object model using cucumber.js

我正在尝试使用 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');

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

有人知道我做错了什么吗?

设法解决了这个问题。问题是步骤中 '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;