How to click on a checkbox and test that an element is no longer in the DOM in Cypress?

I want to be able to click on a checkbox and test that an element is no longer in the DOM in Cypress. Can someone suggest how to do it?

Currently, my test verifies that when the checkbox is clicked, the element is present in the DOM:

cy.get('[type="checkbox"]').click();
cy.get('.check-box-sub-text').contains('Some text in this div.');

I want to do the opposite of the test above. When I click the checkbox again, the div with the class check-box-sub-text should not be in the DOM. How can I achieve this using the Cypress should not exist assertion?

This works perfectly! It shows I still have more to learn about the .should() assertion in Cypress.

cy.get('.check-box-sub-text').should('not.exist');

This approach confirms that the element with the class check-box-sub-text is no longer in the DOM after clicking the checkbox.

To learn more about Cypress shloud() command, follow the given blog below:

You can also check if a specific text is not present in the DOM:

cy.contains('test_invite_member@gmail.com').should('not.exist');

Here’s what worked for me:

cy.get('[data-cy=parent]').should('not.have.descendants', 'img');

This checks that a

with the attribute data-cy=“parent” has no images inside. For the original question, you can set a data-cy attribute on the inner elements (e.g., data-cy=“child”) and use the following assertion:

cy.get('[data-cy=parent]').should('not.have.descendants', '[data-cy=child]');