Hooks are special functions in Playwright that run before or after tests. They are mainly used to handle common setup and cleanup tasks that should not be repeated inside every test. Using hooks helps keep test code clean, reusable, and easier to maintain.
Playwright Hook Types
Playwright provides the following hooks:
1. beforeAll: Runs once before all tests in a test file
2. beforeEach: Runs before every test
3. afterEach: Runs after every test
4. afterAll: Runs once after all tests in a test file
Hooks are useful when you want to share setup logic, such as opening a URL or preparing test data, without rewriting it in every test.
Example: Using Playwright Hooks
Create a test file named hooksTest.spec.js.
How This Works
1. beforeAll runs one time before any test starts
2. beforeEach opens the application before every test
3. Each test executes independently
4. afterEach runs after every test
5. afterAll runs once after all tests complete
This hook setup ensures tests are isolated, common setup logic is reused, and cleanup is handled automatically
Running the Test
Use the following command to execute the test:
Sample Output:
Note: this output is showing the suite execution order