0
0
Cypresstesting~5 mins

beforeEach and afterEach hooks in Cypress - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner

What is the purpose of the beforeEach hook in Cypress?

The beforeEach hook runs a block of code before each test in a test suite. It helps set up a consistent starting state for tests, like visiting a page or logging in.

Click to reveal answer
beginner

When is the afterEach hook executed in Cypress?

The afterEach hook runs a block of code after each test in a test suite. It is used to clean up or reset things after a test finishes, like clearing cookies or resetting data.

Click to reveal answer
beginner

How do beforeEach and afterEach hooks help in writing tests?

They help avoid repeating setup and cleanup code in every test. This makes tests shorter, easier to read, and less error-prone.

Click to reveal answer
beginner

Show a simple example of using beforeEach and afterEach in Cypress.

describe('My Test Suite', () => {
  beforeEach(() => {
    cy.visit('/login')
  })

  afterEach(() => {
    cy.clearCookies()
  })

  it('logs in successfully', () => {
    cy.get('#username').type('user')
    cy.get('#password').type('pass')
    cy.get('button[type=submit]').click()
    cy.url().should('include', '/dashboard')
  })
})
Click to reveal answer
intermediate

Can beforeEach and afterEach hooks be nested inside describe blocks?

Yes. Hooks inside a describe block only run for tests inside that block. This helps organize setup and cleanup for different groups of tests.

Click to reveal answer

What does the beforeEach hook do in Cypress?

ARuns code before each test
BRuns code after all tests
CRuns code only once before all tests
DRuns code after each test

When is the afterEach hook executed?

ABefore each test
BBefore all tests
CAfter each test
DOnly once after all tests

Which hook would you use to visit a page before every test?

AafterEach
BbeforeAll
CafterAll
DbeforeEach

Can beforeEach hooks be scoped inside describe blocks?

AYes, they run only for tests inside that block
BNo, they must be global
CYes, but they run for all tests anyway
DNo, only <code>afterEach</code> can be scoped

What is a benefit of using beforeEach and afterEach?

AThey make tests slower
BThey reduce code repetition and improve test clarity
CThey run tests in parallel
DThey replace the need for assertions

Explain how beforeEach and afterEach hooks improve test writing in Cypress.

Think about what happens before and after every test.
You got /4 concepts.

    Describe a scenario where you would use beforeEach and afterEach hooks in a test suite.

    Consider common setup and cleanup tasks in web testing.
    You got /4 concepts.