'Cypress verify element does NOT flicker (disappear then quickly reappear)
Imagine I have the following simple html:
const inEl = document.querySelector("input")
const buttonEl = document.querySelector("button")
inEl.oninput = (() => {
buttonEl.remove()
setTimeout(() => {
document.body.appendChild(buttonEl)
}, 100)
})
.b {
background: blue;
}
<input>
<button>weee</button>
As you can see, as someone types in the input, the button is temporarily removed from the DOM. I'd like to add a cypress test that checks that the button is NOT removed from the dom (so it would need to fail for the above scenario).
It seems simple enough, but because cypress is so good at waiting for things to appear, I'm not totally sure how to write this test.
It feels like what I need is a way to throw an error if a cypress command does pass. Something like
cy.get("input").type("hello")
cy.get("button").should("not.exist") //if this passes then throw an error!
Any help on how to do this seemingly simple thing would be appreciated. Thanks!
Solution 1:[1]
https://docs.cypress.io/guides/core-concepts/retry-ability#Disable-retry
You can set the timeout to 0 to disable retry
so you could add
cy.get("button", { timeout: 0 }).should("not.exist")
to make sure the button does not flicker.
Solution 2:[2]
One possibility is to spy on the remove method
let spy;
cy.get("button").then($button => {
spy = cy.spy($button[0], 'remove')
})
cy.get("input").type("hello")
.should(() => expect(spy).to.not.have.been.called)
If you try to do visibility or existence checks you run the risk of false results, because that script will run quite quickly.
If you want to do so, you could control the clock
// This passes if the remove/append runs
cy.clock()
cy.visit(...)
cy.get("input").type("h") // one letter only
cy.tick(20) // 10ms is default delay in .type()
cy.get('button').should('not.exist') // clock is frozen part way through setTimeout
cy.tick(100)
cy.get('button').should('exist') // clock has moved past setTimeout completion
// This checks the remove/append does not run
cy.clock()
cy.visit(...)
cy.get("input").type("h") // one letter only
cy.tick(20)
cy.get('button').should('exist') // fails here if the button is removed
cy.tick(100)
cy.get('button').should('exist')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tgreen |
| Solution 2 |
