0
0
CypressHow-ToBeginner ยท 3 min read

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 beforeEach outside the describe block, 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

FeatureDescriptionExample
beforeEachRuns code before each test in a describe blockbeforeEach(() => { cy.visit('/') })
describeGroups tests and hooksdescribe('Suite', () => { ... })
itDefines a single testit('does something', () => { ... })
Setup tasksCommon tasks like visiting pages or resetting databeforeEach(() => { 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.