Let's consider the case where I need to assert if an element exists. There are 2 possible ways of doing this in cypress:
1) cy.get('button').contains('Save') 2) cy.get('button').contains('Save').should('exist')
In both cases the test will fail if the 'Save' button not exist.
What are the reasons apart from maybe better code readability/maintainability that I should add the .should('exist') to my cypress tests?
Use . should('not. exist') to assert that an element does not exist in the DOM.
Cypress Commands - UI Interaction Commands. Assertions are the validation steps that determine whether the specified step of the automated test case succeeded or not. In actual, Assertions validates the desired state of your elements, objects, or application under test.
Conditionally check whether an element has certain text: get('body'). then(($body) => { // synchronously ask for the body's text // and do something based on whether it includes // another string if ($body. text(). includes('some string')) { // yup found it cy.
Cypress can validate the text on an element with the help of jQuery text() method. This method shall help us to fetch the text content on the selected element. We can also put assertions on the text content of the element. cy.
For your usecase of asserting whether an element exists, they are indeed redundant.
.contains()
yields a DOM element and according to documentation, .should
yields the same element it was given as an input. There are some exceptions when .should yields different element (as you can see in the documentation) but in case of using should('exist')
, they are really redundant
As you mentioned, I personally also prefer adding should
for better readability. Actually I prefer .should('be.visible')
because of following scenario - when an element is hidden or is pushed out of the screen because of some CSS issues, it doesn't exist from user perspective. But..
cy.get('button').contains('Save')
- passes test
cy.get('button').contains('Save').should('exist')
- passes test
cy.get('button').contains('Save').should('be.visible')
- fails test
Actually, until v4.0 is released (and this PR is merged), you need to chain should('exist')
assertion if you chain any negative assertions yourself. This is because the default should('exist')
assertion is skipped when you chain your own assertions.
Not necessary for positive assertions because they won't pass on non-existent elements.
Also see Implicit should 'exist' assertion is not being applied on cy.get() when other assertion.
Below, the element .first-item
does not exist but the assertion passes:
describe('test', () => { it('test', () => { cy.get('.first-item').should('not.have.class', 'is-selected'); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With