# Hooks

<div class="view-markdown-wrapper">
<ViewMarkdown />
</div>

Hooks allow you to run setup and teardown templates automatically before and after your tests. They provide a way to execute common preparation or cleanup tasks without duplicating them in every test case.

## Table of Contents

1. [What are Hooks?](#what-are-hooks)
2. [Types of Hooks](#types-of-hooks)
   - [Before Test Hook](#before-test-hook)
   - [After Test Hook](#after-test-hook)
3. [Execution Order](#execution-order)
4. [Configuring Hooks](#configuring-hooks)

## What are Hooks?

Hooks are [Templates](/cloud/test-editor/templates) that run automatically at specific points during test execution:

**Key Benefits:**

- **Consistency**: Ensure the same setup/cleanup runs for all tests
- **Reduced Duplication**: Define once, apply everywhere
- **Centralized Updates**: Modify the template, all tests using the hook are updated
- **Flexible Overrides**: Override hooks at the schedule or suite level when needed

## Types of Hooks

There are two types of hooks:

### Before Test Hook

Runs **before** the main test steps begin

**Common uses:**

- Accept cookie consent banners
- Close promotional popups
- Set up application state
- Navigate to a specific section
- Wait for page elements to load

### After Test Hook

Runs **after** all test steps complete, including any teardown steps. This hook runs in a "finally" block, meaning it executes even if the test fails.

**Common uses:**

- Log out of the application
- Clear shopping cart
- Reset application state
- Clean up test data
- Take final screenshots

## Execution Order

Understanding when hooks run is crucial for designing effective test flows:

```
1. Navigate to Starting URL
2. Login (if test account configured)
3. ▶ BEFORE TEST HOOK ◀
4. Main Test Steps
5. Teardown Steps (if any)
6. ▶ AFTER TEST HOOK ◀
```

**Key points:**

- Before Test hook runs **after** login completes
- After Test hook runs **after** teardown (in a nested "finally" block)
- After Test hook runs even if the test fails
- After Test hook runs even if teardown fails
- If Before Test hook fails, the test stops but After Test hook still runs

## Configuring Hooks

Configure hooks for individual test cases in the Environment Configuration:

1. Navigate to the test **Settings** tab
2. Click on an environment configuration to edit it
3. In the **Hooks** section:
   - Select a template for **Before Test**
   - Select a template for **After Test**
4. Click **Update Config**

Each environment configuration can have different hooks. For example, you might need different cookie consent handling for staging vs. production.

## Next Steps

- [Learn about Templates](/cloud/test-editor/templates) - Create reusable hooks
- [Test Configurations](/cloud/test-editor/test-configurations) - Configure hooks per environment
