根据屏幕大小有条件地从DOM中移除元素



在我的Vue/Vuetify应用程序中,我可以使用Vuetify显示助手类(例如(根据屏幕大小有条件地隐藏元素

<!-- Show on medium width and above -->
<v-app-bar app height="74px" class="hidden-sm-and-down">
<button @click="logout" data-cy="logout">Log Out</button
</v-app-bar>
<!-- Show on small width and below -->
<v-app-bar app height="74px" class="hidden-md-and-up">
<button @click="logout" data-cy="logout">Log Out</button
</v-app-bar>

通过设置CSS属性display: none来隐藏该元素。这导致以下Cypress命令使失败

cy.get('[data-cy="logout"]').click()

带有错误

cy.click((只能在单个元素上调用。您的主题包含2个元素

很明显,Cypress不会忽略带有display: none的元素。

有没有办法删除这些元素而不是隐藏它们,或者告诉Cypress忽略隐藏的元素?

  1. 添加数据属性"removeElement";到您的数据部分。

  2. 为Vuetify断点属性添加一个观察程序;removeElement";设置为true/false,具体取决于何时需要删除/添加元素。

watch: {
'$vuetify.breakpoint.width'(val) {
if (val < 425)
this.removeElement = true
else
this.removeElement = false
},
},
  1. 更新您的模板以使用v-if="removeElement";而不是class="…">

当父/祖先具有display: none时,jquery:visible选择器工作。

参考能见度

如果以下情况,则元素被视为隐藏:

其CSS属性(或祖先(为display: none

测试小提琴

/// <reference types="@cypress/fiddle" />
const test = {
html: `
<div>
<header style="display: none">
<button data-cy="logout">Button small</button>
</header>
<header>
<button data-cy="logout">Button medium</button>
</header>
</div>
`,
test: `
cy.get('[data-cy="logout"]:visible').click()
`
}
it('the test', () => {
cy.runExample(test)
})

最新更新