The k6 module is the main module that provides core k6 functionality for load testing scripts.
Functions
Runs checks on a value and emits check metrics.
Object with check names as keys and check functions as values
Optional tags to attach to the check metrics
Returns true if all checks passed, false otherwise
import { check } from 'k6';
import http from 'k6/http';
export default function () {
const res = http.get('https://test.k6.io');
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
}
fail([message])
Throws an error and interrupts the VU execution.
import { fail } from 'k6';
export default function () {
if (someCondition) {
fail('Test failed due to condition');
}
}
group(name, fn)
Runs a function within a named group for better organization and metrics.
Function to execute within the group. Must be synchronous.
Returns the value returned by the function
import { group } from 'k6';
import http from 'k6/http';
export default function () {
group('visit homepage', function () {
http.get('https://test.k6.io');
});
group('API tests', function () {
http.get('https://test.k6.io/api/v1/users');
});
}
The group() function does not support async functions. Use synchronous functions only.
randomSeed(seed)
Sets the seed for the random generator used for this VU.
Seed value for the random number generator
import { randomSeed } from 'k6';
export default function () {
randomSeed(12345);
// Math.random() will now produce deterministic values
}
sleep(seconds)
Suspends VU execution for the specified duration.
Duration in seconds (can be fractional)
import { sleep } from 'k6';
export default function () {
// Sleep for 1.5 seconds
sleep(1.5);
}
Examples
Basic Load Test
import { check, group, sleep } from 'k6';
import http from 'k6/http';
export const options = {
vus: 10,
duration: '30s',
};
export default function () {
group('Homepage', function () {
const res = http.get('https://test.k6.io');
check(res, {
'status is 200': (r) => r.status === 200,
});
});
sleep(1);
}