What is meant by (before/beforeEach) hook in testing?

The before() and beforeEach() hook

Let’s suppose we have a description of some tests. In these tests, we open a page and test some functionality. We want to open the page with the .visit() command for testing.

it('test #1', () => {

  cy.visit('/')
  // rest of your test

})

it('test #2', () => {

  cy.visit('/')
  // rest of your test

})

Things will repeat themselves somehow. In this case, we can use the before() hook to open all the test pages:

before(() => {

  cy.visit('/')

})

it('test #1', () => {
  // rest of your test
})

it('test #2', () => {
  // rest of your test
})

One thing to note here: test #2 may depend on the result of test #1. If the first test fails, the second test can start at a different location in our application and have a contagion effect that puts all at risk. It is good to isolate tests so that tests do not interfere. We may find the beforeEach() hook more useful. It will help achieve overall test stability.

Using the beforeEach() hook

Sometimes, we do tests in the beforeEach() block, which we run “globally”. We describe a case where API processing data and/or requirements are in a block. We use index.js file like this:

beforeEach(() => {

  Cypress.env('boards', []);
  Cypress.env('lists', []);

});

Where do we use these blocks?

We often use these hooks to trigger API requests, seed data, set authorization cookies, or perform similar activities that do not require opening the app in a browser.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved