JavaScript Steps

In API Hub for Test, you can enhance your API testing workflows by executing custom JavaScript code. This feature lets you interact with API-related contexts, extract critical information, and add assertions to validate the returned values.

Adding a Code-Based Step

  1. Go to the Test Definition View.

  2. Choose Add a JavaScript Step from the context menu.

    API_Hub_For_Test_Screenshot_AddJavaScript.png

The executed JavaScript can be synchronous or asynchronous. Results from these steps are not asserted by default, but you can add assertions or assign the values to variables for further use within your tests. If the returned value is a JavaScript object, you can extract and assert on specific properties of that object.

Example Use Cases

Example 1: Extracting an API Key

Extract an API key from a storage location and assign it to a variable.

return localStorage.getItem('apiKey');

Example 2: Parsing API Response Data

Execute a JavaScript step to parse JSON data from an API response.

const jsonResponse = JSON.parse('{"user": {"id": 1, "name": "John"}}');
return jsonResponse.user.name;

Example 3: Checking Response Times

Retrieve and assert on API response times for performance metrics.

const performanceData = window.performance.getEntriesByType('resource');
return performanceData.find(entry => entry.name.includes('apiEndpoint')).duration < 500;return localStorage.getItem('apiKey');

Best Practices

  • Ensure code-based steps return a single, testable value to simplify assertions.

  • Avoid adding unnecessary explicit waits; rely on API Hub's built-in synchronization features where possible.

  • Use meaningful variable names and concise comments to make your test steps easy to understand.

By leveraging the Execute JavaScript feature in API Hub for Test, you can perform advanced validations and automate complex scenarios, enhancing the robustness of your API testing workflows.

Publication date: