Appearance
Scripts in Boomerang
Scripts are powerful tools in Boomerang that help you automate and enhance your API testing workflow. There are two types of scripts you can write: Pre-request scripts that execute before your request is sent, and Post-response scripts that run after receiving a response.
Pre-request Scripts
Pre-request scripts run immediately before your request is sent, making them perfect for request preparation and dynamic data generation. Common use cases include generating timestamps, creating unique identifiers, or setting up test data.
Working with Pre-request Scripts
Access the pre-request script editor through the SCRIPTS tab in your request window. Here's a simple example that generates a timestamp and unique ID:
javascript
// Generate current timestamp
const timestamp = new Date().toISOString();
bg.variables.set("timestamp", timestamp);
// Create a unique request ID
const requestId = `req_${Date.now()}`;
bg.variables.set("requestId", requestId);
You can then use these variables in your request headers:
X-Request-ID: {{requestId}}
X-Timestamp: {{timestamp}}
Dynamic Request Data
You can prepare your request data dynamically:
javascript
// Generate random test data
const randomUser = {
name: `User_${Math.random().toString(36).substring(7)}`,
email: `test_${Date.now()}@example.com`,
age: Math.floor(Math.random() * 50) + 18
};
// Set as variables for use in request body
bg.variables.set("userName", randomUser.name);
bg.variables.set("userEmail", randomUser.email);
bg.variables.set("userAge", randomUser.age);
Post-response Scripts
Post-response scripts execute after receiving a response, allowing you to validate responses, extract data, and set up variables for subsequent requests. Boomerang uses Chai assertions in post-response scripts, providing a powerful and expressive way to validate responses.
Response Testing
Write clear and expressive tests to validate your API responses:
javascript
// Basic status code check
bg.test("Status code is 200", () => {
bg.expect(bg.response.statusCode).to.eql(200);
});
// Validate response structure
bg.test("Response has required user fields", () => {
const body = bg.response.json();
bg.expect(body).to.have.property('id');
bg.expect(body).to.have.property('name');
bg.expect(body.email).to.match(/@.+\./);
});
Advanced Response Validation
For more complex APIs, you can perform detailed response validation:
javascript
bg.test("Order details are correct", () => {
const order = bg.response.json();
// Check order structure
bg.expect(order).to.be.an('object')
.that.has.all.keys('id', 'items', 'total', 'status');
// Validate order items exist
bg.expect(order.items).to.be.an('array')
.that.has.length.greaterThan(0);
// Verify order total
const calculatedTotal = order.items.reduce((sum, item) =>
sum + item.price * item.quantity, 0);
bg.expect(order.total).to.equal(calculatedTotal);
});
Data Extraction for Chained Requests
Extract data from responses to use in subsequent requests:
javascript
// Parse response data
const responseData = bg.response.json();
// Store authentication token for subsequent requests
if (responseData.token) {
bg.globals.set("authToken", responseData.token);
}
// Extract user ID and other relevant data
bg.globals.set("userId", responseData.userId);
bg.globals.set("lastLoginTime", responseData.loginTime);
This extracted data can be used in subsequent requests:
javascript
// In your next request URL
GET {{baseUrl}}/users/{{userId}}/details
// In headers
Authorization: Bearer {{authToken}}
// In request body
{
"userId": "{{userId}}",
"timestamp": "{{lastLoginTime}}"
}
Response Capture
When working with large API responses, it can be challenging to focus on specific data points that matter to your testing. Boomerang's Capture feature solves this by allowing you to isolate and display only the relevant parts of a response. The captured data appears in the CAPTURES tab of the Response Panel.
Boomerang provides two methods for capturing and displaying specific parts of a response:
bg.capture
- Captures and displays data in the CAPTURES tabbg.captureGroup
- Captures data that appears in the CAPTURES tab and can also be merged across multiple requests when using the Collection Runner
Both methods help you isolate and view specific parts of your response data, with bg.captureGroup
providing additional functionality for data collection during Collection Runner execution.
Basic Capture
The basic capture method using bg.capture
allows you to isolate specific response data:
javascript
const responseJson = bg.response.json();
// Capture specific fields from the response
bg.capture({
id: responseJson.id,
name: responseJson.name,
status: responseJson.status
});
Capture Groups
bg.captureGroup
works similarly to bg.capture
but adds the ability to merge data across requests when using the Collection Runner:
javascript
const responseJson = bg.response.json();
// Data appears in CAPTURES tab and is also collected for Collection Runner
bg.captureGroup('user', {
id: responseJson.id,
name: responseJson.name,
status: responseJson.status
});
You can use both methods in the same script:
javascript
const responseJson = bg.response.json();
// Basic capture
bg.capture({
id: responseJson.id,
name: responseJson.name
});
// Capture group
bg.captureGroup('user_activity', {
userId: responseJson.id,
username: responseJson.name,
lastLogin: responseJson.loginTimestamp
});
When requests containing capture groups are executed using the Collection Runner, Boomerang will merge the captured data with the same group key. The merged data can be viewed by clicking the fileStack icon on the iteration row in the Collection Runner Result window. You can also download the merged data or export it as CSV for further analysis.
The merged result will appear as an array containing all captures:
javascript
[
{
"userId": 123,
"username": "john_doe",
"lastLogin": "2024-03-21T10:30:00Z",
"__key__": "user_activity"
}
]
With these scripting capabilities, Boomerang provides a flexible and powerful way to automate your API testing workflow, validate responses, and gather important data points across your test executions.