Test Hooks | Bondar Academy
Course: Playwright API Testing with TypeScript
Module: API Testing Basics
Instructor: Artem Bondar
Lesson Summary
In this lesson, we explore test hooks , a feature in testing frameworks that allows you to run specific operations before or after tests. There are four main types of test hooks: BeforeAllHook : Executes code before all tests in a test file. BeforeEachHook : Runs code before each individual test, useful for setting up preconditions. AfterEachHook : Performs cleanup after each test. AfterAllHook : Executes code after all tests have completed. The lesson demonstrates how to optimize tests using these hooks. Initially, the Playwright configuration is updated to include a list reporter alongside the existing HTML reporter for better visualization of test execution. Key points covered include: Setting up hooks at the top of the test file. Using console.log to demonstrate when hooks are executed in relation to tests. Understanding the implications of using after hooks and best practices for avoiding flaky tests. It is advised to use before hooks for setup and avoid relying on after hooks for cleanup to prevent test failures due to incomplete operations. Additionally, the lesson illustrates how to refactor code by moving repeated operations, such as creating a token, into a before all hook to enhance code efficiency and maintainability. This way, the token can be shared across tests without redundancy. In conclusion, test hooks are a powerful tool for optimizing test code and improving test execution flow.