> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bugster.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Integrate Hooks

> Run setup and cleanup code before and after your tests

Hooks allow you to run setup and cleanup code before and after your tests. They are TypeScript/JavaScript functions that execute in your project's context, enabling you to:

* Create test data before tests run
* Clean up data after tests complete
* Pass dynamic values to your test steps

## Hook Structure

Add hooks to your test YAML file:

```yaml test.yaml theme={null}
name: My Test
task: Verify feature works correctly
expected_result: Feature should work

hooks:
  before:
    - helper: createTestUser
      args: ["John", "Doe"]
      as: userId

    - helper: createOrder
      args: ["{{userId}}", "Premium Plan"]
      as: orderId

  after:
    - helper: deleteOrder
      args: ["{{orderId}}"]

    - helper: deleteUser
      args: ["{{userId}}"]
```

## Hook Definition Fields

<ParamField body="helper" type="string" required>
  Name of the exported function to call.
</ParamField>

<ParamField body="file_path" type="string" default=".bugster/hooks.ts">
  Path to TypeScript file containing the helper function.
</ParamField>

<ParamField body="args" type="array">
  Array of arguments to pass to the function.
</ParamField>

<ParamField body="as" type="string">
  Variable name to store the result for later use.
</ParamField>

## Creating Helper Functions

### Default Location

Create a `.bugster/hooks.ts` file in your project:

```typescript .bugster/hooks.ts theme={null}
export async function createTestUser(
  firstName: string,
  lastName: string,
): Promise<string> {
  // Create user via API or database
  const response = await fetch("https://api.example.com/users", {
    method: "POST",
    body: JSON.stringify({ firstName, lastName }),
  });
  const user = await response.json();
  return user.id; // This becomes available as {{userId}}
}

export async function deleteUser(userId: string): Promise<void> {
  await fetch(`https://api.example.com/users/${userId}`, {
    method: "DELETE",
  });
}
```

### Custom File Locations

You can specify helpers from any TypeScript file in your project:

```yaml theme={null}
hooks:
  before:
    - helper: getStoreBySlug
      file_path: apps/e2e/helpers/stores.ts
      args: ["acme-electronics"]
      as: storeId

    - helper: createProductWithParams
      file_path: apps/e2e/helpers/products.ts
      args: ["{{productName}}", "{{price}}", "{{storeId}}"]
      as: productId
```

## Template Variables

Use `{{variableName}}` to reference values from previous hooks:

### Simple Access

```yaml theme={null}
- helper: createOrder
  args: ["{{userId}}", 100]
  as: orderId
```

### Nested Object Access

```yaml theme={null}
- helper: getShippingAddress
  args: ["{{customerId}}"]
  as: address

- helper: createShipment
  args: ["{{address.zipCode}}", "{{address.country}}"]
```

### Array Access

```yaml theme={null}
- helper: getAvailableCoupons
  as: coupons

- helper: applyCoupon
  args: ["{{coupons[0].code}}"]
```

## Passing Hook Data to Tests

Hook results are passed to the test as `hook_context`. Reference them in your test steps using `{{data.variableName}}`:

```yaml theme={null}
name: Create and verify product
hooks:
  before:
    - helper: generateProductName
      as: productName
task: Create a product named {{data.productName}} and verify it appears in the catalog
expected_result: Product {{data.productName}} should be visible in the products table
```

## Execution Behavior

### Before Hooks

<Info>
  Before hooks run sequentially before test execution. If any before hook fails,
  the test fails with the hook error. Results are stored in context for
  subsequent hooks.
</Info>

### After Hooks

<Info>
  After hooks run after test completion, regardless of test result. Failures are
  logged but don't affect the test result. Use after hooks for cleanup
  operations.
</Info>

## Complete Example

```yaml test.yaml theme={null}
name: Customer applies discount coupon to cart
page: /checkout

hooks:
  before:
    # Get store data
    - helper: getStoreBySlug
      file_path: apps/e2e/helpers/stores.ts
      args: ["acme-electronics"]
      as: storeId

    # Get related entities (using previous result)
    - helper: getDefaultCategoryByStoreId
      file_path: apps/e2e/helpers/categories.ts
      args: ["{{storeId}}"]
      as: category

    - helper: getPaymentMethodByStoreName
      file_path: apps/e2e/helpers/payments.ts
      args: ["acme-electronics"]
      as: paymentMethod

    # Create test data
    - helper: createProductByApi
      file_path: apps/e2e/helpers/products.ts
      args:
        [
          "{{productName}}",
          "{{category}}",
          "{{paymentMethod.id}}",
          "{{storeId}}",
        ]
      as: productId

    - helper: createCustomerWithParams
      file_path: apps/e2e/helpers/customers.ts
      args: ["{{email}}", "{{firstName}}", "{{storeId}}"]
      as: customerId

  after:
    # Clean up in reverse order
    - helper: removeCartItemsByApi
      file_path: apps/e2e/helpers/cart.ts
      args: ["{{customerId}}", "{{cartId}}"]

    - helper: deleteProductByApi
      file_path: apps/e2e/helpers/products.ts
      args: ["{{productId}}", "{{storeId}}"]

task: Verify customer can apply discount coupon to cart with existing product
steps:
  - Login as test.user@example.com with password SecurePass123!
  - Select store Acme Electronics
  - Navigate to Products section
  - Search for the created product by name
  - Click on product card to open details
  - Click Add to Cart button
  - Navigate to Checkout
  - Enter coupon code in discount field
  - Click Apply button
expected_result: Discount appears in cart summary with updated total
```

## Requirements

<Warning>
  Node.js must be installed for hooks to run. TypeScript helpers require `tsx`
  which is installed automatically via npx.
</Warning>

For path aliases in tsconfig.json, install `tsconfig-paths`:

```bash theme={null}
npm install -D tsconfig-paths
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Hooks file not found">
    Create `.bugster/hooks.ts` in your project root or specify the correct `file_path` for each hook.
  </Accordion>

  <Accordion title="Cannot find module">
    If you're using path aliases in your tsconfig.json, install `tsconfig-paths`:

    ```bash theme={null}
    npm install -D tsconfig-paths
    ```
  </Accordion>

  <Accordion title="Hook returned empty output">
    Ensure your helper function returns a value. Check that you're returning the
    correct data type.
  </Accordion>

  <Accordion title="Hook failed with error">
    Check your helper function for errors. Verify that any external APIs or databases are accessible.
  </Accordion>
</AccordionGroup>
