Run JMeter Tests with the LoadFocus API Client
This guide explains how to use the LoadFocus API Client, both through the command-line interface (CLI) and by directly using the JavaScript library in your applications. It runs JMeter tests that already exist in your LoadFocus account, by name. You need your API key and team ID from the API Keys page. For ready-made pipeline setups, see Integrating JMeter API Client with CI/CD Pipelines.
Table of Contents
Section titled “Table of Contents”- Installation
- Configuration
- Command-Line Interface (CLI)
- JavaScript Library Usage
- Advanced Usage
- Troubleshooting
Installation
Section titled “Installation”Global Installation
Section titled “Global Installation”npm install -g @loadfocus/loadfocus-api-clientLocal Project Installation
Section titled “Local Project Installation”npm install @loadfocus/loadfocus-api-clientConfiguration
Section titled “Configuration”Before using the LoadFocus API Client, you need to configure your API credentials.
CLI Configuration
Section titled “CLI Configuration”# Set API key and team IDloadfocus-api config set --apikey YOUR_API_KEY --teamid YOUR_TEAM_ID
# Verify configurationloadfocus-api config showJavaScript Configuration
Section titled “JavaScript Configuration”const { configManager } = require('@loadfocus/loadfocus-api-client');
// Set configurationconfigManager.set({ apiKey: 'YOUR_API_KEY', teamId: 'YOUR_TEAM_ID' });
// Verify configurationconsole.log(configManager.isConfigured()); // Should print true if the API key and team ID are setCommand-Line Interface (CLI)
Section titled “Command-Line Interface (CLI)”The LoadFocus API Client provides a comprehensive CLI for interacting with the LoadFocus API.
JMeter Test Execution
Section titled “JMeter Test Execution”Execute a Test
Section titled “Execute a Test”# Execute a test by nameloadfocus-api jmeter execute --name "My JMeter Test"Run a Test and Wait for Completion
Section titled “Run a Test and Wait for Completion”# Run a test and wait for completionloadfocus-api jmeter run-test --name "My JMeter Test"
# Run a test with thresholdsloadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250"
# Run a test with custom timeout and polling interval (defaults: 1800 and 10 seconds)loadfocus-api jmeter run-test --name "My JMeter Test" --wait-timeout 1800 --poll-interval 15Test Status Monitoring
Section titled “Test Status Monitoring”# Check status of a test by name and IDloadfocus-api jmeter status --name "My JMeter Test" --id 12345
# Get a list of recent test runsloadfocus-api jmeter runsResults Retrieval
Section titled “Results Retrieval”# Get results for a specific testloadfocus-api jmeter results --name "My JMeter Test" --id 12345Working with Thresholds
Section titled “Working with Thresholds”The run-test command checks every threshold against each label (request) of the test and exits with code 1 if any threshold fails, so a CI job fails with it. If you pass no --thresholds, it uses avgresponse<=100, meaning an average response time of 100 ms or less.
# Run a test with multiple thresholdsloadfocus-api jmeter run-test --name "My JMeter Test" --thresholds "avgresponse<=200,errors==0,p95<=250,hitspersec>=10"Supported threshold operators:
<=- Less than or equal to<- Less than>=- Greater than or equal to>- Greater than==(or=) - Equal to!=- Not equal to
The metrics you can use are:
avgresponse,min,max,p95andp99: response times in millisecondserrors: number of errorshitspersec: throughput in requests per secondsamples: number of samples
A metric name that is not in this list is skipped without an error, so check the spelling.
Output Formats
Section titled “Output Formats”# Print the final result as JSON (progress lines are printed before it)loadfocus-api jmeter run-test --name "My JMeter Test" --format json
# Default pretty-printed outputloadfocus-api jmeter run-test --name "My JMeter Test"JavaScript Library Usage
Section titled “JavaScript Library Usage”The LoadFocus API Client can also be used directly as a JavaScript library in your applications.
Basic Setup
Section titled “Basic Setup”// Import the LoadFocus API Clientconst loadfocus = require('@loadfocus/loadfocus-api-client');
// Access specific componentsconst { createClient, configManager } = loadfocus;JMeter Client
Section titled “JMeter Client”// Create a JMeter clientconst jmeterClient = loadfocus.createClient('jmeter');
// Or with explicit configurationconst jmeterClient = loadfocus.createClient('jmeter', { apiKey: 'YOUR_API_KEY', teamId: 'YOUR_TEAM_ID'});Executing Tests
Section titled “Executing Tests”async function executeTest() { try { const result = await jmeterClient.execute({ testrunname: 'My JMeter Test' });
console.log('Test execution started:', result); return result.testrunid; // Return the test ID for later use } catch (error) { console.error('Error executing test:', error); }}Monitoring Test Status
Section titled “Monitoring Test Status”async function checkTestStatus(testName, testId) { try { const status = await jmeterClient.getStatus({ testrunname: testName, testrunid: testId });
console.log('Test status:', status); return status.state; // Return the current state } catch (error) { console.error('Error checking test status:', error); }}Retrieving Results
Section titled “Retrieving Results”async function getTestResults(testName, testId) { try { // Get available labels for the test const labels = await jmeterClient.getLabels({ testrunname: testName, testrunid: testId });
console.log('Test labels:', labels);
// Get results for each label const allResults = []; for (const item of labels) { const labelResults = await jmeterClient.getResults({ testrunname: testName, testrunid: testId, filter: item.label });
allResults.push({ label: item.label, results: labelResults }); }
console.log('Test results:', allResults); return allResults; } catch (error) { console.error('Error retrieving test results:', error); }}Complete Example
Section titled “Complete Example”Here's a complete example that executes a test, waits for completion, and retrieves results:
const { createClient, configManager } = require('@loadfocus/loadfocus-api-client');
// Set up configurationconfigManager.set({ apiKey: 'YOUR_API_KEY', teamId: 'YOUR_TEAM_ID' });
// Create clientconst jmeterClient = createClient('jmeter');
async function runCompleteTest() { try { // Execute the test console.log('Executing test...'); const executeResult = await jmeterClient.execute({ testrunname: 'My JMeter Test' });
const testId = executeResult.testrunid; console.log(`Test execution started with ID: ${testId}`);
// Wait for completion console.log('Waiting for test to complete...'); let completed = false; while (!completed) { const status = await jmeterClient.getStatus({ testrunname: 'My JMeter Test', testrunid: testId });
console.log(`Current state: ${status.state}`);
if (status.state === 'finished') { completed = true; } else if (['aborted', 'finished_failed_to_run', 'finished_failed_timeout'].includes(status.state)) { throw new Error(`Test ended with state: ${status.state}`); } else { // Wait before checking again await new Promise(resolve => setTimeout(resolve, 10000)); } }
// Get results console.log('Getting test results...'); const labels = await jmeterClient.getLabels({ testrunname: 'My JMeter Test', testrunid: testId });
const allResults = []; for (const item of labels) { const labelResults = await jmeterClient.getResults({ testrunname: 'My JMeter Test', testrunid: testId, filter: item.label });
allResults.push({ label: item.label, results: labelResults }); }
console.log('Test results:', JSON.stringify(allResults, null, 2)); return allResults; } catch (error) { console.error('Error running test:', error); }}
// Run the testrunCompleteTest();Advanced Usage
Section titled “Advanced Usage”Error Handling
Section titled “Error Handling”The LoadFocus API Client provides detailed error information:
try { const result = await jmeterClient.execute({ testrunname: 'My JMeter Test' });} catch (error) { if (error.status) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.error('API Error:', error.status, error.data); } else if (error.request) { // The request was made but no response was received console.error('Network Error:', error.request); } else { // Something happened in setting up the request that triggered an Error console.error('Request Error:', error.message); }}Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”-
Authentication Errors:
- Ensure your API key and team ID are correctly configured
- Check that your API key has the necessary permissions
-
Test Execution Failures:
- Verify that the test name exists in your LoadFocus account
- Check if you have reached your account's concurrent test limit
-
Timeout Issues:
- For long-running tests, increase the
--wait-timeoutparameter (default 1800 seconds)
- For long-running tests, increase the
-
Results Retrieval Problems:
- Ensure the test has completed before retrieving results
- Check if the test ID is correct
For additional help, please contact support.