0
0
CypressHow-ToBeginner ยท 3 min read

How to Use before Hook in Cypress for Setup Tasks

In Cypress, use the before hook to run code once before all tests in a describe block. This is useful for setup tasks like visiting a page or setting test data before tests run.
๐Ÿ“

Syntax

The before hook runs once before all tests inside a describe block. It takes a callback function where you put setup code.

Structure:

  • describe('Test Suite', () => { - groups tests
  • before(() => { ... }) - runs once before all tests
  • it('test case', () => { ... }) - individual tests
  • }) - end of suite
javascript
describe('My Test Suite', () => {
  before(() => {
    // setup code here
  })

  it('does something', () => {
    // test code here
  })
})
๐Ÿ’ป

Example

This example shows using before to visit a webpage once before all tests run. Each test then checks page content without repeating the visit.

javascript
describe('Example of before hook', () => {
  before(() => {
    cy.visit('https://example.cypress.io')
  })

  it('has correct title', () => {
    cy.title().should('include', 'Cypress')
  })

  it('shows the correct header', () => {
    cy.get('h1').should('contain.text', 'Kitchen Sink')
  })
})
Output
Test run result: 2 tests passed, 0 failed
โš ๏ธ

Common Pitfalls

Common mistakes when using before include:

  • Putting asynchronous commands outside before callback, causing tests to run before setup finishes.
  • Using before when you need setup before each test; use beforeEach instead.
  • Not grouping tests inside describe, so before does not apply properly.
javascript
describe('Wrong usage example', () => {
  // This will NOT wait for visit to finish before tests run
  cy.visit('https://example.cypress.io')

  it('test 1', () => {
    cy.title().should('include', 'Cypress')
  })
})

// Correct usage

describe('Correct usage example', () => {
  before(() => {
    cy.visit('https://example.cypress.io')
  })

  it('test 1', () => {
    cy.title().should('include', 'Cypress')
  })
})
๐Ÿ“Š

Quick Reference

HookRuns WhenUse Case
beforeOnce before all tests in a describe blockSetup shared state or visit page once
beforeEachBefore each testReset state or prepare fresh data for every test
afterOnce after all testsCleanup after tests
afterEachAfter each testCleanup after each test
โœ…

Key Takeaways

Use before to run setup code once before all tests in a describe block.
Put asynchronous Cypress commands inside the before callback to ensure proper timing.
Use beforeEach if you need setup before every test instead of once.
Always group tests inside describe to apply hooks correctly.
Avoid running Cypress commands outside hooks or tests to prevent timing issues.