0
0
Cypresstesting~15 mins

First Cypress test - Build an Automation Script

Choose your learning style9 modes available
Verify the homepage loads and displays the main heading
Preconditions (2)
Step 1: Open the browser and navigate to http://localhost:3000
Step 2: Check that the page loads successfully
Step 3: Locate the main heading element with the selector 'h1'
Step 4: Verify that the main heading text is 'Welcome to Our Site'
✅ Expected Result: The homepage loads without errors and the main heading displays the text 'Welcome to Our Site'
Automation Requirements - Cypress
Assertions Needed:
Verify the page URL is correct
Verify the main heading element exists
Verify the main heading text equals 'Welcome to Our Site'
Best Practices:
Use cy.visit() to open the page
Use cy.get() with a semantic selector for the heading
Use should() assertions for checking existence and text
Keep tests isolated and independent
Automated Solution
Cypress
describe('First Cypress Test - Homepage', () => {
  it('should load the homepage and display the main heading', () => {
    cy.visit('http://localhost:3000');
    cy.url().should('eq', 'http://localhost:3000/');
    cy.get('h1').should('exist').and('have.text', 'Welcome to Our Site');
  });
});

This test suite named First Cypress Test - Homepage contains one test case.

We use cy.visit() to open the homepage URL.

Then, cy.url().should('eq', ...) checks that the browser is on the correct page.

Next, cy.get('h1') finds the main heading element. The should('exist') assertion confirms it is present.

Finally, and('have.text', 'Welcome to Our Site') verifies the heading text matches exactly.

This approach uses clear selectors and assertions, making the test easy to read and maintain.

Common Mistakes - 4 Pitfalls
{'mistake': "Using cy.get() with a vague or incorrect selector like '.header' instead of 'h1'", 'why_bad': 'It may select the wrong element or fail if the class changes, making the test flaky.', 'correct_approach': "Use semantic selectors like 'h1' for main headings to keep tests stable and clear."}
Not asserting the URL after visiting the page
{'mistake': "Using .should('contain', 'Welcome') instead of .should('have.text', 'Welcome to Our Site')", 'why_bad': 'Partial text checks can pass even if the full text is incorrect, reducing test accuracy.', 'correct_approach': "Use exact text match with 'have.text' to ensure the heading is exactly as expected."}
{'mistake': 'Not chaining assertions and writing multiple cy.get() calls unnecessarily', 'why_bad': 'This makes tests longer and harder to read.', 'correct_approach': "Chain assertions like .should('exist').and('have.text', ...) for clarity and efficiency."}
Bonus Challenge

Now add data-driven testing to check the homepage heading for three different URLs with expected headings.

Show Hint