No results for

Powered byAlgolia

JavaScript API

Welcome to the k6 JavaScript API documentation.

Init context

The init context (aka "init code") is code in the global context that has access to a few functions not accessible during main script execution (aka "VU context" or "VU code"). For a more detailed description see Running k6.

FunctionDescription
open( filePath, [mode] )Opens a file and reads all the contents into memory.

k6

The k6 module contains k6-specific functionality.

FunctionDescription
check(val, sets, [tags])Runs one or more checks on a value and generates a pass/fail result but does not throw errors or otherwise interrupt execution upon failure.
fail([err])Throws an error, failing and aborting the current VU script iteration immediately.
group(name, fn)Runs code inside a group. Used to organize results in a test.
randomSeed(int)Set seed to get a reproducible pseudo-random number using Math.random.
sleep(t)Suspends VU execution for the specified duration.

k6/crypto

The k6/crypto module provides common hashing functionality available in the GoLang crypto package.

FunctionDescription
createHash(algorithm)Create a Hasher object, allowing the user to add data to hash multiple times, and extract hash digests along the way.
createHMAC(algorithm, secret)Create an HMAC hashing object, allowing the user to add data to hash multiple times, and extract hash digests along the way.
hmac(algorithm, secret, data, outputEncoding)Use HMAC to sign an input string.
md4(input, outputEncoding)Use MD4 to hash an input string.
md5(input, outputEncoding)Use MD5 to hash an input string.
randomBytes(int)Return an array with a number of cryptographically random bytes.
ripemd160(input, outputEncoding)Use RIPEMD-160 to hash an input string.
sha1(input, outputEncoding)Use SHA-1 to hash an input string.
sha256(input, outputEncoding)Use SHA-256 to hash an input string.
sha384(input, outputEncoding)Use SHA-384 to hash an input string.
sha512(input, outputEncoding)Use SHA-512 to hash an input string.
sha512_224(input, outputEncoding)Use SHA-512/224 to hash an input string.
sha512_256(input, outputEncoding)Use SHA-512/256 to hash an input string.
ClassDescription
HasherObject returned by crypto.createHash(). It allows adding more data to be hashed and to extract digests along the way.

k6/data

The data module, added in k6 v0.30.0, provides helpers to work with data.

Class/MethodDescription
SharedArrayread-only array like structure that shares memory between VUs

k6/encoding

The encoding module provides base64 encoding/decoding as defined by RFC4648.

FunctionDescription
b64decode(input, [encoding], [format])Base64 decode a string.
b64encode(input, [encoding])Base64 encode a string.

k6/execution

k6 v0.34.0 introduced the capability to get information about the current test execution state inside the test script. You can now read in your script the execution state during the test execution and change your script logic based on the current state.

The k6/execution module provides the test execution information with the following three properties:

import exec from 'k6/execution';
var options = {
scenarios: {
'myscenario': { // this will be the returned name
executor: 'shared-iterations',
maxDuration: '30m'
}
}
}
export default function() {
console.log(exec.scenario.name) // myscenario
}

ℹ️ Identifiers

All unique identifiers are sequentially generated starting from a base of zero (iterations) or one (VU IDs). In distributed/cloud test runs, the test-wide iteration numbers and VU identifiers are still going to be unique across instances, though there might be gaps in the sequences when, for example, some instances execute faster iterations than others or allocate more VUs mid-test.

scenario

FieldTypeDescription
namestringThe assigned name of the running scenario.
executorstringThe name of the running Executor type.
startTimeintegerThe Unix timestamp in milliseconds when the scenario started.
progressfloatPercentage in a 0 to 1 interval of the scenario progress.
iterationInInstanceintegerThe unique and zero-based sequential number of the current iteration in the scenario, across the current instance.
iterationInTestintegerThe unique and zero-based sequential number of the current iteration in the scenario, across the entire test. It is unique in all k6 execution modes - in local, cloud and distributed/segmented test runs. However, while every instance will get non-overlapping index values in cloud/distributed tests, they might iterate over them at different speeds, so the values won't be sequential across them.

instance

FieldTypeDescription
iterationsInterruptedintegerThe number of prematurely interrupted iterations in the current instance.
iterationsCompletedintegerThe number of completed iterations in the current instance.
vusActiveintegerThe number of active VUs.
vusInitializedintegerThe number of currently initialized VUs.
currentTestRunDurationfloatThe time passed from the start of the current test run in milliseconds.

vu

FieldTypeDescription
iterationInInstanceintegerThe identifier of the iteration in the current instance.
iterationInScenariointegerThe identifier of the iteration in the current scenario.
idInInstanceintegerThe identifier of the VU across the instance.
idInTestintegerThe globally unique (across the whole test run) identifier of the VU.

Examples and use cases

Get unique data once A common use case is getting a unique and incremental index for accessing a dataset's item only once per test.

The scenario.iterationInTest field can be used for this case. Let's show an example:

import exec from "k6/execution";
import { SharedArray } from "k6/data";
var items = 10;
var data = new SharedArray("mydata", function() {
var arr = new Array(items);
for (var i = 0; i < items; i++) {
arr[i] = {"foo": "item" + i, "bar": "12345678"}
}
return arr;
});
export const options = {
scenarios: {
"use-all-the-data": {
executor: "shared-iterations",
vus: 3,
iterations: data.length, // here you can also multiply so it goes through it multiple times
maxDuration: "1h" // this will need to be big enough so that all the iterations can happen if that is what is wanted
}
}
}
export default function() {
var item = data[exec.scenario.iterationInTest];
console.log('my item:', item)
}

Timing operations The startTime property from the scenario object can be used to time operations.

import exec from 'k6/execution';
export default function() {
// do some long operations
...
console.log("step1 took:", new Date() - new Date(exec.scenario.startTime))
// some more long operations
...
console.log("step2 took:", new Date() - new Date(exec.scenario.startTime))
}

Script naming The name property can be used for executing the logic based on which script is currently running.

import exec from 'k6/execution';
var options = {
scenarios: {
'the-first': {
...
},
'the-second': {
...
}
}
};
export default function() {
if (exec.scenario.name == "the-first") {
// do some logic during this scenario
} else {
// do some other logic in the others
}
}

k6/html

The k6/html module contains functionality for HTML parsing.

FunctionDescription
parseHTML(src)Parse an HTML string and populate a Selection object.
ClassDescription
ElementAn HTML DOM element as returned by the Selection API.
SelectionA jQuery-like API for accessing HTML DOM elements.

k6/http

The k6/http module contains functionality for performing HTTP transactions.

FunctionDescription
batch( requests )Issue multiple HTTP requests in parallel (like e.g. browsers tend to do).
cookieJar()Get active HTTP Cookie jar.
del( url, [body], [params] )Issue an HTTP DELETE request.
file( data, [filename], [contentType] )Create a file object that is used for building multi-part requests.
get( url, [params] )Issue an HTTP GET request.
options( url, [body], [params] )Issue an HTTP OPTIONS request.
patch( url, [body], [params] )Issue an HTTP PATCH request.
post( url, [body], [params] )Issue an HTTP POST request.
put( url, [body], [params] )Issue an HTTP PUT request.
request( method, url, [body], [params] )Issue any type of HTTP request.
setResponseCallback(expectedStatuses)Sets a response callback to mark responses as expected.
expectedStatuses( statusCodes )Create a callback for setResponseCallback that checks status codes.
ClassDescription
CookieJarUsed for storing cookies, set by the server and/or added by the client.
FileDataUsed for wrapping data representing a file when doing multipart requests (file uploads).
ParamsUsed for setting various HTTP request-specific parameters such as headers, cookies, etc.
ResponseReturned by the http.* methods that generate HTTP requests.

k6/metrics

The metrics module provides functionality to create custom metrics of various types. All metrics (both the built-in metrics and the custom ones) have a type.

All values added to a custom metric can optionally be tagged which can be useful when analysing the test results.

Metric typeDescription
CounterA metric that cumulatively sums added values.
GaugeA metric that stores the min, max and last values added to it.
RateA metric that tracks the percentage of added values that are non-zero.
TrendA metric that allows for calculating statistics on the added values (min, max, average and percentiles).

k6/net/grpc

The k6/net/grpc module, added in k6 v0.29.0, provides a gRPC client for Remote Procedure Calls (RPC) over HTTP/2.

warning!

The k6 gRPC API is currently considered in beta and is subject to change. Future k6 versions might have slight differences in the method and type signatures described in this documentation.

Class/MethodDescription
ClientgRPC client used for making RPC calls to a gRPC Server.
Client.load(importPaths, ...protoFiles)Loads and parses the given protocol buffer definitions to be made available for RPC requests.
Client.connect(address [,params])Connects to a given gRPC service.
Client.invoke(url, request [,params])Makes an unary RPC for the given service/method and returns a Response.
Client.close()Close the connection to the gRPC service.
ParamsRPC Request specific options.
ResponseReturned by RPC requests.
ConstantsDefine constants to distinguish between gRPC Response statuses.

Example

grpc-test.js
import grpc from 'k6/net/grpc';
import { check, sleep } from 'k6';
const client = new grpc.Client();
client.load(['definitions'], 'hello.proto');
export default () => {
client.connect('grpcb.in:9001', {
// plaintext: false
});
const data = { greeting: 'Bert' };
const response = client.invoke('hello.HelloService/SayHello', data);
check(response, {
'status is OK': (r) => r && r.status === grpc.StatusOK,
});
console.log(JSON.stringify(response.message));
client.close();
sleep(1);
};

k6/ws

The ws module provides a WebSocket client implementing the WebSocket protocol.

FunctionDescription
connect( url, params, callback )Create a WebSocket connection, and provides a Socket client to interact with the service. The method blocks the test finalization until the connection is closed.
Class/MethodDescription
SocketWebSocket client used to interact with a WS connection.
Socket.close()Close the WebSocket connection.
Socket.on(event, callback)Set up an event listener on the connection for any of the following events:
- open
- binaryMessage
- message
- ping
- pong
- close
- error.
Socket.ping()Send a ping.
Socket.send(data)Send string data.
Socket.sendBinary(data)Send binary data.
Socket.setInterval(callback, interval)Call a function repeatedly at certain intervals, while the connection is open.
Socket.setTimeout(callback, period)Call a function with a delay, if the connection is open.

jslib

The jslib.k6.io is a collection of external JavaScript libraries that can be directly imported in k6 scripts.

LibraryDescription
utilsSmall utility functions useful in every day load testing
expectMicro-framework for writing tests in a style of Jest or ava.
httpxWrapper around the http that simplifies session handling
-Documentation for other libraries will be added shortly.

Example

import { check, sleep } from "k6";
import jsonpath from "https://jslib.k6.io/jsonpath/1.0.2/index.js"
import { randomIntBetween,
randomItem,
uuidv4 } from "https://jslib.k6.io/k6-utils/1.1.0/index.js";
const testData = {
user: {
name: "Batman"
}
};
export default function() {
check(testData, {
"JSON path works": () => jsonpath.value(testData, 'user.name') === "Batman"
});
console.log(uuidv4());
console.log(randomItem([1,2,3,4]));
sleep(randomIntBetween(1,5)); // sleep between 1 and 5 seconds
}

The complete list of supported libraries can be viewed on jslib.k6.io.

Versioning

https://jslib.k6.io/library-name/version/index.js

Libraries hosted on jslib have versions. For example "httpx.js" library currently has v0.0.1, v0.0.2 and v0.0.3.

We recommend that you use the last version available at the time of writing your k6 scripts. Older versions will continue to be hosted on jslib, so you don't have to worry about your scripts breaking.

This documentation is for the last version of these libraries. If the examples documented here don't work, please check that you are using the latest version.

If you don't want to depend on jslib or want to make modifications to the code, you can download the libraries and use them locally.

Error Codes

Error codes are unique numbers that can be used to identify and handle different application and network errors more easily. For the moment, these error codes are applicable only for errors that happen during HTTP requests, but they will be reused and extended to support other protocols in future k6 releases.

When an error occurs, its code is determined and returned as both the error_code field of the http.Response object, and also attached as the error_code tag to any metrics associated with that request. Additionally, for more details, the error metric tag and http.Response field will still contain the actual string error message.

Error codes for different errors are as distinct as possible, but for easier handling and grouping, codes in different error categories are also grouped in broad ranges. The current error code ranges are:

  • 1000-1099 - General errors
  • 1100-1199 - DNS errors
  • 1200-1299 - TCP errors
  • 1300-1399 - TLS errors
  • 1400-1499 - HTTP 4xx errors
  • 1500-1599 - HTTP 5xx errors
  • 1600-1699 - HTTP/2 specific errors

The following specific error codes are currently defined:

  • 1000: A generic error that isn't any of the ones listed below.
  • 1010: A non-TCP network error - this is a place holder there is no error currently known to trigger it.
  • 1020: An invalid URL was specified.
  • 1050: The HTTP request has timed out.
  • 1100: A generic DNS error that isn't any of the ones listed below.
  • 1101: No IP for the provided host was found.
  • 1110: Blacklisted IP was resolved or a connection to such was tried to be established.
  • 1111: Blacklisted hostname using The Block Hostnames option.
  • 1200: A generic TCP error that isn't any of the ones listed below.
  • 1201: A "broken pipe" on write - the other side has likely closed the connection.
  • 1202: An unknown TCP error - We got an error that we don't recognize but it is from the operating system and has errno set on it. The message in error includes the operation(write,read) and the errno, the OS, and the original message of the error.
  • 1210: General TCP dial error.
  • 1211: Dial timeout error - the timeout for the dial was reached.
  • 1212: Dial connection refused - the connection was refused by the other party on dial.
  • 1213: Dial unknown error.
  • 1220: Reset by peer - the connection was reset by the other party, most likely a server.
  • 1300: General TLS error
  • 1310: Unknown authority - the certificate issuer is unknown.
  • 1311: The certificate doesn't match the hostname.
  • 1400 to 1499: error codes that correspond to the HTTP 4xx status codes for client errors
  • 1500 to 1599: error codes that correspond to the HTTP 5xx status codes for server errors
  • 1600: A generic HTTP/2 error that isn't any of the ones listed below.
  • 1610: A general HTTP/2 GoAway error.
  • 1611 to 1629: HTTP/2 GoAway errors with the value of the specific HTTP/2 error code added to 1611.
  • 1630: A general HTTP/2 stream error.
  • 1631 to 1649: HTTP/2 stream errors with the value of the specific HTTP/2 error code added to 1631.
  • 1650: A general HTTP/2 connection error.
  • 1651 to 1669: HTTP/2 connection errors with the value of the specific HTTP/2 error code added to 1651.
  • 1701: Decompression error.