Conditionally remove element from DOM depending on screen size

Viewed 1299

In my Vue/Vuetify app, I can conditionally hide elements depending on the screen size using the Vuetify display helper classes, e.g.

<!-- 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>

The element is hidden by setting the CSS property display: none. This causes the following Cypress command to fail

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

With the error

cy.click() can only be called on a single element. Your subject contained 2 elements

So evidently Cypress doesn't ignore elemnts with display: none.

Is there a way I either remove these elements instead of hiding them, or alternatively tell Cypress to ignore hidden elements?

2 Answers
  1. Add the data property "removeElement" to your data section.

  2. Add a watcher for the Vuetify breakpoint attribute, and set the "removeElement" to true/false depending on when you need to remove/add the element.

watch: {
    '$vuetify.breakpoint.width'(val) {
        if (val < 425)
            this.removeElement = true
        else
            this.removeElement = false
    },
},
  1. Update your template to use v-if="removeElement" instead of class=" .... "

The jquery :visible selector works, when the parent/ancestor has display: none.

Ref visibility

An element is considered hidden if:
...
Its CSS property (or ancestors) is display: none.

Test fiddle

/// <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)
})
Related