0
0
Cypresstesting~5 mins

Negative assertions (not) in Cypress

Choose your learning style9 modes available
Introduction

Negative assertions check that something does not happen or exist. They help catch errors by confirming unwanted things are absent.

Check that a button is not visible before a user action
Verify that an error message does not appear on valid input
Ensure a checkbox is not checked by default
Confirm a link does not exist on a page
Test that a modal is not open before clicking a trigger
Syntax
Cypress
cy.get('selector').should('not.exist')
cy.get('selector').should('not.be.visible')
cy.get('selector').should('not.have.class', 'className')

Use should('not.exist') to check element absence in the DOM.

Use should('not.be.visible') to check element is hidden but present.

Examples
Check that the submit button is hidden on page load.
Cypress
cy.get('#submit-button').should('not.be.visible')
Verify no error message is shown before form submission.
Cypress
cy.get('.error-message').should('not.exist')
Confirm the checkbox is unchecked by default.
Cypress
cy.get('input[type="checkbox"]').should('not.be.checked')
Sample Program

This test visits a page and checks two things: the disabled button is hidden and no error message is present initially.

Cypress
describe('Negative assertions example', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io/commands/actions')
  })

  it('checks that the disabled button is not visible', () => {
    cy.get('#disabled-button').should('not.be.visible')
  })

  it('verifies error message does not exist initially', () => {
    cy.get('.error-message').should('not.exist')
  })
})
OutputSuccess
Important Notes

Negative assertions help confirm the absence or invisibility of elements.

Use clear selectors to avoid false positives in negative checks.

Combine with positive assertions for thorough testing.

Summary

Negative assertions check that something is not present or visible.

Use should('not.exist') for absence in the DOM.

Use should('not.be.visible') for hidden elements.