Skip to main content

Overview

The sandbox is a virtual machine where your tests run. You can execute shell commands, JavaScript, and manage applications within the sandbox environment.

Code Execution

exec()

Execute code or shell commands in the sandbox.
await testdriver.exec(language, code, timeout, silent)
Parameters:
  • language (string) - Language to execute: 'js' (JavaScript) or 'pwsh' (PowerShell)
  • code (string) - Code or command to execute
  • timeout (number) - Timeout in milliseconds
  • silent (boolean, optional) - Suppress output if true
Returns: Promise<string> - Command output

JavaScript Execution

Execute JavaScript code in the browser context (Windows sandbox only).
// Execute JavaScript in the browser
const result = await testdriver.exec('js', 'document.title', 5000);
console.log('Page title:', result);

// Manipulate the DOM
await testdriver.exec('js', `
  document.querySelector('#username').value = 'testuser';
`, 5000);

// Return data from the page
const elementText = await testdriver.exec('js', `
  document.querySelector('.message').textContent
`, 5000);

PowerShell Execution

Execute PowerShell commands in the Windows sandbox.
// Run a simple command
const output = await testdriver.exec('pwsh', 'Get-Process chrome', 5000);
console.log('Chrome processes:', output);

// Install software
await testdriver.exec('pwsh', 'npm install -g dashcam@beta', 10000);

// Start an application
await testdriver.exec('pwsh', `
  Start-Process "C:/Program Files/Google/Chrome/Application/chrome.exe" -ArgumentList "--start-maximized", "https://example.com"
`, 10000);

// File operations
await testdriver.exec('pwsh', 'New-Item -Path "C:\\test.txt" -ItemType File', 5000);

Silent Execution

Use the silent parameter to suppress output for background operations:
// Silent installation
await testdriver.exec('pwsh', 'npm install -g some-package', 10000, true);

// Start background process
await testdriver.exec('pwsh', 'Start-Process notepad', 5000, true);

Application Management

focusApplication()

Bring an application window to the foreground.
await testdriver.focusApplication(name)
Parameters:
  • name (string) - Application name (e.g., 'Google Chrome', 'Microsoft Edge', 'Notepad')
Returns: Promise<string> - Result message Example:
// Focus Chrome browser
await testdriver.focusApplication('Google Chrome');

// Focus Edge
await testdriver.focusApplication('Microsoft Edge');

// Focus Notepad
await testdriver.focusApplication('Notepad');
Call focusApplication() before interacting with UI elements to ensure the correct window is active.

Common Sandbox Operations

Installing Software

// Install npm package globally
await testdriver.exec('pwsh', 'npm install -g package-name', 30000);

// Install via Chocolatey (if available)
await testdriver.exec('pwsh', 'choco install firefox -y', 60000);

// Download and install
await testdriver.exec('pwsh', `
  Invoke-WebRequest -Uri "https://example.com/installer.exe" -OutFile "C:\\installer.exe"
  Start-Process -FilePath "C:\\installer.exe" -ArgumentList "/S" -Wait
`, 120000);

File Operations

// Create a file
await testdriver.exec('pwsh', `
  Set-Content -Path "C:\\test.txt" -Value "Hello World"
`, 5000);

// Read a file
const content = await testdriver.exec('pwsh', 'Get-Content -Path "C:\\test.txt"', 5000);

// Copy files
await testdriver.exec('pwsh', 'Copy-Item -Path "C:\\source.txt" -Destination "C:\\dest.txt"', 5000);

// Delete files
await testdriver.exec('pwsh', 'Remove-Item -Path "C:\\test.txt"', 5000);

Environment Variables

// Set environment variable
await testdriver.exec('pwsh', '$env:MY_VAR = "value"', 5000);

// Get environment variable
const value = await testdriver.exec('pwsh', '$env:MY_VAR', 5000);

// Set persistent environment variable
await testdriver.exec('pwsh', '[Environment]::SetEnvironmentVariable("MY_VAR", "value", "User")', 5000);

Network Operations

// Test connectivity
const pingResult = await testdriver.exec('pwsh', 'Test-NetConnection google.com', 10000);

// Download file
await testdriver.exec('pwsh', `
  Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "C:\\Downloads\\file.zip"
`, 30000);

// Check if port is open
const portCheck = await testdriver.exec('pwsh', 'Test-NetConnection -ComputerName localhost -Port 3000', 5000);

Process Management

// List running processes
const processes = await testdriver.exec('pwsh', 'Get-Process', 5000);

// Kill a process
await testdriver.exec('pwsh', 'Stop-Process -Name "chrome" -Force', 5000);

// Start a process and wait for it
await testdriver.exec('pwsh', 'Start-Process notepad -Wait', 30000);

// Start process with arguments
await testdriver.exec('pwsh', `
  Start-Process "chrome.exe" -ArgumentList "--incognito", "https://example.com"
`, 5000);

Browser Automation with JavaScript

DOM Manipulation

// Click an element
await testdriver.exec('js', `
  document.querySelector('#submit-button').click();
`, 5000);

// Fill a form
await testdriver.exec('js', `
  document.querySelector('#username').value = '[email protected]';
  document.querySelector('#password').value = 'secret';
  document.querySelector('#login-form').submit();
`, 5000);

// Scroll to element
await testdriver.exec('js', `
  document.querySelector('#footer').scrollIntoView();
`, 5000);

Reading Page Data

// Get page title
const title = await testdriver.exec('js', 'document.title', 5000);

// Get all links
const links = await testdriver.exec('js', `
  Array.from(document.querySelectorAll('a')).map(a => a.href).join('\\n')
`, 5000);

// Check if element exists
const exists = await testdriver.exec('js', `
  document.querySelector('.error-message') !== null
`, 5000);

// Get element text
const text = await testdriver.exec('js', `
  document.querySelector('.notification').textContent
`, 5000);

Waiting for Conditions

// Wait for element to appear (using polling)
await testdriver.exec('js', `
  await new Promise((resolve) => {
    const interval = setInterval(() => {
      if (document.querySelector('.loaded')) {
        clearInterval(interval);
        resolve();
      }
    }, 100);
  });
`, 30000);

// Wait for page load
await testdriver.exec('js', `
  if (document.readyState !== 'complete') {
    await new Promise(resolve => window.addEventListener('load', resolve));
  }
`, 10000);

Complete Example

import { beforeAll, afterAll, describe, it } from 'vitest';
import TestDriver from 'testdriverai';

describe('Sandbox Operations', () => {
  let testdriver;

  beforeAll(async () => {
    client = new TestDriver(process.env.TD_API_KEY, {
      os: 'windows',
      resolution: '1366x768'
    });
    
    await testdriver.auth();
    await testdriver.connect({ newSandbox: true });
  });

  afterAll(async () => {
    await testdriver.disconnect();
  });

  it('should install and use a tool', async () => {
    // Install a tool
    await testdriver.exec('pwsh', 'npm install -g http-server', 30000, true);
    
    // Create a simple HTML file
    await testdriver.exec('pwsh', `
      Set-Content -Path "C:\\index.html" -Value "<h1>Hello World</h1>"
    `, 5000);
    
    // Start HTTP server (background process)
    await testdriver.exec('pwsh', `
      Start-Process pwsh -ArgumentList "-Command", "http-server C:\\ -p 8080"
    `, 5000, true);
    
    // Wait for server to start
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    // Launch browser to view the page
    await testdriver.exec('pwsh', `
      Start-Process chrome -ArgumentList "http://localhost:8080"
    `, 5000);
    
    // Focus the browser
    await testdriver.focusApplication('Google Chrome');
    
    // Verify the page loaded
    const pageText = await testdriver.exec('js', 'document.body.textContent', 5000);
    expect(pageText).toContain('Hello World');
  });

  it('should manage files and processes', async () => {
    // Create test file
    await testdriver.exec('pwsh', `
      "Test content" | Out-File -FilePath "C:\\test.txt"
    `, 5000);
    
    // Open file in notepad
    await testdriver.exec('pwsh', 'Start-Process notepad C:\\test.txt', 5000);
    
    // Focus notepad
    await testdriver.focusApplication('Notepad');
    
    // Wait a moment
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // Close notepad
    await testdriver.exec('pwsh', 'Stop-Process -Name notepad -Force', 5000);
  });
});

Best Practices

Set realistic timeouts based on the operation:
// Quick operations: 5000ms
await testdriver.exec('js', 'document.title', 5000);

// Installations: 30000-60000ms
await testdriver.exec('pwsh', 'npm install -g package', 30000);

// Downloads or complex operations: 60000-120000ms
await testdriver.exec('pwsh', 'Install-Module Something', 120000);
Wrap exec calls in try-catch for better error handling:
try {
  await testdriver.exec('pwsh', 'Some-Command', 5000);
} catch (error) {
  console.error('Command failed:', error.message);
  // Fall back or retry
}
Suppress output for installation and background tasks:
// Silent install
await testdriver.exec('pwsh', 'npm install -g tool', 30000, true);

// Background process
await testdriver.exec('pwsh', 'Start-Process app', 5000, true);
Always focus the target application before UI interactions:
await testdriver.focusApplication('Google Chrome');
const button = await testdriver.find('submit button');
await button.click();
Use proper escaping for special characters:
// Use backticks for newlines in PowerShell strings
await testdriver.exec('pwsh', `
  Write-Host "Line 1\`nLine 2"
`, 5000);

// Use single quotes to avoid variable expansion
await testdriver.exec('pwsh', "Write-Host 'Text with $special chars'", 5000);