我正在尝试从页面中获取文本,然后在规范中进一步使用该文本来断言另一个元素。
我粘贴了一个您可以运行的非常简单的规范,它表明如果函数的返回语句位于 Protractor promise return txt;
中,则您无法从函数返回值(第 24 行) ……
describe('My Test', function () {
var tempVariable;
it('should go get some text from the page', function () {
browser.get('https://angularjs.org/');
tempVariable = getTextFromElement(); //it appears javascript immediately sets this variable before waiting for protractor to return the value
});
it('should do some random other stuff', function () {
element.all(by.cssContainingText('a', 'Learn')).get(0).click();
element.all(by.cssContainingText('a', 'Case Studies')).get(0).click();
element.all(by.cssContainingText('a', ' Home')).get(0).click();
});
it('should be able to use the text from the first page in this test', function () {
console.log('\ntempVariable: ' + tempVariable); //this is undefined!
expect(typeof tempVariable).not.toBe('undefined', 'failed: tempVariable was undefined!');
});
});
function getTextFromElement() {
$('a.learn-link').getText().then(function (txt) {
console.log('\nInitial text: ' + txt);
return txt; //how do we return this so it's available to other 'it' blocks?
});
}
在@alecxe 回答和我的评论之后更新了代码片段。
我正在尝试从页面上的各种文本构造一个对象并将其返回以在后面的页面中断言...
function getRandomProductFromList() {
var Product = function (line, name, subname, units) {
this.line = line;
this.name = name;
this.subname = subname;
this.units = units;
};
var myProduct = new Product();
myProduct.line = 'Ford';
myProduct.units = 235;
//select a random product on the page and add it to 'myProduct'
var allProducts = element.all('div.product');
allProducts.count().then(function (count) {
var randomIndex = Math.floor(Math.random() * count);
var productName = allProducts.get(randomIndex);
productName.getText().then(function (prodName) {
myProduct.name = prodName;
productName.click();
});
});
//If a sub-product can be chosen, select it and add it to 'myProduct'
var subproduct = $('div.subproduct');
subproduct.isDisplayed().then(function (subProductExists) {
if (subProductExists) {
subproduct.getText().then(function (subProductName) {
myProduct.subname = subProductName;
});
subproduct.click();
}
}, function (err) {});
return myProduct;
}
最佳答案
首先,您没有从函数返回任何东西:
function getTextFromElement() {
return $('a.learn-link').getText();
}
现在,此函数将返回一个 promise ,您需要在使用前解决该问题:
it('should be able to use the text from the first page in this test', function () {
tempVariable.then(function (tempVariableValue) {
console.log('\ntempVariable: ' + tempVariableValue);
expect(typeof tempVariableValue).not.toBe('undefined', 'failed: tempVariable was undefined!');
});
});
另外,为了确定变量是否已定义,我会使用来自 jasmine-matchers
的 toBeDefined()
:
expect(tempVariableValue).toBeDefined();
关于javascript - 从函数内的 Protractor promise 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31925005/