API Hooks for Tests – Before Each & After Each Hooks

API Hooks allow you to execute API calls before and after test execution. Use hooks to set up test data, authenticate users, clean up resources, and perform other operations that support your test scenarios.

What are API Hooks?

API Hooks are API calls that execute automatically at specific points during test execution. They allow you to perform setup and teardown operations, manage test data, handle authentication, and more without including these steps in your main test flow.

Hook Types

  • Before Each: Executes before each test case runs
  • After Each: Executes after each test case completes
  • Before All: Executes once before all tests in a suite (if available)
  • After All: Executes once after all tests in a suite (if available)

Common Use Cases

Authentication

Authenticate users before tests run, eliminating the need to include login steps in every test.

Example: Call login API, store auth token, use token in test headers

Test Data Setup

Create test data (users, orders, content) before tests execute.

Example: Create test user via API, use user in test, delete user in after hook

Environment Preparation

Prepare the test environment (clear cache, reset state, etc.).

Example: Clear user session, reset feature flags, prepare test environment

Cleanup

Clean up test data and resources after tests complete.

Example: Delete test data, reset database state, clear temporary files

Setting Up API Hooks

Step 1: Access Hook Configuration

Navigate to test configuration and find the Hooks section.

  • Open Test Management Modal
  • Go to "Hooks" or "API Hooks" section
  • Select hook type (Before Each, After Each)

Step 2: Configure API Call

Set up the API call details for your hook.

  • Enter API endpoint URL
  • Select HTTP method (GET, POST, PUT, DELETE)
  • Configure headers (authentication, content-type, etc.)
  • Add request body if needed
  • Set up query parameters

Step 3: Handle Response

Configure how to use the API response in your test.

  • Extract values from response (tokens, IDs, etc.)
  • Store values in variables for use in test
  • Verify response status and content
  • Handle errors and failures

Hook Configuration Options

API Request Configuration

  • URL: API endpoint to call
  • Method: HTTP method (GET, POST, PUT, PATCH, DELETE)
  • Headers: Request headers (Authorization, Content-Type, etc.)
  • Body: Request body (JSON, form data, etc.)
  • Query Parameters: URL query parameters
  • Timeout: Maximum time to wait for response

Response Handling

  • Extract Variables: Extract values from response JSON
  • Store in Context: Save values for use in test steps
  • Verify Response: Validate response status and content
  • Error Handling: Configure behavior on API failure

Execution Settings

  • Continue on Failure: Whether to continue test if hook fails
  • Retry on Failure: Automatically retry failed hooks
  • Conditional Execution: Execute hook only under certain conditions
  • Logging: Configure logging for hook execution

Practical Examples

Example 1: Authentication Hook

Before Each Hook:

  • POST /api/auth/login
  • Body: { "email": "test@example.com", "password": "test123" }
  • Extract: response.token → store as $authToken
  • Use $authToken in test headers for authenticated requests

Example 2: Test Data Setup

Before Each Hook:

  • POST /api/users (create test user)
  • Extract: response.userId → store as $testUserId
  • Use $testUserId in test to interact with created user

After Each Hook:

  • DELETE /api/users/$testUserId (cleanup)

Example 3: Environment Reset

Before Each Hook:

  • POST /api/test/reset (reset test environment)
  • Clear cache, reset feature flags, prepare clean state

Using Variables and Context

Variable Extraction

  • Extract values from API responses using JSON path
  • Store extracted values in variables
  • Use variables in test steps (selectors, text, URLs)
  • Variables are available throughout the test execution

Common Variable Patterns

  • Authentication Tokens: Store tokens for authenticated requests
  • Resource IDs: Store created resource IDs for cleanup
  • User Data: Store user information for use in tests
  • Configuration Values: Store environment-specific values

Error Handling

Hook Failure Behavior

  • Fail Test: Test fails if hook fails (default for Before Each)
  • Continue Test: Test continues even if hook fails (useful for After Each cleanup)
  • Retry: Automatically retry failed hooks
  • Log and Continue: Log error but don't fail test

Best Practices

  • Always handle authentication failures gracefully
  • Use retries for transient API failures
  • Log hook failures for debugging
  • Ensure cleanup hooks don't fail tests unnecessarily

Best Practices

  • Use Hooks for Setup/Teardown: Keep test steps focused on testing

    Separate setup from actual test logic

  • Idempotent Hooks: Design hooks to be safely repeatable

    Hooks may run multiple times or be retried

  • Clean Up Resources: Always clean up in After Each hooks

    Prevents test data pollution and conflicts

  • Use Variables Effectively: Store and reuse values from hooks

    Reduces duplication and improves maintainability

  • Handle Errors Gracefully: Configure appropriate error handling

    Prevents unnecessary test failures

  • Document Hook Purpose: Clearly document what each hook does

    Helps team understand test setup

Next Steps

Continue enhancing your tests with hooks: