1. Anatomy of a script #
Init, setup, default, teardown.
First script #
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10, // utilisateurs virtuels simultanés
duration: '30s',
};
export default function () {
const res = http.get('http://localhost:8080/get');
check(res, {
'statut 200': (r) => r.status === 200,
'moins de 300 ms': (r) => r.timings.duration < 300,
});
sleep(1); // temps de réflexion de l'utilisateur
}k6 run script.jsGood practice: A check does not fail the test: it counts successes and failures. To fail a test, use thresholds.2. Realistic requests #
Data, headers, groups.
Examples #
import http from 'k6/http';
import { group } from 'k6';
export function setup() { // exécuté une fois : par exemple, obtenir un jeton
const res = http.post('http://api/login', JSON.stringify({ user: 'demo', pass: 'demo' }),
{ headers: { 'Content-Type': 'application/json' } });
return { token: res.json('token') };
}
export default function (data) {
const params = { headers: { Authorization: `Bearer ${data.token}` }, tags: { name: 'commande' } };
group('parcours achat', () => {
http.get('http://api/produits');
http.post('http://api/panier', JSON.stringify({ id: 42 }), params);
});
}Common mistake: URLs with identifiers (/produits/123) create one metric series per URL. Give them a commonnametag ({ tags: { name: 'produit' } }) to keep results readable.
3. Scenarios and executors #
Modeling the load.
VUs or rate? #
Executors decide how load is generated. Two families:
| Executor | Model | Usage |
|---|---|---|
constant-vus, ramping-vus | Closed: N users chaining iterations | Simulating user sessions |
constant-arrival-rate, ramping-arrival-rate | Open: N iterations per second, no matter what | Measuring an API at a given rate |
shared-iterations, per-vu-iterations | Fixed number of iterations | Batch jobs, functional tests |
Good to know: With a closed model, if the service slows down, each VU makes fewer requests: the load drops and hides the problem. An open model (arrival rate) keeps the rate and reveals saturation.
Several scenarios #
export const options = {
scenarios: {
navigation: {
executor: 'ramping-vus',
startVUs: 0,
stages: [
{ duration: '2m', target: 50 }, // montée
{ duration: '5m', target: 50 }, // plateau
{ duration: '1m', target: 0 }, // descente
],
exec: 'parcours',
},
api: {
executor: 'constant-arrival-rate',
rate: 200, timeUnit: '1s', // 200 requêtes par seconde
duration: '8m',
preAllocatedVUs: 50, maxVUs: 300,
exec: 'appelApi',
},
},
};
export function parcours() { /* ... */ }
export function appelApi() { /* ... */ }My progress
Sign in to track your progress and take notes. Sign in
💬 Questions about this lesson
No questions yet: be the first to ask for help or share your configuration.
Recommended Articles
Thresholds, metrics and results of a k6 test
Read the summary of a k6 test, understand the built-in metrics (http_req_duration, http_req_faile...
Load testing with Grafana k6: why, and which types of tests
Why test performance before production, the types of tests (smoke, load, stress, spike, soak, bre...
Performance testing best practices with k6
Checklist for useful load tests: objectives, realistic scenarios, environment, thresholds, observ...
Website monitoring: availability, HTTPS monitoring, certificates and performance
Set up website monitoring: availability and HTTPS checks, certificate expiry, response time, Core...
Bash scripts for administrators: writing robust scripts
Automate Linux administration with Bash: variables and quoting, conditions, loops, functions, exi...
Writing good Prometheus alerting rules (and testing them)
Design useful alerts: alert on symptoms, choose for and thresholds, severity and team labels, ann...
End-to-end CI/CD (1/5): principles and anatomy of a pipeline
Understand end-to-end CI/CD: continuous integration, continuous delivery and continuous deploymen...
k6 in continuous integration and on Kubernetes (k6-operator)
Automate performance tests: k6 in GitHub Actions and GitLab CI with blocking thresholds, distribu...
Browser testing and synthetic monitoring with k6
Test a web application in a real browser with the k6 browser module, measure Core Web Vitals, and...