Skip to content

Functions

Functions are reusable code components that can be called from your tests, providing powerful capabilities for complex operations and integrations.

Table of Contents

  1. Creating and Managing Functions
  2. Function Editor Features
  3. Common Use Cases
  4. Using Functions in Tests
  5. Function Testing
  6. Function Status
  7. Best Practices

Creating and Managing Functions

Functions are created and managed from the Functions sidebar menu (not from within tests):

  1. Navigate to Functions in the sidebar
  2. Click Create Function to open the function editor
  3. Define your function with:
    • Name - Unique identifier for the function
    • Description - What the function does
    • Code - The function implementation
    • Test Code - "Try it out" test to validate the function

Pre-defined Parameters

Every function receives three pre-defined parameters that are automatically passed when the function is called:

ParameterSourceDescription
pagePlaywrightThe Playwright Page object for browser interactions
requestPlaywrightThe Playwright Request object for making HTTP requests
testContextShiplightGlobal context object for passing variables within the test scope. Aliases: $, ctx

Your function signature should always start with these three parameters, followed by any custom parameters:

javascript
async function myFunction(page, testContext, request, customParam1, customParam2) {
  // Use page for browser interactions
  await page.click("#button");

  // Use request for API calls
  const response = await request.get("https://api.example.com/data");

  // Use testContext to store/retrieve variables
  testContext.myValue = "stored value";
  $.anotherValue = "also stored"; // $ is an alias for testContext
}

Function Editor Features

The function editor provides a tabbed interface for managing your functions:

Editor Tabs

The function editor includes three main tabs:

  • Overview - The main editing interface where you define your function:

    • Split-pane interface - Code editor on left, live browser view on right
    • Live browser preview - If your function operates on the page, see real-time results
    • "Try it out" testing - Write and run test code that calls your function
    • Status management - Draft or Active
  • Usage - View which of your tests are using this function

  • Settings - Configure function-specific settings and preferences, such as selecting the environment to run test code

Common Use Cases

Functions are particularly useful for:

API Integrations

javascript
// Function to fetch data from internal API
async function getOrderDetails(page, testContext, request, orderId) {
  const response = await request.get(`${testContext.apiUrl}/orders/${orderId}`, {
    headers: { Authorization: `Bearer ${testContext.apiToken}` },
  });
  const data = await response.json();

  // Store results in test context for test to access
  $.orderData = data; // $ is an alias of testContext
  testContext.orderId = data.id;
  $.orderStatus = data.status;

  // Don't return value!!!
}

Complex Operations

javascript
// Function to handle multi-step authentication
async function authenticateWithMFA(page, testContext, request, username, password) {
  await page.fill("#username", username);
  await page.fill("#password", password);
  await page.click("#login");

  // Wait for MFA prompt
  await page.waitForSelector("#mfa-code");

  // Get MFA code from API or service
  const mfaCode = await getMFACode(username);
  await page.fill("#mfa-code", mfaCode);
  await page.click("#verify");
}

Data Processing

javascript
// Function to parse and validate complex data
function processInvoiceData(page, testContext, request, rawData) {
  const parsed = JSON.parse(rawData);
  const validated = validateInvoiceSchema(parsed);

  // Store processed data in test context
  $.invoiceTotal = calculateTotal(validated.items);
  $.invoiceTax = calculateTax(validated.items);
  $.invoiceDueDate = formatDate(validated.dueDate);

  // Store complete invoice data if needed
  ctx.processedInvoice = {
    total: $.invoiceTotal,
    tax: $.invoiceTax,
    dueDate: $.invoiceDueDate,
  };
}

Using Functions in Tests

Once created, functions can be called from your tests in two ways:

Using the Function Statement (Easy)

  1. Insert a new statement in your test
  2. From the dropdown menu, switch to Function (or press Ctrl + Alt + F)
  3. Pick a function from the list
  4. Fill in the parameters

This is the recommended approach for most users.

Using a Code Block (Programmatic Way)

Create a JavaScript code block and call the function directly by name:

javascript
// Call a function and use its stored results
await getOrderDetails(page, testContext, request, $.orderId);
console.log($.orderTotal); // Access stored value

Accessing Function Results

Important: Functions cannot directly return values to tests. Instead, functions store values in the test context:

javascript
// In your function:
async function getOrderDetails(orderId) {
  // Code ...
  // Store results in test context instead of returning
  $.orderTotal = orderData.total;
  $.orderStatus = orderData.status;
  ctx.orderItems = orderData.items;
}

Function Testing

Each function includes a "Try it out" section where you can:

  • Write test code that calls your function
  • Execute the test to verify function behavior
  • See live browser results if the function interacts with pages
  • Debug and refine your function implementation

Function Status

Functions have two status levels:

  • Draft - In development, can be edited and tested
  • Active - Ready for use in tests

Best Practices

Keep Functions Focused

  • Single responsibility principle
  • Clear input/output contract
  • Proper error handling
  • Meaningful function names

Document Your Functions

  • Clear descriptions of what the function does
  • Document expected parameters
  • Include usage examples in test code
  • Note any dependencies or requirements

Test Thoroughly

  • Use the "Try it out" feature to validate
  • Test edge cases and error conditions
  • Verify browser interactions work correctly
  • Ensure functions work across environments

Released under the MIT License.