所以,我有一個頁面對象文件,它爲頁面上的元素提供了許多方法。該頁面是一個包含文本,用戶名和密碼輸入元素以及登錄按鈕的登錄頁面。我創建了一個名爲「InputLabel.js」的通用對象,它將標籤和輸入元素綁定在一起以用於測試目的。驗證sendKeys導致頁面對象文件導致未定義的錯誤(量角器)
我遇到的問題是,我清除輸入後,發送數據,然後驗證數據,我得到一個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()
}
}
我是否失去了一些東西?同樣,錯誤是它失敗了,因爲它在發送密鑰後無法讀取未定義的屬性'verifyValue'。
當我把「這」。關閉它,我仍然得到同樣的錯誤。 '失敗:verifyValue未定義'。不過,我會看看你的鏈接並從中吸取教訓。謝謝。 – Machtyn
一旦你進入第一個承諾'el.clear()',你就失去了'this'的範圍,就像@finspin所說的那樣。在'sendKeys'函數的基本級別放置'var self = this;'(這將使您將範圍限定在InputLabel),然後使用'self.verifyValue(data);' – martin770
謝謝。這非常有幫助。自從我再次遇到它。 (我仍然在學習JavaScript風格。) – Machtyn