### Common Patterns - Register New User Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Example of registering a new user using random data generation utilities. ```javascript import { randomString, randomItem, uuidv4 } from 'k6-jslib-utils' import http from 'k6/http' const res = http.post('https://api.example.com/register', { first_name: randomItem(['Alice', 'Bob', 'Charlie']), email: `user_${randomString(10)}@example.com`, password: uuidv4() }) ``` -------------------------------- ### Import Examples Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/README.md Examples demonstrating how to import all utilities or specific functions from the k6-jslib-utils library. ```javascript // Import all utilities import { check, findBetween, getCurrentStageIndex, normalDistributionStages, parseDuration, randomIntBetween, randomItem, randomString, tagWithCurrentStageIndex, tagWithCurrentStageProfile, uuidv4, } from 'k6-jslib-utils' // Or import specific functions import { randomIntBetween, randomString } from 'k6-jslib-utils' import { check } from 'k6-jslib-utils' ``` -------------------------------- ### Normal Distribution Load Test Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Example of setting up a load test with a normal distribution of VUs using `normalDistributionStages`. ```javascript import { normalDistributionStages, tagWithCurrentStageIndex } from 'k6-jslib-utils' import http from 'k6/http' export const options = { scenarios: { ramp: { executor: 'ramping-vus', startVUs: 0, stages: normalDistributionStages(100, 120) // 100 VUs, 120 sec } } } export default function () { tagWithCurrentStageIndex() http.get('https://api.example.com/data') } ``` -------------------------------- ### Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/types.md An example of how to define stages for a k6 load test. ```typescript const stages: Stage[] = [ { duration: '5m', target: 50 }, { duration: '10m', target: 100 }, { duration: '5m', target: 0 } ] ``` -------------------------------- ### parseDuration() Errors Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Example of catching errors when using `parseDuration` with an unsupported unit. ```javascript try { parseDuration('5x') // Unsupported unit } catch (err) { console.error(err.message) // "x is an unsupported time unit" } ``` -------------------------------- ### Import Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Imports all 11 exported functions from the k6-jslib-utils library. ```javascript import { check, findBetween, getCurrentStageIndex, normalDistributionStages, parseDuration, randomIntBetween, randomItem, randomString, tagWithCurrentStageIndex, tagWithCurrentStageProfile, uuidv4, } from 'k6-jslib-utils' ``` -------------------------------- ### check - With Tags Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Performs checks and adds custom tags to the metrics. ```javascript check(response, { 'status is 200': (r) => r.status === 200, }, { endpoint: '/api/users', method: 'GET' }) ``` -------------------------------- ### uuidv4() Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/utils.md Demonstrates how to generate both fast (non-cryptographic) and cryptographically secure UUIDv4s. ```javascript import { uuidv4 } from 'k6-jslib-utils' // Fast, non-cryptographic UUIDs (default) const password = uuidv4() console.log(password) // e.g., "550e8400-e29b-41d4-a716-446655440000" // Cryptographically secure UUIDs (slower) const secureToken = uuidv4(true) console.log(secureToken) // e.g., "a1b2c3d4-e5f6-47a8-9b0c-1d2e3f4a5b6c" ``` -------------------------------- ### getCurrentStageIndex() Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/stages.md Shows how to get the current stage index based on wall-clock time and how to use this information to adjust behavior within a k6 test. Includes a sample k6 options configuration with stages. ```typescript export function getCurrentStageIndex(): number ``` ```javascript import { getCurrentStageIndex } from 'k6-jslib-utils' import http from 'k6/http' export const options = { scenarios: { loadTest: { executor: 'ramping-vus', startVUs: 0, stages: [ { duration: '5m', target: 50 }, { duration: '10m', target: 100 }, { duration: '5m', target: 0 } ] } } } export default function () { const stageIndex = getCurrentStageIndex() console.log(`Current stage: ${stageIndex}`) // Adjust behavior based on current stage if (stageIndex === 0) { console.log('In ramp-up phase') } else if (stageIndex === 1) { console.log('In steady load phase') } else if (stageIndex === 2) { console.log('In ramp-down phase') } http.get('https://example.com') ``` -------------------------------- ### getCurrentStageIndex Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Gets the index of the current stage in a k6 scenario. ```javascript const index = getCurrentStageIndex() // 0, 1, 2, ... console.log(`Stage: ${index}`) ``` -------------------------------- ### Example Usage of tagWithCurrentStageProfile Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/stages.md An example demonstrating how to use tagWithCurrentStageProfile within a k6 test script, including scenario configuration and making HTTP requests. ```javascript import { tagWithCurrentStageProfile } from 'k6-jslib-utils' import http from 'k6/http' export const options = { scenarios: { loadTest: { executor: 'ramping-vus', startVUs: 0, stages: [ { duration: '5m', target: 50 }, // ramp-up { duration: '10m', target: 100 }, // ramp-up { duration: '10m', target: 100 }, // steady { duration: '5m', target: 0 } // ramp-down ] } } } export default function () { // Tag this VU with its current stage profile tagWithCurrentStageProfile() // Make requests; metrics will be tagged with profile: ramp-up, steady, or ramp-down http.get('https://example.com/api/data') } // In k6 result aggregation, you can group metrics by stage_profile tag // to see separate response times for ramp-up, steady, and ramp-down phases ``` -------------------------------- ### Stage Errors Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Example of catching errors when calling `getCurrentStageIndex` in an unsupported executor. ```javascript try { getCurrentStageIndex() } catch (err) { console.error(err.message) // "only ramping-vus or ramping-arrival-rate supports stages..." } ``` -------------------------------- ### Synchronous Checks Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/check.md An example demonstrating how to use the check() function with synchronous value and checker functions, including custom tags. ```javascript import { check } from 'k6-jslib-utils' import http from 'k6/http' export default function () { const response = http.get('https://api.example.com/users/1') // Simple boolean assertions const passed = check(response, { 'status is 200': (r) => r.status === 200, 'body has id': (r) => r.body.includes('"id"'), 'response time < 500ms': (r) => r.timings.duration < 500, }, { endpoint: '/users/1', method: 'GET' }) console.log(`All checks passed: ${passed}`) ``` -------------------------------- ### parseDuration() Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/stages.md Demonstrates how to parse various duration strings into milliseconds using the parseDuration function. Includes examples for different time units and a practical use case within k6 stage configuration. ```typescript export function parseDuration(str: string): number ``` ```javascript import { parseDuration } from 'k6-jslib-utils' console.log(parseDuration('1h')) // 3600000 console.log(parseDuration('30s')) // 30000 console.log(parseDuration('1h30m45s')) // 5445000 console.log(parseDuration('5.5ms')) // 5 (truncated) console.log(parseDuration('1d')) // 86400000 console.log(parseDuration('2h30m15s')) // 9015000 // For use in k6 scenarios const stageDuration = parseDuration('5m') const stageConfig = { executor: 'ramping-vus', stages: [ { duration: '5m', target: 50 }, { duration: '10m', target: 100 }, { duration: '5m', target: 0 } ] } ``` -------------------------------- ### tagWithCurrentStageProfile Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Adds a 'stage_profile' tag ('ramp-up', 'steady', or 'ramp-down') to metrics. ```javascript // Add 'stage_profile' tag: 'ramp-up', 'steady', or 'ramp-down' tagWithCurrentStageProfile() ``` -------------------------------- ### Promise Values Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/check.md An example demonstrating how check() handles Promise values directly, automatically awaiting their resolution. ```javascript import { check } from 'k6-jslib-utils' import http from 'k6/http' async function fetchUser(id) { const res = http.get(`https://api.example.com/users/${id}`) return res } export default async function () { // check() automatically waits for the promise to resolve const passed = await check(fetchUser(123), { 'status is 200': (r) => r.status === 200, 'has email field': (r) => r.json().email !== undefined, 'name is non-empty': (r) => r.json().name.length > 0, }) if (!passed) { console.error('User fetch checks failed') } ``` -------------------------------- ### Example Usage Source: https://github.com/grafana/k6-jslib-utils/blob/master/README.md Demonstrates how to import and use various utility functions for generating random data, finding substrings, and sleeping for a random duration within a k6 test. ```javascript import { sleep } from 'k6' import http from 'k6/http' import { randomIntBetween, randomString, randomItem, uuidv4, findBetween } from './src/utils.js' export default function () { let res = http.post(`https://test-api.k6.io/user/register/`, { first_name: randomItem(['Joe', 'Jane']), // random name last_name: `Jon${randomString(1, 'aeiou')}s`, //random character from given list username: `user_${randomString(10)}@example.com`, // random email address, password: uuidv4(), // random password in form of uuid }) let username = findBetween(res.body, '"username":"', '"') // grab the username from surrounding strings sleep(randomIntBetween(1, 5)) // sleep between 1 and 5 seconds. } ``` -------------------------------- ### tagWithCurrentStageIndex Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Adds a 'stage' tag to metrics for the current VU. ```javascript // Add 'stage' tag to metrics for this VU tagWithCurrentStageIndex() ``` -------------------------------- ### Async Checks Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Demonstrates how to perform asynchronous checks on HTTP responses using the `check` utility. ```javascript import { check } from 'k6-jslib-utils' import http from 'k6/http' export default async function () { const res = http.get('https://api.example.com/users/1') await check(res, { 'status 200': (r) => r.status === 200, 'valid JSON': async (r) => { try { JSON.parse(r.body); return true } catch { return false } }, 'has email': (r) => r.json().email !== undefined, }, { scenario: 'user-fetch' }) } ``` -------------------------------- ### CheckMap Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/types.md Example of how to define a CheckMap. ```typescript const checkers: CheckMap = { 'status is 200': (r) => r.status === 200, 'body has data': (r) => r.body.includes('data'), 'response time < 1s': async (r) => r.timings.duration < 1000 } ``` -------------------------------- ### User Registration Test Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/index.md Example of using utility functions for user registration. ```javascript import { randomString, randomItem, uuidv4, findBetween } from 'k6-jslib-utils' import http from 'k6/http' export default function () { const firstName = randomItem(['Alice', 'Bob', 'Charlie']) const email = `user_${randomString(10)}@example.com` const password = uuidv4() // Fast UUID const res = http.post('https://api.example.com/register', { first_name: firstName, email: email, password: password }) const userId = findBetween(res.body, '"id":"', '"') console.log(`Registered user: ${userId}`) } ``` -------------------------------- ### Asynchronous Checks Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/check.md An example showcasing the use of check() with asynchronous checker functions that return Promises. ```javascript import { check } from 'k6-jslib-utils' import http from 'k6/http' export default async function () { const response = http.get('https://api.example.com/data') // Check can handle promise-returning functions const passed = await check(response, { 'status is 200': (r) => r.status === 200, 'valid JSON': async (r) => { try { JSON.parse(r.body) return true } catch { return false } }, 'correct structure': (r) => r.json().hasOwnProperty('items'), }, { scenario: 'data-fetch' }) console.log(`All checks passed: ${passed}`) ``` -------------------------------- ### normalDistributionStages Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/utils.md Shows how to generate k6 load testing stages using a normal distribution curve for realistic ramp patterns, and how to integrate it into k6 options. ```typescript import { normalDistributionStages } from 'k6-jslib-utils' // Generate 10-stage normal distribution, peaking at 100 VUs over 60 seconds const stages = normalDistributionStages(100, 60, 10) console.log(stages) // Output (approximate): // [ // { duration: '10s', target: 2 }, // { duration: '6.67s', target: 10 }, // { duration: '6.67s', target: 32 }, // { duration: '6.67s', target: 62 }, // { duration: '6.67s', target: 88 }, // { duration: '6.67s', target: 100 }, // { duration: '6.67s', target: 88 }, // { duration: '6.67s', target: 62 }, // { duration: '6.67s', target: 32 }, // { duration: '6.67s', target: 10 }, // { duration: '6.67s', target: 2 }, // { duration: '10s', target: 0 } // ] export const options = { scenarios: { loadTest: { executor: 'ramping-vus', startVUs: 0, stages: normalDistributionStages(100, 60), } } } ``` -------------------------------- ### check - With Promise Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Performs checks on the result of a promise. ```javascript const passed = await check(fetchData(), { 'status is 200': (r) => r.status === 200, 'has id': (r) => r.json().id !== undefined, }) ``` -------------------------------- ### randomIntBetween() Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/utils.md Shows how to generate random integers for use cases like random sleep durations or payload variations. ```javascript import { randomIntBetween } from 'k6-jslib-utils' import { sleep } from 'k6' // Generate random sleep duration between 1 and 5 seconds const duration = randomIntBetween(1, 5) sleep(duration) // Generate random HTTP request payload const retries = randomIntBetween(0, 3) const httpVersion = randomIntBetween(1, 2) ``` -------------------------------- ### randomItem Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Picks a random item from an array. ```javascript randomItem(['Alice', 'Bob', 'Charlie']) // Picks one at random randomItem([1, 2, 3, 4, 5]) ``` -------------------------------- ### Example — With Promise Checkers Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/check.md Shows how to use the check function with asynchronous operations and promise-based assertions. ```javascript import { check } from 'k6-jslib-utils' import http from 'k6/http' export default async function () { const response = http.get('https://api.example.com/search?q=test') const passed = await check(response, { 'status is 200': (r) => r.status === 200, 'has results': (r) => Array.isArray(r.json().results) && r.json().results.length > 0, 'all results valid': async (r) => { // Simulate async validation (e.g., secondary API call) const results = r.json().results return results.every(r => r.id && r.title) }, 'response completes quickly': Promise.resolve(true) // static promise }) console.log(`Check result: ${passed}`) } ``` -------------------------------- ### randomString() Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/utils.md Demonstrates generating random strings for various purposes, including email addresses, passwords, and custom character sets. ```javascript import { randomString } from 'k6-jslib-utils' // Generate random email address const username = 'user_' + randomString(10) const email = `${username}@example.com` console.log(email) // e.g., "user_abcdefghij@example.com" // Generate random password with mixed characters const password = randomString(12, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()') console.log(password) // e.g., "aB3$xY!pQm9vL" // Generate random string with vowels only const vowelString = randomString(5, 'aeiou') console.log(vowelString) // e.g., "aeioa" ``` -------------------------------- ### CheckResult Example 1 Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/types.md Example of CheckResult when all checkers are synchronous. ```typescript import { check } from 'k6-jslib-utils' // Type: boolean (all sync checkers) const result1 = check(value, { 'check1': (v) => true, 'check2': (v) => false }) // result1 is boolean ``` -------------------------------- ### parseDuration Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Parses a duration string into milliseconds. ```javascript parseDuration('1h') // 3600000 (ms) parseDuration('30s') // 30000 parseDuration('1h30m45s') // 5445000 parseDuration('2d') // 172800000 ``` -------------------------------- ### CheckResult Example 3 Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/types.md Example of CheckResult when the input value is a promise. ```typescript // Type: Promise (value is a promise) const result3 = check( Promise.resolve(value), { 'check1': (v) => true } ) // result3 is Promise ``` -------------------------------- ### Duration Configuration Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/index.md Example of configuring test durations using parseDuration. ```javascript import { parseDuration, getCurrentStageIndex } from 'k6-jslib-utils' const stageConfig = { rampUp: parseDuration('5m'), // 300000 ms steady: parseDuration('10m'), // 600000 ms rampDown: parseDuration('5m') // 300000 ms } export const options = { scenarios: { test: { executor: 'ramping-vus', startVUs: 0, stages: [ { duration: `${stageConfig.rampUp}ms`, target: 50 }, { duration: `${stageConfig.steady}ms`, target: 50 }, { duration: `${stageConfig.rampDown}ms`, target: 0 } ] } } } export default function () { const index = getCurrentStageIndex() console.log(`Stage ${index}`) } ``` -------------------------------- ### CheckResult Example 2 Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/types.md Example of CheckResult when a checker is asynchronous. ```typescript // Type: Promise (has async checker) const result2 = check(value, { 'check1': (v) => true, 'check2': async (v) => await validate(v) }) // result2 is Promise ``` -------------------------------- ### normalDistributionStages Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Generates stages for a normal distribution of VUs over a given duration. ```javascript // Generate 100 VUs over 60 seconds, normal distribution across 10 stages const stages = normalDistributionStages(100, 60, 10) export const options = { scenarios: { loadTest: { executor: 'ramping-vus', startVUs: 0, stages: stages } } } ``` -------------------------------- ### randomIntBetween Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Generates a random integer between min and max (inclusive). ```javascript randomIntBetween(1, 100) // Random integer 1–100 inclusive sleep(randomIntBetween(1, 5)) ``` -------------------------------- ### Example — Mixed Static and Dynamic Checks Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/check.md Demonstrates how to use the check function with a mix of static values and dynamic functions for assertions. ```javascript import { check } from 'k6-jslib-utils' import http from 'k6/http' export default function () { const response = http.post('https://api.example.com/register', { username: 'testuser', email: 'test@example.com' }) // Mix static values and functions check(response, { 'status is 201': (r) => r.status === 201, 'has id in response': (r) => r.json().id !== undefined, 'authentication token exists': !!response.headers['x-token'], // static boolean 'response body not empty': response.body.length > 0 // static boolean }) } ``` -------------------------------- ### findBetween Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/utils.md Demonstrates how to use the findBetween utility to extract single or multiple values from a string, including extracting email addresses from HTML. ```javascript import { findBetween } from 'k6-jslib-utils' import http from 'k6/http' const response = http.post('https://api.example.com/register', { username: 'testuser', email: 'test@example.com' }) // Extract single value from response const username = findBetween(response.body, '"username":"', '"') console.log(username) // "testuser" // Extract multiple values const jsonResponse = '{"ids": [10, 20, 30]}' const firstId = findBetween(jsonResponse, '[', ',') console.log(firstId) // "10" // Extract all email addresses from HTML const htmlBody = 'Contact: email1@test.com and email2@test.com' const emails = findBetween(htmlBody, 'email', ' and ', true) console.log(emails) // ["1@test.com", "2@test.com"] ``` -------------------------------- ### check - Synchronous Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Performs synchronous checks on a response object. ```javascript const passed = check(response, { 'status is 200': (r) => r.status === 200, 'has body': (r) => r.body.length > 0, }) ``` -------------------------------- ### Check Metric Name Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/index.md Illustrates how the check function reports metrics. ```javascript // k6 uses check: '{checkName}' tag to distinguish checkRate.add(passed ? 1 : 0, { check: 'status is 200', ...customTags }) ``` -------------------------------- ### tagWithCurrentStageIndex() Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/stages.md Illustrates how to tag the current virtual user with the stage index using tagWithCurrentStageIndex(). This is useful for filtering metrics by stage. Includes a sample k6 options configuration. ```typescript export function tagWithCurrentStageIndex(): void ``` ```javascript import { tagWithCurrentStageIndex } from 'k6-jslib-utils' import http from 'k6/http' export const options = { scenarios: { loadTest: { executor: 'ramping-vus', startVUs: 0, stages: [ { duration: '5m', target: 50 }, { duration: '10m', target: 100 }, { duration: '5m', target: 0 } ] } } } export default function () { // Tag this VU with its current stage tagWithCurrentStageIndex() // Make requests; metrics will be tagged with stage information http.get('https://example.com/api/users') http.post('https://example.com/api/login', { username: 'test' }) ``` -------------------------------- ### randomItem() Example Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/utils.md Illustrates selecting a random element from an array, useful for generating varied test data like names. ```javascript import { randomItem } from 'k6-jslib-utils' const firstNames = ['Alice', 'Bob', 'Charlie', 'Diana'] const lastNames = ['Smith', 'Johnson', 'Williams', 'Brown'] const firstName = randomItem(firstNames) const lastName = randomItem(lastNames) const username = `${firstName}_${lastName}` console.log(username) // e.g., "Bob_Williams" ``` -------------------------------- ### uuidv4 Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Generates a UUID. The optional 'secure' parameter enables cryptographically secure generation. ```javascript uuidv4() // e.g., "550e8400-e29b-41d4-a716-446655440000" (fast) uuidv4(true) // Cryptographically secure UUID (slower) ``` -------------------------------- ### Pattern 2: Graceful Fallback Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Example demonstrating a graceful fallback mechanism when `getCurrentStageIndex` fails. ```javascript import { getCurrentStageIndex } from 'k6-jslib-utils' export default function () { let stageIndex = 0 try { stageIndex = getCurrentStageIndex() } catch (err) { console.warn(`Could not determine stage: ${err.message}. Using default.`) // Continue with default value } // Use stageIndex safely console.log(`Stage: ${stageIndex}`) } ``` -------------------------------- ### check - Asynchronous Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Performs asynchronous checks on a response object, handling promises. ```javascript const passed = await check(response, { 'status is 200': (r) => r.status === 200, 'valid JSON': async (r) => { try { JSON.parse(r.body); return true } catch { return false } } }) ``` -------------------------------- ### randomString Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Generates a random string of a specified length. Optionally accepts a charset for character selection. ```javascript randomString(10) // 10 random lowercase letters (default) randomString(10, 'ABCDEF0123456789') // Hex string randomString(12, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') // Alphanumeric ``` -------------------------------- ### Preventing 'no stage' error by defining at least one stage Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Example showing the correct way to define stages to avoid the 'no stage' error. ```javascript export const options = { scenarios: { test: { executor: 'ramping-vus', startVUs: 0, stages: [ { duration: '1m', target: 50 }, // At least one stage required ] } } } ``` -------------------------------- ### findBetween Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/QUICK-START.md Extracts content between specified left and right delimiters. Can extract all matches if repeat is true. ```javascript findBetween('value', '', '') // Returns "value" findBetween(jsonStr, '"id":"', '"') // Extract JSON field // Extract all matches findBetween(htmlBody, 'email', ' and ', true) // Returns array of all matches ``` -------------------------------- ### Pattern 1: Validate Early Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Example of validating input early and throwing an error for invalid duration strings. ```javascript import { parseDuration } from 'k6-jslib-utils' function createScenario(durationStr) { if (!durationStr || durationStr.length === 0) { throw new Error('duration string is required') } try { const ms = parseDuration(durationStr) return { duration: `${ms}ms`, target: 50 } } catch (err) { console.error(`Invalid duration format: ${err.message}`) throw err } } ``` -------------------------------- ### Catching 'the current scenario {scenarioName} doesn't contain any stage' error Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Example demonstrating how to catch the error when a scenario has an empty stages array. ```javascript import { getCurrentStageIndex } from 'k6-jslib-utils' export const options = { scenarios: { test: { executor: 'ramping-vus', startVUs: 0, stages: [] // Empty! } } } export default function () { try { const index = getCurrentStageIndex() } catch (err) { console.error(err.message) // "the current scenario test doesn't contain any stage" } } ``` -------------------------------- ### Pattern 3: Strict Executor Validation Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Example enforcing strict validation for executors that require stages. ```javascript import { getCurrentStageIndex } from 'k6-jslib-utils' import exec from 'k6/execution' function requireStages() { const scenario = exec.test.options.scenarios[exec.scenario.name] if (!scenario || !scenario.stages) { throw new Error('This test requires ramping-vus or ramping-arrival-rate executor with stages') } return getCurrentStageIndex() } export default function () { const index = requireStages() console.log(`Current stage: ${index}`) } ``` -------------------------------- ### Main Entry Point: src/index.js Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/README.md Exports from the main entry point of the k6-jslib-utils library, showing functions from stages.js, utils.js, and check.ts. ```javascript export { // From stages.js parseDuration, getCurrentStageIndex, tagWithCurrentStageIndex, tagWithCurrentStageProfile, // From utils.js findBetween, normalDistributionStages, randomIntBetween, randomItem, randomString, uuidv4, // From check.ts check, } ``` -------------------------------- ### Stage-Based Load Testing Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/index.md Demonstrates setting up stage-based load testing with custom stages. ```javascript import { normalDistributionStages, tagWithCurrentStageIndex } from 'k6-jslib-utils' import http from 'k6/http' export const options = { scenarios: { loadTest: { executor: 'ramping-vus', startVUs: 0, stages: normalDistributionStages(100, 60, 10) // 100 VUs over 60s with normal distribution } } } export default function () { tagWithCurrentStageIndex() // Tag metrics with current stage http.get('https://api.example.com/data') } ``` -------------------------------- ### Entry Point: src/index.js Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/index.md Re-exports all public API from three source modules: stages.js, utils.js, and check.ts. All 11 functions are available when importing from the main entry point. ```javascript // From stages.js export { parseDuration, getCurrentStageIndex, tagWithCurrentStageIndex, tagWithCurrentStageProfile } // From utils.js export { findBetween, normalDistributionStages, randomIntBetween, randomItem, randomString, uuidv4 } // From check.ts export { check } ``` -------------------------------- ### Catching 'str is empty' error Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Demonstrates how to catch the 'str is empty' error when an empty string is passed to parseDuration(). ```javascript import { parseDuration } from 'k6-jslib-utils' try { parseDuration('') } catch (err) { console.error(err.message) // "str is empty" } ``` -------------------------------- ### Catching '{unit} time unit is provided multiple times' error Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Demonstrates how to catch the '{unit} time unit is provided multiple times' error when a time unit is repeated in parseDuration(). ```javascript import { parseDuration } from 'k6-jslib-utils' try { parseDuration('5s10s') } catch (err) { console.error(err.message) // "s time unit is provided multiple times" } ``` -------------------------------- ### Async Assertions Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/index.md Shows how to perform asynchronous assertions using the check function. ```javascript import { check } from 'k6-jslib-utils' import http from 'k6/http' export default async function () { const response = http.get('https://api.example.com/users/1') const passed = await check(response, { 'status is 200': (r) => r.status === 200, 'has valid JSON': async (r) => { try { JSON.parse(r.body) return true } catch { return false } }, 'response time < 500ms': (r) => r.timings.duration < 500 }, { endpoint: '/users/1' }) if (!passed) { console.error('Check failed') } } ``` -------------------------------- ### Catching 'only ramping-vus or ramping-arrival-rate supports stages...' error Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Demonstrates catching the error when getCurrentStageIndex() is called with an unsupported executor type. ```javascript import { getCurrentStageIndex } from 'k6-jslib-utils' export const options = { scenarios: { test: { executor: 'constant-vus', // Does not support stages! vus: 10, duration: '1m' } } } export default function () { try { const index = getCurrentStageIndex() } catch (err) { console.error(err.message) // "only ramping-vus or ramping-arrival-rate supports stages..." } } ``` -------------------------------- ### Catching '{unit} is an unsupported time unit' error Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Demonstrates how to catch the '{unit} is an unsupported time unit' error when an invalid time unit is used in parseDuration(). ```javascript import { parseDuration } from 'k6-jslib-utils' try { parseDuration('5x') } catch (err) { console.error(err.message) // "x is an unsupported time unit" } ``` -------------------------------- ### Preventing 'only ramping-vus or ramping-arrival-rate supports stages...' error Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Shows how to prevent the error by using a ramping executor when calling getCurrentStageIndex(). ```javascript export const options = { scenarios: { test: { executor: 'ramping-vus', // Supports stages startVUs: 0, stages: [ { duration: '5m', target: 50 }, { duration: '5m', target: 0 } ] } } } ``` -------------------------------- ### Preventing 'str is empty' error Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Shows how to prevent the 'str is empty' error by validating string length before calling parseDuration(). ```javascript const durationStr = // ... from user input or config if (!durationStr || durationStr.length === 0) { throw new Error('duration string is required') } const ms = parseDuration(durationStr) ``` -------------------------------- ### Catching 'the exec.test.options object doesn't contain the current scenario {scenarioName}' error Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Demonstrates how to catch the error when getCurrentStageIndex() is called without a valid scenario in k6 options. ```javascript import { getCurrentStageIndex } from 'k6-jslib-utils' try { const index = getCurrentStageIndex() } catch (err) { console.error(err.message) // "the exec.test.options object doesn't contain the current scenario myScenario" } ``` -------------------------------- ### check() Function Signature Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/check.md The TypeScript signatures for the check() function, demonstrating its support for synchronous and asynchronous values and checkers. ```typescript export function check>( value: T, checkers: C, tags?: Record ): CheckResult export function check>( value: Promise, checkers: C, tags?: Record ): Promise> ``` -------------------------------- ### Preventing 'the exec.test.options object doesn't contain the current scenario {scenarioName}' error Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/errors.md Shows how to prevent the error by ensuring a named scenario is defined in k6 options when calling getCurrentStageIndex(). ```javascript export const options = { scenarios: { loadTest: { // scenario must be defined executor: 'ramping-vus', stages: [ { duration: '5m', target: 50 }, ] } } } export default function () { // Only call within this scenario context const index = getCurrentStageIndex() } ``` -------------------------------- ### Stage Object Interface Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/types.md A k6 stage configuration object returned by `normalDistributionStages()`. ```typescript interface Stage { duration: string target: number } ``` -------------------------------- ### tagWithCurrentStageProfile Function Signature Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/stages.md The TypeScript signature for the tagWithCurrentStageProfile function. ```typescript export function tagWithCurrentStageProfile(): void ``` -------------------------------- ### Type Safety Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/api-reference/check.md Illustrates the type safety provided by TypeScript overloads for synchronous and asynchronous checks. ```typescript import { check } from 'k6-jslib-utils' // Synchronous: returns boolean const result1: boolean = check(value, { 'check1': (v) => true, 'check2': (v) => false }) // Asynchronous: returns Promise const result2: Promise = check(value, { 'check1': async (v) => true, 'check2': (v) => false }) // Promise value: returns Promise const result3: Promise = check( Promise.resolve(value), { 'check1': (v) => true } ) ``` -------------------------------- ### CheckMap Interface Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/types.md A mapping of check names (keys) to checker definitions (values). Each key becomes the name of the check in metrics and logs. ```typescript interface CheckMap { [key: string]: Checker } ``` -------------------------------- ### SyncCheckMap Interface Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/types.md A specialized CheckMap with no async functions or promises. Used internally for type inference: if all checkers are synchronous, the return type is `boolean`; if any checker is async, the return type is `Promise`. ```typescript interface SyncCheckMap { [key: string]: ((value: any) => CheckValue) | CheckValue } ``` -------------------------------- ### Generic Type Parameters for check() Source: https://github.com/grafana/k6-jslib-utils/blob/master/_autodocs/index.md The `check()` function utilizes two generic parameters, `T` for the value type and `C` for the CheckMap, defining the return type as `CheckResult`. ```typescript check>( value: T | Promise, checkers: C, tags?: Record ): CheckResult ```