0
0
Cypresstesting~15 mins

expect() for BDD assertions in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify the page title and button text using BDD expect assertions
Preconditions (2)
Step 1: Open the URL 'https://example.cypress.io'
Step 2: Check that the page title is exactly 'Cypress.io: Kitchen Sink'
Step 3: Locate the button with id 'query-btn'
Step 4: Verify that the button text contains the word 'Button'
✅ Expected Result: The page title matches exactly 'Cypress.io: Kitchen Sink' and the button with id 'query-btn' contains text with the word 'Button'
Automation Requirements - Cypress
Assertions Needed:
Assert page title equals 'Cypress.io: Kitchen Sink' using expect()
Assert button text contains 'Button' using expect()
Best Practices:
Use cy.visit() to open the page
Use cy.title() to get the page title
Use cy.get() with id selector '#query-btn' to locate the button
Use .should() with a callback and expect() for assertions
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('BDD expect() assertions example', () => {
  it('checks page title and button text', () => {
    cy.visit('https://example.cypress.io');

    cy.title().should('equal', 'Cypress.io: Kitchen Sink');

    cy.get('#query-btn').should('be.visible').then(($btn) => {
      expect($btn.text()).to.include('Button');
    });
  });
});

This test opens the Cypress example page using cy.visit(). Then it checks the page title with cy.title() and asserts it equals the expected string using .should('equal', ...). Next, it finds the button by its id #query-btn and ensures it is visible. Using .then(), it accesses the button's text and uses expect() to assert the text includes the word 'Button'. This approach uses Cypress best practices: automatic waiting, clear selectors, and BDD style assertions with expect().

Common Mistakes - 3 Pitfalls
Using cy.get() with an incorrect or overly complex selector
Using cy.wait() with fixed time instead of relying on Cypress automatic waits
Using expect() outside of a .then() callback when working with Cypress commands
Bonus Challenge

Now add data-driven testing to check multiple buttons with different ids and expected text using expect() assertions

Show Hint