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.
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.

ClassDescription
HasherObject returned by crypto.createHash(). It allows adding more data to be hashed and to extract digests along the way.
FunctionDescription
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.
createHash( algorithm )Create a Hasher 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.
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.

k6/encoding

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

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

k6/html

The k6/html module contains functionality for HTML parsing.

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

k6/http

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

ClassDescription
CookieJar (k6/http)Used for storing cookies, set by the server and/or added by the client.
Response (k6/http)Returned by the http.* methods that generate HTTP requests.
FileData (k6/http)Used for wrapping data representing a file when doing multipart requests (file uploads).
Params (k6/http)Used for setting various HTTP request-specific parameters such as headers, cookies, etc.
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 GET 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.

k6/metrics

The metrics module provides functionality to create custom metrics of various types. All metrics (both the built-in ones and the custom ones) have a type. There are four different metrics types, and they are: Counter, Gauge, Rate and Trend.

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

Metric type Description
Counter A metric that cumulatively sums added values.
Gauge A metric that stores the min, max and last values added to it.
Rate A metric that tracks the percentage of added values that are non-zero.
Trend A metric that allows for calculating statistics on the added values (min, max, average and percentiles).

Example

import { Counter, Gauge, Rate, Trend } from 'k6/metrics';
import { check } from 'k6';

var myCounter = new Counter('my_counter');
var myGauge = new Gauge('my_gauge');
var myRate = new Rate('my_rate');
var myTrend = new Trend('my_trend');

export default function() {
  myCounter.add(1);
  myCounter.add(2, { tag1: 'myValue', tag2: 'myValue2' });

  myGauge.add(123);
  myGauge.add(456, { tag1: 'myValue', tag2: 'myValue2' });

  myRate.add(true);
  myRate.add(false, { tag1: 'value', tag2: 'value2' });

  myTrend.add(1);
  myTrend.add(2, { tag1: 'value', tag2: 'value2' });
}

k6/ws

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

Class Description
Socket WebSocket client used to interact with a WS connection.
Function Description
connect( url, params, callback ) Create a WebSocket connection, and provides a Socket client to interact with the service. The method returns a Response object and blocks the test finalization until the connection is closed.

WebSocket built-in metrics

k6 will automatically collect some metrics when interacting with a WebSocket service through the k6/ws API.

Metric name Type Description
ws_connecting Trend Total duration for the WebSocket connection request.
ws_session_duration Trend Duration of the WebSocket session. Time between the start of the connection and the end of the VU execution.
ws_sessions Counter Total number of started WebSocket sessions.
ws_ping Trend Duration between a ping request and its pong reception
ws_msgs_sent Counter Total number of messages sent through Socket.send(data)
ws_msgs_received Counter Total number of received messages Socket.on('message', callback).

Check out the Results output article for more information about how to process the metric information.

Example

import ws from 'k6/ws';
import { check } from 'k6';

export default function() {
  var url = 'ws://echo.websocket.org';
  var params = { tags: { my_tag: 'hello' } };

  var response = ws.connect(url, params, function(socket) {
    socket.on('open', function open() {
      console.log('connected');
      socket.send(Date.now());

      socket.setInterval(function timeout() {
        socket.ping();
        console.log('Pinging every 1sec (setInterval test)');
      }, 1000);
    });

    socket.on('ping', function() {
      console.log('PING!');
    });

    socket.on('pong', function() {
      console.log('PONG!');
    });

    socket.on('pong', function() {
      // Multiple event handlers on the same event
      console.log('OTHER PONG!');
    });

    socket.on('message', function(message) {
      console.log(`Received message: ${message}`);
    });

    socket.on('close', function() {
      console.log('disconnected');
    });

    socket.on('error', function(e) {
      if (e.error() != 'websocket: close sent') {
        console.log('An unexpected error occured: ', e.error());
      }
    });

    socket.setTimeout(function() {
      console.log('2 seconds passed, closing the socket');
      socket.close();
    }, 2000);
  });

  check(response, { 'status is 101': r => r && r.status === 101 });
}
//VU execution won't be completely finished until the connection is closed.

Error Codes

Error codes, introduced in k6 0.24.0, 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.
  • 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.
  • 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.
  • 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.