Using Scripts
Resonance includes a powerful scripting engine that allows you to automate workflows with JavaScript. You can write pre-request scripts to modify requests before they're sent, and test scripts to validate responses and extract data.
Overview
Scripts in Resonance run in a secure sandboxed environment with a 10-second timeout. They have access to a rich API for manipulating requests, validating responses, and managing environment variables.
Accessing Scripts
- Open the Scripts tab in the request configuration panel
- Choose between Pre-request and Test sub-tabs
- Write your JavaScript code in the editor
- Scripts are auto-saved after 1 second of inactivity
- View script output in the Scripts tab of the response panel
Pre-request Scripts
Pre-request scripts execute before sending the request. Use them to:
- Modify request headers dynamically
- Calculate authentication signatures or timestamps
- Set or update environment variables
- Modify query parameters or path parameters
- Transform request body content
Pre-request Script Example: Add Timestamp
// Add current timestamp to headers
request.headers['X-Request-Time'] = new Date().toISOString();
// Set timestamp in environment for use in other scripts
environment.set('requestTimestamp', Date.now());
console.log('Request timestamp:', request.headers['X-Request-Time']);
Pre-request Script Example: Dynamic Authentication
// Calculate HMAC signature for authentication
const secret = environment.get('apiSecret');
const timestamp = Date.now().toString();
const payload = request.method + request.url + timestamp;
// Note: This is a simplified example
// In production, you would use proper cryptographic libraries
const signature = btoa(secret + payload);
request.headers['X-Signature'] = signature;
request.headers['X-Timestamp'] = timestamp;
console.log('Authentication headers added');
Test Scripts
Test scripts execute after receiving the response. Use them to:
- Validate response status codes and headers
- Assert response body structure and content
- Extract data from responses and save to environment variables
- Chain requests by passing data between endpoints
- Measure and validate performance metrics
Test Script Example: Response Validation
// Validate status code
expect(response.status).toBe(200);
// Parse and validate response body
const data = JSON.parse(response.body);
expect(data).toBeDefined();
expect(data.id).toBeDefined();
expect(data.name).toBeTruthy();
// Check response headers
expect(response.headers['content-type']).toContain('application/json');
console.log('All validations passed');
Test Script Example: Data Extraction
// Extract authentication token from login response
const data = JSON.parse(response.body);
if (data.token) {
// Save token to environment for use in subsequent requests
environment.set('authToken', data.token);
console.log('Token saved to environment');
} else {
console.error('No token found in response');
}
// Extract user ID for next request
if (data.userId) {
environment.set('currentUserId', data.userId);
console.log('User ID:', data.userId);
}
Test Script Example: Performance Testing
// Validate response time
expect(response.status).toBe(200);
// Check if response was fast enough
const maxResponseTime = 1000; // 1 second
if (response.timings && response.timings.total) {
expect(response.timings.total).toBeLessThan(maxResponseTime);
console.log('Response time:', response.timings.total, 'ms');
}
// Validate response size
const bodySize = response.body.length;
console.log('Response size:', bodySize, 'bytes');
Script APIs
Pre-request Script APIs
request.url
The request URL (string). Can be modified.
request.method
HTTP method (GET, POST, etc.). Can be modified.
request.headers
Request headers object. Add, modify, or remove headers.
request.body
Request body content (string). Can be modified.
request.queryParams
Query parameters object. Add, modify, or remove parameters.
request.pathParams
Path parameters object. Modify parameter values.
environment.get(name)
Get an environment variable value.
environment.set(name, value)
Set an environment variable.
environment.delete(name)
Delete an environment variable.
console.log(...args)
Log messages to the Scripts tab in response.
console.info(...args)
Log info messages with timestamp.
console.warn(...args)
Log warning messages.
console.error(...args)
Log error messages.
Test Script APIs
response.status
HTTP status code (number, e.g., 200, 404).
response.statusText
HTTP status text (e.g., "OK", "Not Found").
response.headers
Response headers object (read-only).
response.body
Response body as string. Parse with JSON.parse() if needed.
response.cookies
Response cookies array.
response.timings
Performance timing information object.
expect(value).toBe(expected)
Assert strict equality (===).
expect(value).toEqual(expected)
Assert deep equality for objects and arrays.
expect(value).toBeDefined()
Assert value is not undefined.
expect(value).toBeNull()
Assert value is null.
expect(value).toBeTruthy()
Assert value is truthy.
expect(value).toBeFalsy()
Assert value is falsy.
expect(value).toContain(item)
Assert array/string contains item/substring.
expect(value).toHaveProperty(key)
Assert object has property.
expect(value).toBeGreaterThan(n)
Assert value is greater than n.
expect(value).toBeLessThan(n)
Assert value is less than n.
Note: All test script APIs also have access to the environment and console APIs from pre-request scripts.
Common Use Cases
Request Chaining
Use scripts to chain requests together by extracting data from one response and using it in the next request:
// In the login request test script:
const loginData = JSON.parse(response.body);
environment.set('authToken', loginData.token);
// In subsequent requests' pre-request script:
const token = environment.get('authToken');
request.headers['Authorization'] = `Bearer ${token}`;
Dynamic Data Generation
// Generate random data for testing
const randomEmail = `test${Date.now()}@example.com`;
const randomId = Math.floor(Math.random() * 10000);
// Update request body
const body = JSON.parse(request.body);
body.email = randomEmail;
body.id = randomId;
request.body = JSON.stringify(body);
console.log('Generated test data:', { email: randomEmail, id: randomId });
Conditional Logic
// Use different endpoints based on environment
const env = environment.get('environmentName');
if (env === 'production') {
request.url = request.url.replace('staging', 'api');
console.log('Using production endpoint');
} else {
console.log('Using staging endpoint');
}
// Add debug header in non-production environments
if (env !== 'production') {
request.headers['X-Debug'] = 'true';
}
Best Practices
- Keep scripts simple: Complex logic should be moved to your backend or external tools
- Use console.log liberally: Debug output helps understand script execution
- Handle errors gracefully: Use try-catch blocks for operations that might fail
- Store secrets in environment variables: Never hardcode API keys or passwords in scripts
- Use descriptive variable names: Make scripts readable and maintainable
- Comment your code: Explain what complex scripts are doing
- Test incrementally: Build scripts step by step and test as you go
Security and Limitations
- Sandboxed execution: Scripts run in a secure sandbox with no access to the file system, network, or system resources
- 10-second timeout: Scripts that run longer than 10 seconds will be terminated
- No external modules: You cannot require() or import external libraries
- Limited APIs: Only the documented APIs are available (Date, Math, JSON, console, etc.)
- No async operations: Scripts execute synchronously; promises and async/await are not supported
Troubleshooting
Script not executing
- Check the Scripts tab in the response panel for error messages
- Ensure your script doesn't have syntax errors
- Verify the script is saved (auto-save happens after 1 second)
Variables not available
- Ensure you have an active environment selected
- Check that variable names are spelled correctly
- Use console.log to verify environment.get() returns expected values
Assertions failing
- Log the actual values using console.log before asserting
- Check response.body is being parsed correctly
- Verify the API is returning the expected data structure
Next Steps
- Return to Getting Started for basic usage
- Check out Features for all capabilities
- Visit the GitHub repository for updates