</>

Technology

Cypress

Difficulty

Beginner

Interview Question

What are Cypress assertions? Explain .should() and .expect().

Answer

Cypress Assertions

Cypress bundles Chai, Sinon-Chai, and Chai-jQuery for assertions.

.should() — Implicit Assertion (Retries Until True)

JavaScript
// Visibility
cy.get('.alert').should('be.visible')
cy.get('.modal').should('not.exist')
cy.get('#spinner').should('not.be.visible')

// Text content
cy.get('h1').should('have.text', 'Welcome')
cy.get('.title').should('contain', 'Dashboard')
cy.get('[data-testid="msg"]').should('include.text', 'success')

// Value (inputs)
cy.get('#email').should('have.value', 'test@example.com')
cy.get('select').should('have.value', 'option1')

// CSS class / attribute
cy.get('.btn').should('have.class', 'active')
cy.get('input').should('have.attr', 'placeholder', 'Enter email')
cy.get('a').should('have.attr', 'href').and('include', '/dashboard')

// Element state
cy.get('button').should('be.disabled')
cy.get('input[type="checkbox"]').should('be.checked')
cy.get('input').should('be.enabled')

// Length
cy.get('li').should('have.length', 5)
cy.get('tr').should('have.length.greaterThan', 0)
cy.get('[data-testid="item"]').should('have.length.at.least', 3)

// URL
cy.url().should('include', '/dashboard')
cy.url().should('eq', 'https://example.com/home')

.and() — Chain Multiple Assertions

JavaScript
// Chain multiple should() / and() on same element
cy.get('input#email')
  .should('be.visible')
  .and('not.be.disabled')
  .and('have.attr', 'type', 'email')

cy.get('.notification')
  .should('be.visible')
  .and('have.class', 'success')
  .and('contain', 'Saved successfully')

.expect() — Explicit Assertion (Inside Callbacks)

JavaScript
// Used inside .then() callbacks
cy.get('[data-testid="price"]').then(($el) => {
  const price = parseFloat($el.text().replace('$', ''));
  expect(price).to.be.greaterThan(0);
  expect(price).to.be.lessThan(1000);
});

cy.get('tbody tr').then(($rows) => {
  expect($rows).to.have.length.greaterThan(0);
  expect($rows.length).to.equal(5);
});

Negative Assertions

JavaScript
cy.get('.error-msg').should('not.exist')
cy.get('#spinner').should('not.be.visible')
cy.get('button').should('not.be.disabled')
cy.get('.modal').should('not.have.class', 'open')

Common Assertion Examples

JavaScript
it('should validate login form', () => {
  cy.visit('/login');

  // Initially disabled
  cy.get('[data-testid="login-btn"]').should('be.disabled');

  // Fill form
  cy.get('#email').type('user@example.com');
  cy.get('#password').type('Password123');

  // Now enabled
  cy.get('[data-testid="login-btn"]').should('be.enabled');

  // Submit and verify
  cy.get('[data-testid="login-btn"]').click();
  cy.url().should('include', '/dashboard');
  cy.get('h1').should('have.text', 'Dashboard');
  cy.get('.user-name').should('contain', 'user@example.com');
});

Follow AutomateQA

Related Topics