我正在尝试从我正在自动化的站点获取两个值。我遍历一组元素,然后尝试将下拉列表的值与页面上的值进行比较,以确保它们彼此相等。值之一只能由.getValue()
访问。另一个通过.getText()
访问。我想保存这些回调函数的result.value
并比较结果。
我尝试将这两个值都设为console.log
,然后又将它们取回,但是我无法从此回调函数返回任何内容。我也似乎无法将其值保存在变量中并返回它。我试图用document.getElementById()
在普通javascript中做到这一点,但是它适用于客户端javascript,而不是像nodejs这样的服务器端。只是试图将两个值进行比较
for (let i = 1; i <= 20; i++) {
browser
.element('css selector', `mat-nav-list > a:nth-child(${i})`,
function(result) {
if (result.value && result.value.ELEMENT) {
browser.isVisible(`mat-nav-list > a:nth-child(${i})`,
function(result) {
if (result.value === true) {
browser.click(`mat-nav-list > a:nth-child(${i})`)
let chunkView = '#mat-input-0';
let sideBar = `body > gps-app-root > div > div.sidebar-desktop > gps-app-sidebar-menu > div > div.product-list-wrap > mat-nav-list > a:nth-child(${i}) > div`
browser.getValue(chunkView, function(result) {
chunkView = result.value
console.log(chunkView)
})
browser.getText(sideBar, function(result) {
console.log(result.value);
})
}
})
}
})
//.pause(2000)
//.pause(10000)
}
当我遍历时,我希望两个值sideBar result.value
等于chunkView
result.value
。当前输出只能记录两个单独的值。
我以前没有使用过Nightwatch.js,因此我的答案基于browser.click
,browser.getValue
和browser.getText
异步运行的假设,因为这在UI和UI测试框架中相当普遍,并且,如果它们确实同步运行,则使用回调是没有意义的。
您可能会习惯于使用JavaScript Promise
。由于JavaScript引擎是单线程的,因此无法在其他线程处理某些更改(例如,在click事件之后更新UI)时自旋锁/睡眠。 Promise
允许您通过使用回调并处理后台事件来解决此问题。
然后您可以使用Promise
链接诺言,将返回的值传递到下一个回调。
不过,在您的情况下,我将包装两个在promise中检索值的函数,然后使用promise.then()
。这使他们可以按任何顺序完成操作,从而可以提高性能。
Promise.all()
使用Promise.all()
方法,以确保在下一个命令之前完成回调。 (请参见browser.isVisible(`mat-nav-list > a:nth-child(${i})`,
function(result) {
if (result.value === true) {
browser.click(`mat-nav-list > a:nth-child(${i})`);
let chunkView = '#mat-input-0';
let sideBar = `body > gps-app-root > div > div.sidebar-desktop > gps-app-sidebar-menu > div > div.product-list-wrap > mat-nav-list > a:nth-child(${i}) > div`;
let valPromise = new Promise(resolve => {
browser.getValue(chunkView, resolve);
});
let textPromise = new Promise(resolve => {
browser.getText(sideBar, resolve);
});
Promise.all([valPromise, textPromise]).then(([valueResult, textResult]) => {
browser.assert.strictEqual(valueResult.value, textResult.value,
`Server-side value '${value.result}' does not match client-side value '${text.result}'`);
});
}
});
)
这样的东西
perform
或者您可以链接https://github.com/nightwatchjs/nightwatch/wiki/Understanding-the-Command-Queue#the-perform-command命令,以便最后可以对中间步骤数进行比较。
browser.getValue(chunkView, function(result) {
chunkView = result.value
console.log(chunkView)
}).perform(function() {
// here you have access to chunkView so you can compare it
browser.getText(sideBar, function(result) {
console.log(result.value);
if (chunkView === result.value) {
console.log('They are the same!');
}
})
});
我发现如果我嵌套了.getValue()和.getText并分配了变量,我能够将两者进行比较。