In today's “Pinches of Cypress”, learn how to check that an element is not present at the DOM
This post's motivation came from the following question, by Anderson Faria, in a comment in another post.
How can we ensure that an element does not exist on the screen (e.g., a button or a menu option)?
Thanks for the question, Anderson!
The answer is simple.
Let's look at an example.
describe('Pinches of Cypress', () => {
it('"Pinches of pepper" is not present at the DOM', () => {
cy.visit('https://example.com')
cy.contains('Pinches of pepper')
.should('not.exist')
})
})
The same is true when identifying elements by a CSS selector (see below.)
describe('Pinches of Cypress', () => {
it('element with class "foo" is not present at the DOM', () => {
cy.visit('https://example.com')
cy.get('.foo').should('not.exist')
})
})
However, it’s a best practice to run a positive assertion before running the negative assertion. This ensures you’re ate the right place and avoids false positives.
For example.
describe('Pinches of Cypress', () => {
it('element with class "bar" is not present at the DOM', () => {
cy.visit('https://example.com')
cy.url().should('include', '/dashboard')
cy.contains('h1', 'Welcome to the Dashboard!').should('be.visible')
cy.get('.bar').should('not.exist')
})
})
That way, you’re sure you’re running the assertion at the right time.
I hope you learned something new!
What do you think about the series?
I'm looking forward to hearing your feedback.
This post was originally published in Portuguese on the Talking About Testing blog.
Would you like to learn about test automation with Cypress? Get to know my online courses on Udemy.
Top comments (2)
It works, thanks :)
I'm glad!