k6 — Load Testing Your API
Advertisement
k6 is for load testing. Write tests in JavaScript, run at scale, analyze results.
Setup
# Install k6
brew install k6 # macOS
# Or Docker
docker run -i grafana/k6 run - < script.js
Basic Test
import http from "k6/http";
import { check, sleep } from "k6";
export const options = {
vus: 10, // Virtual users
duration: "30s", // Duration
};
export default function () {
const res = http.get("http://localhost:3000/api/users");
check(res, {
"status is 200": (r) => r.status === 200,
"response time < 200ms": (r) => r.timings.duration < 200,
});
sleep(1);
}
Ramp Up Test
export const options = {
stages: [
{ duration: "30s", target: 20 }, // Ramp up
{ duration: "1m", target: 20 }, // Stay at 20
{ duration: "20s", target: 0 }, // Ramp down
],
};
FAQ
Q: k6 vs Apache JMeter? A: k6 simpler, code-first. JMeter GUI-based.
Q: How to analyze results? A: k6 Cloud for distributed testing and dashboards.
k6 makes load testing accessible to developers.
Advertisement