【发布时间】:2015-08-10 16:48:52
【问题描述】:
我正在尝试从页面中获取文本,然后在规范中进一步使用该文本来断言另一个元素。
我粘贴了一个可以运行的非常简单的规范,它表明如果函数的 return 语句在量角器承诺 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 回答和我的评论之后更新了代码的 sn-p。
我正在尝试从页面上的各种文本构造一个对象并将其返回以在以后的页面中断言...
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;
}
【问题讨论】:
-
将返回后要执行的代码包装在匿名函数中,并将其作为参数传递给
getTextFromElements。然后只需将该参数作为一个函数调用,您就可以在其中尝试返回值。
标签: javascript node.js testing selenium-webdriver protractor