How to Use beforeEach in Cypress for Test Setup
In Cypress, use
beforeEach to run a block of code before every test in a describe block. This helps set up the test environment consistently, like visiting a page or resetting data, so each test starts fresh.Syntax
The beforeEach function takes a callback that runs before each test (it) inside the same describe block. It helps prepare the test environment.
Parts explained:
describe: Groups related tests.beforeEach: Runs setup code before each test.it: Defines an individual test.
javascript
describe('My Test Suite', () => { beforeEach(() => { // Setup code here }); it('Test 1', () => { // Test code }); it('Test 2', () => { // Test code }); });
Example
This example shows how to use beforeEach to visit a webpage before each test. It ensures every test starts on the homepage.
javascript
describe('Homepage Tests', () => { beforeEach(() => { cy.visit('https://example.cypress.io'); }); it('should have correct title', () => { cy.title().should('include', 'Kitchen Sink'); }); it('should contain the correct header', () => { cy.get('h1').should('contain.text', 'Kitchen Sink'); }); });
Output
Test 1: passes
Test 2: passes
Common Pitfalls
Common mistakes when using beforeEach include:
- Placing
beforeEachoutside thedescribeblock, causing it to run globally or not as expected. - Not resetting state properly inside
beforeEach, leading to flaky tests. - Using asynchronous commands incorrectly without returning or waiting, which can cause tests to run before setup finishes.
javascript
describe('Wrong Usage', () => { // Incorrect: beforeEach outside describe will run globally }); beforeEach(() => { cy.visit('https://example.cypress.io'); }); // Correct usage: describe('Right Usage', () => { beforeEach(() => { cy.visit('https://example.cypress.io'); }); it('Test runs after visit', () => { cy.title().should('include', 'Kitchen Sink'); }); });
Quick Reference
| Feature | Description | Example |
|---|---|---|
| beforeEach | Runs code before each test in a describe block | beforeEach(() => { cy.visit('/') }) |
| describe | Groups tests and hooks | describe('Suite', () => { ... }) |
| it | Defines a single test | it('does something', () => { ... }) |
| Setup tasks | Common tasks like visiting pages or resetting data | beforeEach(() => { cy.visit('/home') }) |
Key Takeaways
Use beforeEach inside describe to run setup code before every test.
beforeEach helps keep tests independent and reduces repeated code.
Always place beforeEach inside describe blocks to avoid unexpected behavior.
Ensure asynchronous commands in beforeEach complete before tests run.
Use beforeEach for common setup like visiting pages or resetting state.