我有一个包含许多元素的页面,其中五个是属性为零的 div 元素。这五个 div 中的每一个都有一个 Shadow root/shadow dom。我只对五个 div 之一感兴趣,其中包含一个带有特定文本的元素。我无法找到并过滤出正确的 div。我怎么做 ?我有一些代码仅当我有一个这样的 div 而不是五个时才有效。
cy.get("div").find(
'div.items span:contains("7")',
{
includeShadowDom: true,
}
).click();
我认为您可能会指定
div#shadowroot
两次 - 一次在 get 中,一次在 find 中。
如果我使用 Cypress 的
<cy-test-element>
构建一个类似的页面,其中有 ShadowDOM 子项,我可以毫无问题地找到 span:contains("7")
。
具有五个阴影元素的测试页面
<body>
<cy-test-element content="1"></cy-test-element>
<cy-test-element content="3"></cy-test-element>
<cy-test-element content="5"></cy-test-element>
<cy-test-element content="7"></cy-test-element>
<cy-test-element content="9"></cy-test-element>
<script type="text/javascript">
if (window.customElements) {
window.customElements.define('cy-test-element', class extends HTMLElement {
constructor () {
super()
const root = this.attachShadow({ mode: 'open' })
const content = this.getAttribute('content') || 'Shadow Content'
const className = this.hasAttribute('innerClass') ? this.getAttribute('innerClass') : 'shadow-content'
const rootAddition = this.hasAttribute('rootAddition') ? this.getAttribute('rootAddition') : 'shadow-content'
root.innerHTML = `<div class="shadow-div"><span class="${className}">${content}</span><input /><slot></slot></div>${rootAddition}`
}
})
}
if (window.location.search.includes('wrap-qsa')) {
const realQuerySelectorAll = document.querySelectorAll;
document.querySelectorAll = function (...args) {
return realQuerySelectorAll.apply(document, args);
};
}
</script>
</body>
实时页面的DOM
<cy-test-element innerclass="7" content="7">
#shadow-root
<div class="shadow-div">
<span class="7">7</span>
<input>
<slot></slot>
</div>
</cy-test-element>
测试
cy.get('cy-test-element')
.find('span:contains("7")', {includeShadowDom:true}) // passes