isDisplayed
如果选定的 DOM 元素显示(即使元素在视口之外),则返回 true。如果要验证元素也不在视口中,请使用 isDisplayedInViewport 命令。
信息
与其他元素命令相反,WebdriverIO 不会等待元素存在以执行此命令。
在执行浏览器测试时,WebdriverIO 使用自定义脚本专门用于评估元素的可见性。此脚本是确定元素是否显示在页面上的关键。相反,对于使用 Appium 的原生移动测试场景,WebdriverIO 会委托给 Appium 提供的isElementDisplayed
命令。此命令使用底层 Appium 驱动程序建立的标准评估元素的可见性,确保对移动应用程序进行准确且特定于驱动程序的评估。
用法
$(selector).isDisplayed([isWithinViewport=false])
参数
名称 | 类型 | 详情 |
---|---|---|
[isWithinViewport=false] 可选 | 布尔值 | 设置为 true 以检查元素是否在视口中 |
示例
index.html
<div id="noSize"></div>
<div id="noSizeWithContent">Hello World!</div>
<div id="notDisplayed" style="width: 10px; height: 10px; display: none"></div>
<div id="notVisible" style="width: 10px; height: 10px; visibility: hidden"></div>
<div id="zeroOpacity" style="width: 10px; height: 10px; opacity: 0"></div>
<div id="notInViewport" style="width: 10px; height: 10px; position:fixed; top: 999999; left: 999999"></div>
isDisplayed.js
it('should detect if an element is displayed', async () => {
elem = await $('#notExisting');
isDisplayed = await elem.isDisplayed();
console.log(isDisplayed); // outputs: false
let elem = await $('#noSize');
let isDisplayed = await elem.isDisplayed();
console.log(isDisplayed); // outputs: false
let elem = await $('#noSizeWithContent');
let isDisplayed = await elem.isDisplayed();
console.log(isDisplayed); // outputs: true
let elem = await $('#notDisplayed');
let isDisplayed = await elem.isDisplayed();
console.log(isDisplayed); // outputs: false
elem = await $('#notVisible');
isDisplayed = await elem.isDisplayed();
console.log(isDisplayed); // outputs: false
elem = await $('#zeroOpacity');
isDisplayed = await elem.isDisplayed();
console.log(isDisplayed); // outputs: false
elem = await $('#notInViewport');
isDisplayed = await elem.isDisplayed();
console.log(isDisplayed); // outputs: true
});
isDisplayedWithinViewport.js
it('should detect if an element is visible within the viewport', async () => {
let isDisplayedInViewport = await $('#notDisplayed').isDisplayed({ withinViewport: true });
console.log(isDisplayedInViewport); // outputs: false
isDisplayedInViewport = await $('#notVisible').isDisplayed({ withinViewport: true });
console.log(isDisplayedInViewport); // outputs: false
isDisplayedInViewport = await $('#notExisting').isDisplayed({ withinViewport: true });
console.log(isDisplayedInViewport); // outputs: false
isDisplayedInViewport = await $('#notInViewport').isDisplayed({ withinViewport: true });
console.log(isDisplayedInViewport); // outputs: false
isDisplayedInViewport = await $('#zeroOpacity').isDisplayed({ withinViewport: true });
console.log(isDisplayedInViewport); // outputs: false
});