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

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

本文关键字:对象模型 出错 实现 js cucumber      更新时间:2023-09-26

我正试图用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;