Overview

The Run JavaScript step allows you to execute custom JavaScript code within your test cases, providing full access to the Playwright API. This powerful feature enables complex logic, custom validations, data processing, and integration with external systems that go beyond standard test steps.

Form Fields

Field NameTypeRequiredDescription
TitleinputYesDescriptive title for the JavaScript step
Code EditoreditorYesMonaco editor for writing JavaScript code
VariablesselectNoSupatest variables to pass as function parameters
Return VariableinputNoVariable name to store the returned value
Timeout (seconds)numberNoCustom timeout for code execution (default: 10)

Form Configuration

Code Editor

The form provides a full-featured Monaco editor:
  • Syntax Highlighting: Full TypeScript/JavaScript syntax highlighting
  • IntelliSense: Code completion and error detection
  • Playwright API: Full access to Playwright methods and objects
  • Function Structure: Code must be wrapped in supatestRunCode() function
  • Theme Support: Adapts to light/dark theme preferences

Variable Integration

Input Variables

  • Variable Selection: Choose from previously created Supatest variables
  • Function Parameters: Selected variables become function parameters
  • Automatic Updates: Function signature updates automatically based on selection
  • Type Safety: Variables maintain their types throughout execution

Return Variable

  • Optional Field: Only required if you want to store the result
  • Alphanumeric Only: Variable names must be alphanumeric without spaces
  • Scope: Returned variables are available in subsequent test steps
  • Data Types: Supports strings, numbers, booleans, and objects

AI Code Generation

The step includes AI-powered code generation:
  • Prompt Interface: Natural language input for code generation
  • Context Awareness: AI considers surrounding test steps for relevant code
  • Playwright Integration: Generated code uses appropriate Playwright APIs
  • Validation: Generated code follows best practices and conventions

Examples

Basic Page Interaction

Generate a simple page interaction:
  • Title: “Check page title and return it”
  • Code:
async function supatestRunCode() {
  // Navigate to the webpage
  await page.goto('https://example.com');

  // Get the page title
  const pageTitle = await page.title();

  // Verify title contains expected text
  await expect(page).toHaveTitle(/Example/);

  // Return the title for use in other steps
  return pageTitle;
}
  • Return Variable: pageTitle

Data Processing with Variables

Process data using input variables:
  • Title: “Process user data and generate report”
  • Variables: userEmail, userName
  • Code:
async function supatestRunCode(userEmail, userName) {
  // Process the input data
  const emailDomain = userEmail.split('@')[1];
  const fullReport = `User: ${userName}, Domain: ${emailDomain}`;

  // Perform some page interactions based on data
  await page.fill('#search', emailDomain);
  await page.click('#search-button');

  // Wait for results and process them
  await page.waitForSelector('.search-results');
  const resultCount = await page.locator('.result-item').count();

  // Return processed information
  return `${fullReport}, Results: ${resultCount}`;
}
  • Return Variable: processedReport

API Integration

Integrate with external APIs:
  • Title: “Fetch data from external API and compare”
  • Variables: apiKey
  • Code:
async function supatestRunCode(apiKey) {
  // Fetch data from external API
  const response = await fetch(`https://api.example.com/data?key=${apiKey}`);
  const apiData = await response.json();

  // Get data from the page
  const pageData = await page.textContent('#data-display');

  // Compare API data with page data
  const dataMatches = apiData.value === pageData.trim();

  // Log results for debugging
  console.log('API Data:', apiData.value);
  console.log('Page Data:', pageData);
  console.log('Match:', dataMatches);

  // Verify the data matches
  if (!dataMatches) {
    throw new Error(`Data mismatch: API=${apiData.value}, Page=${pageData}`);
  }

  return apiData.value;
}
  • Return Variable: verifiedData

Best Practices

Code Structure

  • Function Wrapper: Always use supatestRunCode() as the entry point
  • Async/Await: Use async/await pattern for all asynchronous operations
  • Error Handling: Implement proper error handling for robust tests
  • Return Values: Return meaningful data that can be used in subsequent steps

Playwright Integration

  • Page Object: Use the global page object for browser interactions
  • Expect Assertions: Use Playwright’s expect for assertions and validations
  • Selectors: Use stable, unique selectors for element targeting
  • Waits: Implement proper waits for dynamic content

Performance Considerations

  • Timeout Management: Set appropriate timeouts for long-running operations
  • Resource Cleanup: Clean up resources and close unnecessary connections
  • Efficient Selectors: Use efficient CSS selectors to minimize DOM queries
  • Batch Operations: Group related operations for better performance

Variable Management

  • Descriptive Names: Use clear, descriptive names for variables
  • Type Consistency: Maintain consistent data types throughout the test
  • Scope Planning: Plan variable scope and lifecycle across test steps
  • Data Validation: Validate variable data before using in operations

Advanced Features

AI Code Generation

Leverage AI assistance for code generation:
  • Natural Language Prompts: Describe what you want in plain English
  • Context Awareness: AI considers surrounding test steps and test case context
  • Best Practices: Generated code follows Playwright and testing best practices
  • Iterative Refinement: Refine generated code with additional prompts
Example prompts:
  • “Click all buttons with class ‘submit’ and count them”
  • “Extract all product prices from the page and calculate total”
  • “Verify all form fields are properly validated”
  • “Compare data between two tables and report differences”

Variable Integration

Advanced variable usage patterns:
  • Pre-Step Variables: Use variables created in earlier steps as function parameters
  • Post-Step Variables: Create variables that subsequent steps can use
  • Complex Data Types: Handle objects, arrays, and complex data structures
  • Variable Transformation: Transform data between different formats

Custom Validations

Implement complex business logic validations:
  • Multi-Field Validation: Validate relationships between multiple form fields
  • Cross-Page Verification: Verify data consistency across different pages
  • Business Rule Checking: Implement custom business rules that standard steps can’t handle
  • Data Integrity: Ensure data integrity across complex workflows

Common Issues

Function Structure Problems

  • Problem: Code doesn’t execute because it’s not wrapped in supatestRunCode()
  • Solution: Ensure all code is inside the async function supatestRunCode() wrapper
  • Prevention: Always use the provided function template

Async/Await Issues

  • Problem: Code fails due to improper handling of asynchronous operations
  • Solution: Use await for all Playwright operations and promises
  • Best Practice: Follow async/await patterns consistently throughout the code

Variable Scope Issues

  • Problem: Variables are not accessible in subsequent steps
  • Solution: Ensure variables are returned from the function and properly named
  • Debugging: Check that the return variable name matches the field value

Timeout Problems

  • Problem: Code execution times out on slow operations
  • Solution: Increase timeout value or optimize code for better performance
  • Analysis: Identify slow operations and add appropriate waits

Selector Reliability

  • Problem: Element selectors fail or target wrong elements
  • Solution: Use more specific, stable selectors and add proper waits
  • Improvement: Prefer data-testid attributes for reliable element targeting

Performance Considerations

Execution Efficiency

  • Code Optimization: Write efficient code that minimizes unnecessary operations
  • Selector Performance: Use fast, specific selectors that don’t require extensive DOM traversal
  • Batch Operations: Group related operations to reduce overhead
  • Resource Management: Clean up resources and avoid memory leaks

Timeout Management

  • Appropriate Timeouts: Set timeouts based on expected operation duration
  • Default Values: Use system defaults for typical operations
  • Custom Timeouts: Increase timeouts for known slow operations
  • Error Handling: Handle timeout scenarios gracefully

Memory Usage

  • Variable Cleanup: Clean up large variables after use
  • Object Management: Avoid creating unnecessary objects in loops
  • Resource Release: Release resources when no longer needed
  • Garbage Collection: Write code that allows proper garbage collection
  • Extract Value - For creating variables that can be used as JavaScript parameters
  • Fill - For using JavaScript-generated values in form fields
  • Verify Value - For verifying values generated by JavaScript code
  • Navigate - Often used in conjunction with JavaScript for complex navigation
  • API Request - For combining API calls with custom JavaScript logic