0
0
Cypresstesting~5 mins

Value and attribute assertions in Cypress

Choose your learning style9 modes available
Introduction

We use value and attribute assertions to check if a web element has the right value or attribute. This helps us make sure the page works as expected.

Checking if an input box contains the correct text after typing.
Verifying a button has the right disabled state.
Making sure an image has the correct source URL.
Confirming a link has the correct href attribute.
Testing if a checkbox is checked or unchecked.
Syntax
Cypress
cy.get('selector').should('have.value', 'expectedValue')
cy.get('selector').should('have.attr', 'attributeName', 'expectedAttributeValue')

have.value checks the value property of form elements like inputs.

have.attr checks any attribute on the element, like href, src, disabled.

Examples
This checks if the input with id 'username' has the value 'john_doe'.
Cypress
cy.get('#username').should('have.value', 'john_doe')
This checks if the button element has the 'disabled' attribute present.
Cypress
cy.get('button').should('have.attr', 'disabled')
This checks if the image with class 'logo' has the source '/images/logo.png'.
Cypress
cy.get('img.logo').should('have.attr', 'src', '/images/logo.png')
Sample Program

This test suite visits a sample page. It types an email and checks the input value. It checks if a button is disabled. It also verifies a link's href attribute.

Cypress
describe('Value and Attribute Assertions Example', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io/commands/actions')
  })

  it('checks input value after typing', () => {
    cy.get('.action-email')
      .type('test@example.com')
      .should('have.value', 'test@example.com')
  })

  it('checks button disabled attribute', () => {
    cy.get('.action-disabled')
      .should('have.attr', 'disabled')
  })

  it('checks link href attribute', () => {
    cy.get('.home-link')
      .should('have.attr', 'href', '/')
  })
})
OutputSuccess
Important Notes

Use have.value only for form elements like input, textarea, select.

Use have.attr to check any attribute, including boolean attributes like disabled.

Assertions wait automatically in Cypress, so no need for extra waits.

Summary

Value assertions check the content of form fields.

Attribute assertions check any attribute on an element.

These assertions help confirm the page behaves as expected.