Testing PatternsManaging Data & Context

Managing Data & Context

Effective data management is at the heart of dynamic and powerful API testing. ReAPI provides a flexible Context system and a powerful Template Engine to handle the entire lifecycle of your test data.

What is the Context?

The Context is a temporary, in-memory storage object that exists for the duration of a single test run. It’s the primary mechanism for passing data between the steps in your test flow.

  • Lifecycle: A new, empty context is created when a test run starts, and it is destroyed when the run finishes.
  • Accessibility: All nodes in a test flow can read from and write to the context.

The Core Pattern: Chaining Requests

The most common use case for the context is to chain API requests together, where the output of one request is the input for another.

Example: Create and then Get a User

  1. API Node: Create User

    • POST /users with a request body.
    • The API responds with the new user’s object, including an ID: { "id": "user-123", ... }.
  2. Context Operation on the API Node

    • After the response is received, an operation saves the new ID to the context.
    • Action: Set Variable
    • Variable Name: newUserId
    • Source: JSONata Expression - response.body.id
  3. API Node: Get User

    • GET /users/{{newUserId}}
    • ReAPI’s template engine automatically replaces {{newUserId}} with user-123 from the context, ensuring the correct user is requested.

Generating Dynamic Data

Hardcoding data in your tests makes them brittle. Use the template engine to generate realistic data on the fly.

  • Syntax: ${function()}
  • Use Cases:
    • Create a unique email for every test run: ${faker.internet.email()}
    • Generate random numbers for IDs or values: ${_.random(1000, 9999)}
    • Get the current timestamp: ${new Date().toISOString()}

This ensures that your tests are independent and can be run repeatedly without conflicts.

📖 Full Reference: See the Template Engine guide for a complete list of available functions.

Data-Driven Testing

The Iteration Node allows you to run a block of test steps multiple times, with a different set of data for each run.

Example: Test with Multiple User Roles

  1. Iteration Node Configuration:

    • Type: INLINE
    • Value: [ { "role": "admin", "expectedStatus": 200 }, { "role": "guest", "expectedStatus": 403 } ]
    • Context Key: userData
  2. Child API Node:

    • POST /resource with a body like:
      {
        "userRole": "{{userData.role}}"
      }
    • The node has an assertion: response.status === {{userData.expectedStatus}}.

This flow will execute the API node twice.

  • First run: It sends "role": "admin" and expects a 200 status.
  • Second run: It sends "role": "guest" and expects a 403 status.