In previous posts we have commented on extensibility as a hallmark of the k6 architecture. While there are a wide variety of official modules you can easily import into your k6 tests, it is also possible to import custom JavaScript code. In this brief post we will show you how to easily import code from your own modules. This can potentially accelerate your development efforts by reusing these modules across multiple tests, while at the same time decluttering your scripts away from repetitive lines of code.
Creating Your Own Modules
Since k6 tests are built in JavaScript, you can create extension methods to perform virtually any task and have them available to your test plan. For the sake of an example, let’s say we have a function that creates a special randomly generated identifier that we want to pass as parameter in our k6 requests:
export function createRandomID(length) {
const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
var id = '';
var counter = 0;
while (counter < length) {
id += characters.charAt(Math.floor(Math.random() * characters.length));
counter++;
}
return id;
}
This function can be called to generate a random identifier of any specified length. Note that we have decorated the method with the export
keyword. Let’s save this script and name the file “myLibrary.js”, which we will reference in the next step.
Importing Your Own Modules
Using the filesystem module pattern, you can bring your custom JavaScript code into k6 using the import
statement. With the above file “myLibrary.js” alongside your test plan, let’s add the following line of code to the top of our k6 test script:
import { createRandomID } from './myLibrary.js'
Once this reference exists, you can now call the createRandomID()
function from any place in your k6 test plan. You can use it when forming HTTP requests, filling out form fields, or any other k6 testing task.
Uploading Your Custom Module to RedLine13
To use the above pattern in your k6 test plans on RedLine13, we simply need to upload the “myLibrary.js” file as an extra file attachment:
This will place your JavaScript file alongside your test for it to be accessible when running your k6 script.
Did you know that RedLine13 offers a full-featured, time-limited free trial? Sign up now, and jumpstart your k6 testing with RedLine13 today.