Installing K6 and Running a Load Test
Installation
I’m having a Mac device so I’m going to use brew to install K6. others who are having other OS, please go through this documentation.
brew install k6
Create a new folder K6 and create a file name called loadtest.js.
touch loadtest.js
add the following script to that file
import http from 'k6/http';
import { sleep } from 'k6';export default function () {
http.get('https://test.k6.io');
sleep(1);
}
will try to run the script using the following command.
k6 run loadtest.js
now you can see the result

we will do the assertion for this request. An assertion is a relay important factor that ensures that we hit the correct endpoint.
I try to fail the assertion.
import { check } from 'k6';
import http from 'k6/http';export default function () {
let res = http.get('http://test.k6.io/');
check(res, {
'is status 200': (r) => r.status === 200,
'body contains text': (r) => r.body.includes('aaa'),
});
}

we will correct and run the same test.
import { check } from 'k6';
import http from 'k6/http';export default function () {
let res = http.get('http://test.k6.io/');
check(res, {
'is status 200': (r) => r.status === 200,
'body contains text': (r) => r.body.includes('Collection of simple web-pages suitable for load testing.'),
});
}

Then we’ll try to run for 30 seconds with a user
k6 run --duration 30s loadtest.js

It’s time to add one more endpoint to the script
import { check, sleep } from 'k6';
import http from 'k6/http';export default function () {
let res = http.get('http://test.k6.io/',{tags: {'name': 'home'}});
check(res, {
'is status 200': (r) => r.status === 200,
'body contains text': (r) => r.body.includes('Collection of simple web-pages suitable for load testing.'),
});
sleep(1);
res = http.get('http://test.k6.io/news.php',{tags: {'name': 'news'}});
check(res, {
'is status 200': (r) => r.status === 200,
'body contains text': (r) => r.body.includes('In the news'),
});
}
Then we’ll try to run for 30 seconds with a user

Then we’ll try to run for 30 seconds with 10 users
k6 run --vus 10 --duration 30s loadtest.js

we can get the result as json format
k6 run --out json=my_test_result.json --vus 10 --duration 30s loadtest.js

