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 testsbefore(() => { ... })- runs once before all testsit('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
beforecallback, causing tests to run before setup finishes. - Using
beforewhen you need setup before each test; usebeforeEachinstead. - Not grouping tests inside
describe, sobeforedoes 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
| Hook | Runs When | Use Case |
|---|---|---|
| before | Once before all tests in a describe block | Setup shared state or visit page once |
| beforeEach | Before each test | Reset state or prepare fresh data for every test |
| after | Once after all tests | Cleanup after tests |
| afterEach | After each test | Cleanup 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.