k6 Load Test Script Error Fix
In this tutorial, you'll learn about k6 load test script error fix. We cover key concepts, practical examples, and best practices.
Your k6 load test throws SyntaxError or ReferenceError — k6 uses a JavaScript runtime with limitations: no require(), no import, no DOM APIs, and no Node.js built-ins.
The Problem
// WRONG — using Node.js features that k6 doesn't support
const axios = require('axios');
const fs = require('fs');
export default function () {
const response = axios.get('https://api.example.com/users');
console.log(response.data);
}
ERRO[0000] GoError: Unexpected token 'export' in script.js at 1:1
k6 uses a Go-based JavaScript runtime (goja) that supports ES6 modules with export default but does NOT support CommonJS (require), Node.js APIs, or browser APIs.
Step-by-Step Fix
1. Use k6's HTTP module
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10,
duration: '30s',
};
export default function () {
const res = http.get('https://api.example.com/users');
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
2. Configure thresholds
export const options = {
vus: 50,
duration: '1m',
thresholds: {
http_req_duration: ['p(95)<2000'],
http_req_failed: ['rate<0.01'],
},
};
3. Handle JSON responses
export default function () {
const res = http.get('https://api.example.com/users');
const users = res.json();
users.forEach((user) => {
console.log(`User: ${user.name}`);
});
}
4. Add ramp-up stages
export const options = {
stages: [
{ duration: '2m', target: 100 },
{ duration: '5m', target: 100 },
{ duration: '2m', target: 0 },
],
};
Expected output:
✓ status is 200
✓ response time < 500ms
http_req_duration........: avg=123ms min=45ms med=98ms max=890ms
http_reqs................: 3000 100/s
vus......................: 50 min=0 max=50
Prevention Tips
- Use
importfrom k6 modules, neverrequire() - Use
http.get(),http.post()instead of axios/fetch - Use
check()for assertions instead of expect/assert libraries - Set
thresholdsin options for pass/fail criteria - Use
stagesfor gradual ramp-up instead of fixed VUs
Common Mistakes with load test error
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world K6 code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro