What are the Hooks in Cypress

Hooks in Cypress are used to perform common tasks before and after test execution. They help in running reusable actions such as clearing test data, loading fixtures, or performing a login before tests run. Cypress provides several types of hooks, each serving a specific purpose.

Types of Hooks in Cypress

1. before Hook

The before hook runs once before all tests in a test file. It is commonly used for actions like setting up test data or performing a one-time login.

Example:

before(() => {
// Runs once before all tests
cy.log(‘Running setup before all tests’);
});

2. after Hook

The after hook runs once after all tests in a test file. It is useful for clean-up tasks such as deleting data or logging out.

Example:

after(() => {
// Runs once after all tests
cy.log(‘Running cleanup after all tests’);
});

3. beforeEach Hook

The beforeEach hook runs before every test, making it ideal for repeated setup tasks such as navigating to a page or resetting test state.

Example:

beforeEach(() => {
// Runs before each test
cy.log(‘Running before each test’);
});

4. afterEach Hook

The afterEach hook runs after every test, and is typically used for per-test cleanup operations.

Example:

afterEach(() => {
// Runs after each test
cy.log(‘Running after each test’);
});

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x