Running local tests
Let's start by running a simple local script. Copy the code below, paste it into your favourite editor, and save it as "script.js":
Then run k6 using this command:
Adding more VUs
Now we'll try running a load test with more than 1 virtual user and a slightly longer duration:
Running a 30-second, 10-VU load test
k6 works with the concept of virtual users (VUs), which run scripts - they're essentially glorified, parallel while(true) loops. Scripts are written using JavaScript, as ES6 modules, which allows you to break larger tests into smaller pieces, or make reusable pieces as you like.
Scripts must contain, at the very least, a default function - this defines the entry point for your VUs, similar to the main() function in many other languages:
The init context and the default function
"Why not just run my script normally, from top to bottom", you might ask - the answer is: we do, but code inside and outside your default function can do different things.
Code inside default is called "VU code", and is run over and over for as long as the test is running. Code outside of it is called "init code", and is run only once per VU.
VU code can make HTTP requests, emit metrics, and generally do everything you'd expect a load test to do - with a few important exceptions: you can't load anything from your local filesystem, or import any other modules. This all has to be done from init-code.
Read more about the different life cycle stages of a k6 test.
Using options
If you want to avoid having to type --vus 10 and --duration 30s all the time, you can include those settings inside your JavaScript file also:
Then you just run the script without those parameters on the command line:
Stages: ramping up/down VUs
You can also have the VU level ramp up and down during the test. The options.stages property allows you to configure ramping behaviour.
This can also be accomplished with more advanced configuration using scenarios and the ramping-vus executor.
Running cloud tests
k6 supports three execution modes to run your k6 tests:
- Local: on your local machine or a CI server.
- Cloud: on cloud infrastructure managed by k6 Cloud.
- Clustered: on more than one machine managed by you. Not supported yet.
One of the goals with k6 is to support running a test in the three execution modes without making modifications to the script.
For running cloud tests from the CLI, you must first register a k6 Cloud account and then log into your account via the CLI. Then, you only have to pass your existing script to the k6 cloud command.
For detailed instructions and the different options, read more on running cloud tests from the CLI.