0
0
Cypresstesting~15 mins

Value and attribute assertions in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify input field value and button attribute
Preconditions (1)
Step 1: Locate the input field with id 'username' and type 'testuser'
Step 2: Locate the input field with id 'username' and verify its value is 'testuser'
Step 3: Locate the submit button with id 'submit-btn' and verify it has attribute 'type' with value 'submit'
✅ Expected Result: The input field contains the typed value 'testuser' and the submit button has the correct 'type' attribute set to 'submit'
Automation Requirements - Cypress
Assertions Needed:
Assert input field value equals 'testuser'
Assert submit button has attribute 'type' with value 'submit'
Best Practices:
Use cy.get() with id selectors for locating elements
Use .type() to enter text into input fields
Use .should() for assertions on values and attributes
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('Value and attribute assertions test', () => {
  beforeEach(() => {
    cy.visit('/form');
  });

  it('should type username and verify value and button attribute', () => {
    cy.get('#username').type('testuser').should('have.value', 'testuser');
    cy.get('#submit-btn').should('have.attr', 'type', 'submit');
  });
});

This test visits the form page before each test to ensure a fresh start.

It types 'testuser' into the input field with id 'username' and immediately asserts that the input's value is 'testuser'.

Then it checks that the submit button with id 'submit-btn' has the attribute 'type' set to 'submit'.

Using cy.get() with id selectors ensures precise element targeting. The .should() command is used for clear, readable assertions.

Common Mistakes - 3 Pitfalls
{'mistake': "Using incorrect selector syntax like cy.get('username') instead of cy.get('#username')", 'why_bad': "This will not find the element because it misses the id selector symbol '#', causing the test to fail.", 'correct_approach': "Always use '#' prefix for id selectors, e.g., cy.get('#username')"}
Using cy.wait() to pause before assertions
{'mistake': "Checking attribute with .should('contain', 'submit') instead of .should('have.attr', 'type', 'submit')", 'why_bad': "The 'contain' assertion is not precise for attributes and may pass incorrectly.", 'correct_approach': "Use .should('have.attr', 'attributeName', 'expectedValue') for exact attribute checks."}
Bonus Challenge

Now add data-driven testing with 3 different usernames and verify the input value and button attribute for each.

Show Hint