在页面对象文件中验证sendKeys结果会导致未定义的错误(Protractor)

Verifying sendKeys result in a Page Object file results in undefined error (Protractor)

本文关键字:未定义 错误 Protractor 结果 对象 面对 文件 sendKeys 验证      更新时间:2023-09-26

因此,我有一个页面对象文件,它为页面上的元素提供了许多方法。该页面是一个登录页面,包含一些文本、用户名和密码输入元素以及登录按钮。我创建了一个名为"InputLabel.js"的通用对象,它将标签和输入元素绑定在一起以进行测试。

我遇到的问题是,在我清除输入、发送数据,然后验证数据之后,我得到了一个Failed: Cannot read property 'verifyValue' of undefined错误。

以下是相关代码:

// InputLabel.js
function InputLabel(container) {
    this.Container = container;
}
InputLabel.prototype = {
    constructor: InputLabel,
    // ...
    /**
     * Return the element for the input of the input/label combination of elements.
     * 
     * @returns {ElementFinder}
     */
    getInput: function () {
        return this.Container.$('input');
    },
    /**
     * Return the text shown in the input of the input/label combination of elements.
     * 
     * @returns {Promise}
     */
    getValue: function () {
        return this.getInput().getAttribute('value');
    },
    /**
     * Verify the text shown in the input of the input/label combination of elements.
     * 
     * @param expected The expected text in the input element.
     */
    verifyValue: function (expected) {
        console.log('Asserting input value [' + expected + ']');
        expect(this.getValue()).toEqual(expected);
    },
    // ...
    /**
     * Clears the input element then puts the text from data into the input element.
     * 
     * @param data The text to be entered into the input element.
     */
    sendKeys: function (data) {
        var el = this.getInput();
        el.clear().then(function () {
            el.sendKeys(data).then(function () {
                console.log("Verifying [" + data + "] was sent to the input.")
                this.verifyValue(data);
            });
        });
    }
};

在需要该文件之后,除了sendKeys之外,我可以毫无问题地调用这些方法中的任何一个。如果我禁用了this.verifyValue(data);方法,sendKeys可以正常工作。

// LoginPage.js
var InputLabel = require('InputLabel.js');
function LoginPage() {
}
var username = new InputLabel($('#username'));
var password = new InputLabel($('#password'));
function.prototype = {
   // ...
   username: username,
   password: password,
   loginButton: {
      get: function() { return $('#Login'); },
      click: function() { return this.get().click(); }
   },
   // ...
   login: function(user, pw) {
      this.username.sendKeys(user);
      this.password.sendKeys(pw);
      this.loginButton.click()
   }
}

我是不是失去了一些范围内的东西?同样,错误是它失败了,因为它在发送密钥后无法读取undefined的属性"verifyValue"。

在包含"this.verifyValue(data);"的行中,"this"关键字存在作用域问题。在本例中,"this"关键字不引用InputLabel类。此外,保持页面对象断言自由也是一种很好的做法。看见http://martinfowler.com/bliki/PageObject.html