我正在验证网页中是否显示某个元素。
element(by.css('<css>')).isDisplayed()
如果显示它应该返回“true”。但是对于下面的代码
getElement = element(by.css('<css>'))
console.log(getElement.isDisplayed())
在控制台输出中打印整个元素。像下面这样
{ ptor_:
{ controlFlow: [Function],
schedule: [Function],
setFileDetector: [Function],
getSession: [Function],
getCapabilities: [Function],
quit: [Function],
actions: [Function],
touchActions: [Function],
executeScript: [Function],
executeAsyncScript: [Function],
call: [Function],
wait: [Function],
sleep: [Function],
getWindowHandle: [Function],
getAllWindowHandles: [Function],
getPageSource: [Function],
close: [Function],
getCurrentUrl: [Function],
.....................................................................
但是,当与 .then 函数一起使用时,它可以正常工作。
getElement.isDisplayed().then(function(isVisible){
if(isVisible){
<code to run if element is visible>
}
}
如果元素可见,则工作正常。
那么,.then(function()) 在这里究竟是如何工作的?
最佳答案
.then 表示该函数是 promise 。
Every promise starts in a pending state and may either be successfully resolved with a value or it may be rejected to designate an error.
当事情异步发生时,就会使用 Promise,例如,当您不知道需要多长时间才能在页面上找到某个元素或从服务器获取数据时(例如 $http.得到)。但是您需要此元素或数据才能使以下代码正常工作。
从字面上看,你 promise 一个值或一个最终值。 .then 调用此 Promise 进行解析,并返回解析后要使用的值。
在 Protractor 中,带有 Promise 函数的简单函数调用始终返回 Protractor 驱动程序(对象),这就是您在日志输出中看到的内容。除了较新 Protractor 版本 (2.0++) 中的 ElementFinder 函数之外,几乎所有公共(public) Protractor 函数都是 Promise。
此外,Protractor 的 expect 可以自动解析所有( Protractor )promise 函数。
expect(element(by.css('<css>')).isDisplayed()).toBe(true);
在其他任何地方您都需要手动解析该函数。 .isDisplayed() 函数还有一种特殊情况,该函数仅在元素存在于 DOM 中时才起作用。如果不是(例如 ngIf),.isDisplayed() 会抛出错误,您可以使用 .isElementPresent() 代替。
关于javascript - '.then' 函数在 AngularJS 的 Protractor E2E 测试中到底是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32222305/