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.
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.
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.
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')
})
})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.
What does the beforeEach hook do in Cypress?
beforeEach runs before every test to set up the test environment.
When is the afterEach hook executed?
afterEach runs after every test to clean up.
Which hook would you use to visit a page before every test?
beforeEach is used to run code before each test, like visiting a page.
Can beforeEach hooks be scoped inside describe blocks?
Hooks inside describe run only for tests in that block, helping organize tests.
What is a benefit of using beforeEach and afterEach?
Using hooks avoids repeating setup/cleanup code, making tests clearer and easier to maintain.
Explain how beforeEach and afterEach hooks improve test writing in Cypress.
Describe a scenario where you would use beforeEach and afterEach hooks in a test suite.