How to Write Your First Test in Cypress Quickly
Cypress, create a test file inside the cypress/e2e folder and use describe and it blocks to define your test suite and test case. Use cy.visit() to open a webpage and cy.get() with assertions like should('be.visible') to check elements.Syntax
The basic syntax for a Cypress test includes a describe block to group tests and an it block for individual test cases. Inside the test case, use Cypress commands like cy.visit() to open a page and cy.get() to select elements. Assertions check if elements behave as expected.
describe('Test Suite Name', () => { ... }): Groups related tests.it('Test Case Name', () => { ... }): Defines a single test.cy.visit('url'): Opens the webpage.cy.get('selector'): Finds an element on the page..should('assertion'): Checks conditions like visibility or text.
describe('My First Test Suite', () => { it('Visits the example page and checks title', () => { cy.visit('https://example.cypress.io') cy.get('h1').should('be.visible') }) })
Example
This example test visits the Cypress example page and verifies that the main heading is visible. It shows how to write a simple test that opens a page and checks an element's visibility.
describe('Example Page Test', () => { it('should load the page and show the main heading', () => { cy.visit('https://example.cypress.io') cy.get('h1').should('be.visible') }) })
Common Pitfalls
Beginners often forget to put tests inside describe and it blocks or use incorrect selectors. Another common mistake is not waiting for elements to load before asserting, but Cypress commands handle waiting automatically. Avoid using brittle selectors like classes that change often; prefer stable selectors like data attributes.
/* Wrong: Missing 'it' block */ describe('Test Suite', () => { cy.visit('https://example.cypress.io') cy.get('h1').should('be.visible') }) /* Right: Proper test structure */ describe('Test Suite', () => { it('checks heading visibility', () => { cy.visit('https://example.cypress.io') cy.get('h1').should('be.visible') }) })
Quick Reference
Remember these key commands when writing your first Cypress test:
| Command | Purpose |
|---|---|
| describe('name', fn) | Groups tests into a suite |
| it('name', fn) | Defines a single test case |
| cy.visit(url) | Opens a webpage |
| cy.get(selector) | Selects an element on the page |
| should('assertion') | Checks an element's state or content |