What will be the output order of console logs when running this Cypress test?
describe('Test hooks order', () => { before(() => { cy.log('before all') }) beforeEach(() => { cy.log('before each') }) it('test 1', () => { cy.log('test 1') }) it('test 2', () => { cy.log('test 2') }) afterEach(() => { cy.log('after each') }) after(() => { cy.log('after all') }) })
Remember the order: before runs once before all tests, beforeEach runs before each test, afterEach runs after each test, and after runs once after all tests.
The before hook runs once before all tests. Then for each test, beforeEach runs, followed by the test, then afterEach. After all tests finish, after runs once.
You want to verify that a cleanup function in an after hook resets a global variable count to zero after all tests run. Which assertion correctly checks this?
let count = 0; describe('Count tests', () => { after(() => { count = 0; }); it('increments count', () => { count += 1; }); it('increments count again', () => { count += 2; }); });
The after hook runs after all tests, so assertions about cleanup should be inside it.
The after hook resets count to zero. To verify this, the assertion must be inside the after hook. Checking outside the describe block or inside tests will not reflect the reset.
Given this Cypress test, why is the afterEach hook not running after the tests?
describe('Sample tests', () => { afterEach(() => { cy.log('Cleaning up'); }); it('test A', () => { cy.log('Running test A'); }); context('Nested context', () => { it('test B', () => { cy.log('Running test B'); }); }); });
Consider how hooks apply to nested blocks in Cypress.
In Cypress, hooks declared in a describe block apply to tests inside that block only. The nested context creates a new block, so the afterEach hook in the outer describe does not run after tests inside the nested context.
Which statement best describes the purpose of before and after hooks in Cypress test suites?
Think about when before and after hooks run relative to tests.
before and after hooks run once per test suite to prepare and clean up the environment. They do not run before/after each test (that's beforeEach and afterEach), nor do they replace assertions or skip tests.
You want to reset the test database only once before all tests run and close the database connection only once after all tests finish. Which hook pair correctly implements this in Cypress?
Consider how often you want each action to run.
Resetting the database once before all tests and closing connection once after all tests requires before() and after() hooks. Using beforeEach() or afterEach() would run these actions multiple times unnecessarily.