k6: Add examples and fix Option object (#45459)

* k6: Add examples and fix Options definition

* Add `simskij` as contributor

* k6: add Options test
This commit is contained in:
Pepe Cano 2020-06-16 11:30:53 +02:00 committed by GitHub
parent 37ae0cea48
commit d10c9171e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 297 additions and 32 deletions

75
types/k6/crypto.d.ts vendored
View File

@ -4,6 +4,8 @@ import { bytes } from '.';
* Generate random bytes.
* @param size - Number of bytes to generate.
* @returns Random bytes.
* @example
* crypto.randomBytes(42)
*/
export function randomBytes(size: number): bytes;
@ -15,6 +17,8 @@ export function randomBytes(size: number): bytes;
* @param data - Input data.
* @param outputEncoding - Output encoding.
* @returns Produced HMAC.
* @example
* crypto.hmac('sha256', 'mysecret', 'hello world!', 'hex')
*/
export function hmac<OE extends OutputEncoding>(
algorithm: Algorithm,
@ -29,6 +33,8 @@ export function hmac<OE extends OutputEncoding>(
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns MD4 digest.
* @example
* crypto.md4('hello world!', 'hex')
*/
export function md4<OE extends OutputEncoding>(
input: string,
@ -41,6 +47,8 @@ export function md4<OE extends OutputEncoding>(
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns MD5 digest.
* @example
* crypto.md5("hello world!", "hex")
*/
export function md5<OE extends OutputEncoding>(
input: string,
@ -53,6 +61,8 @@ export function md5<OE extends OutputEncoding>(
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-1 digest.
* @example
* crypto.sha1('hello world!', 'hex')
*/
export function sha1<OE extends OutputEncoding>(
input: string,
@ -65,6 +75,8 @@ export function sha1<OE extends OutputEncoding>(
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-256 digest.
* @example
* crypto.sha256('hello world!', 'hex')
*/
export function sha256<OE extends OutputEncoding>(
input: string,
@ -77,6 +89,8 @@ export function sha256<OE extends OutputEncoding>(
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-384 digest.
* @example
* crypto.sha384('hello world!', 'hex')
*/
export function sha384<OE extends OutputEncoding>(
input: string,
@ -89,6 +103,8 @@ export function sha384<OE extends OutputEncoding>(
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-512 digest.
* @example
* crypto.sha512('hello world!', 'hex')
*/
export function sha512<OE extends OutputEncoding>(
input: string,
@ -101,6 +117,8 @@ export function sha512<OE extends OutputEncoding>(
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-512/224 digest.
* @example
* crypto.sha512_224('hello world!', 'hex')
*/
export function sha512_224<OE extends OutputEncoding>(
input: string,
@ -113,6 +131,8 @@ export function sha512_224<OE extends OutputEncoding>(
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-512/256 digest.
* @example
* crypto.sha512_256('hello world!', 'hex')
*/
export function sha512_256<OE extends OutputEncoding>(
input: string,
@ -125,6 +145,8 @@ export function sha512_256<OE extends OutputEncoding>(
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns RIPEMD-160 digest.
* @example
* crypto.ripemd160('hello world!', 'hex')
*/
export function ripemd160<OE extends OutputEncoding>(
input: string,
@ -136,6 +158,7 @@ export function ripemd160<OE extends OutputEncoding>(
* https://k6.io/docs/javascript-api/k6-crypto/createhash-algorithm
* @param algorithm - Hash algorithm.
* @returns Hashing object.
* @example
*/
export function createHash(algorithm: Algorithm): Hasher;
@ -145,6 +168,7 @@ export function createHash(algorithm: Algorithm): Hasher;
* @param algorithm - Hash algorithm.
* @param secret - Shared secret.
* @returns HMAC hashing object.
* @example
*/
export function createHMAC(algorithm: Algorithm, secret: string): Hasher;
@ -196,14 +220,26 @@ export abstract class Hasher {
/**
* Add more data to the string we want to create a hash of.
* https://k6.io/docs/javascript-api/k6-crypto/hasher
* @param input - Data to add.
* @example
* let hasher = crypto.createHMAC('sha256', 'a secret');
* hasher.update('hello ');
* hasher.update('world!');
* console.log(hasher.digest('hex'));
*/
update(input: string): void;
/**
* Return a digest from the data added so far.
* https://k6.io/docs/javascript-api/k6-crypto/hasher
* @param outputEncoding - Output encoding.
* @returns Digest of data added so far.
* @example
* let hasher = crypto.createHMAC('sha256', 'a secret');
* hasher.update('hello ');
* hasher.update('world!');
* console.log(hasher.digest('hex'));
*/
digest<OE extends OutputEncoding>(outputEncoding: OE): Output<OE>;
}
@ -213,6 +249,15 @@ export abstract class Hasher {
* https://k6.io/docs/javascript-api/k6-crypto
*/
declare namespace crypto {
/**
* Generate random bytes.
* @param size - Number of bytes to generate.
* @returns Random bytes.
* @example
* crypto.randomBytes(42)
*/
function randomBytes(size: number): bytes;
/**
* Produce HMAC.
* https://k6.io/docs/javascript-api/k6-crypto/hmac-algorithm-secret-data-outputencoding
@ -221,6 +266,8 @@ declare namespace crypto {
* @param data - Input data.
* @param outputEncoding - Output encoding.
* @returns Produced HMAC.
* @example
* crypto.hmac('sha256', 'mysecret', 'hello world!', 'hex')
*/
function hmac<OE extends OutputEncoding>(
algorithm: Algorithm,
@ -235,6 +282,8 @@ declare namespace crypto {
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns MD4 digest.
* @example
* crypto.md4('hello world!', 'hex')
*/
function md4<OE extends OutputEncoding>(
input: string,
@ -247,6 +296,8 @@ declare namespace crypto {
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns MD5 digest.
* @example
* crypto.md5("hello world!", "hex")
*/
function md5<OE extends OutputEncoding>(
input: string,
@ -259,6 +310,8 @@ declare namespace crypto {
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-1 digest.
* @example
* crypto.sha1('hello world!', 'hex')
*/
function sha1<OE extends OutputEncoding>(
input: string,
@ -271,6 +324,8 @@ declare namespace crypto {
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-256 digest.
* @example
* crypto.sha256('hello world!', 'hex')
*/
function sha256<OE extends OutputEncoding>(
input: string,
@ -283,6 +338,8 @@ declare namespace crypto {
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-384 digest.
* @example
* crypto.sha384('hello world!', 'hex')
*/
function sha384<OE extends OutputEncoding>(
input: string,
@ -295,6 +352,8 @@ declare namespace crypto {
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-512 digest.
* @example
* crypto.sha512('hello world!', 'hex')
*/
function sha512<OE extends OutputEncoding>(
input: string,
@ -307,6 +366,8 @@ declare namespace crypto {
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-512/224 digest.
* @example
* crypto.sha512_224('hello world!', 'hex')
*/
function sha512_224<OE extends OutputEncoding>(
input: string,
@ -319,6 +380,8 @@ declare namespace crypto {
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns SHA-512/256 digest.
* @example
* crypto.sha512_256('hello world!', 'hex')
*/
function sha512_256<OE extends OutputEncoding>(
input: string,
@ -331,6 +394,8 @@ declare namespace crypto {
* @param input - Data to hash.
* @param outputEncoding - Output encoding.
* @returns RIPEMD-160 digest.
* @example
* crypto.ripemd160('hello world!', 'hex')
*/
function ripemd160<OE extends OutputEncoding>(
input: string,
@ -342,6 +407,11 @@ declare namespace crypto {
* https://k6.io/docs/javascript-api/k6-crypto/createhash-algorithm
* @param algorithm - Hash algorithm.
* @returns Hashing object.
* @example
* let hasher = crypto.createHash('sha256');
* hasher.update('hello ');
* hasher.update('world!');
* console.log(hasher.digest('hex'));
*/
function createHash(algorithm: Algorithm): Hasher;
@ -351,6 +421,11 @@ declare namespace crypto {
* @param algorithm - Hash algorithm.
* @param secret - Shared secret.
* @returns HMAC hashing object.
* @example
* let hasher = crypto.createHMAC('sha256', 'a secret');
* hasher.update('hello ');
* hasher.update('world!');
* console.log(hasher.digest('hex'));
*/
function createHMAC(algorithm: Algorithm, secret: string): Hasher;
}

View File

@ -4,6 +4,9 @@
* @param input - Base64 encoded string.
* @param encoding - Base64 variant.
* @returns Decoded string.
* @example
* encoding.b64decode(str)
* encoding.b64decode(str, 'rawstd')
*/
export function b64decode(input: string, encoding?: Base64Variant): string;
@ -13,6 +16,9 @@ export function b64decode(input: string, encoding?: Base64Variant): string;
* @param input - String to encode.
* @param encoding - Base64 variant.
* @returns Base64 encoded string.
* @example
* encoding.b64encode(str)
* encoding.b64encode(str, 'rawstd')
*/
export function b64encode(input: string, encoding?: Base64Variant): string;
@ -32,6 +38,9 @@ declare namespace encoding {
* @param input - Base64 encoded string.
* @param encoding - Base64 variant.
* @returns Decoded string.
* @example
* encoding.b64decode(str)
* encoding.b64decode(str, 'rawstd')
*/
function b64decode(input: string, encoding?: Base64Variant): string;
/**
@ -40,6 +49,9 @@ declare namespace encoding {
* @param input - Base64 encoded string.
* @param encoding - Base64 variant.
* @returns Decoded string.
* @example
* encoding.b64encode(str)
* encoding.b64encode(str, 'rawstd')
*/
function b64encode(input: string, encoding?: Base64Variant): string;
}

20
types/k6/global.d.ts vendored
View File

@ -20,6 +20,16 @@ declare global {
* https://k6.io/docs/javascript-api/init-context/open-filepath-mode
* @param filePath - Path to file.
* @returns File contents decoded as UTF-8.
* @example
* let binFile = open('/path/to/file.bin', 'b');
* export default function () {
* var data = {
* field: 'this is a standard form field',
* file: http.file(binFile, 'test.bin'),
* };
* const res = http.post('https://example.com/upload', data);
* sleep(3);
* }
*/
function open(filePath: string): string;
@ -28,6 +38,16 @@ declare global {
* https://k6.io/docs/javascript-api/init-context/open-filepath-mode
* @param filePath - Path to file.
* @returns Binary file contents.
* @example
* let binFile = open('/path/to/file.bin', 'b');
* export default function () {
* var data = {
* field: 'this is a standard form field',
* file: http.file(binFile, 'test.bin'),
* };
* const res = http.post('https://example.com/upload', data);
* sleep(3);
* }
*/
function open(filePath: string, mode: 'b'): bytes;

80
types/k6/http.d.ts vendored
View File

@ -21,6 +21,8 @@ export function del<RT extends ResponseType | undefined>(
* @param url - Request URL.
* @param params - Request parameters.
* @returns Resulting response.
* @example
* http.get('https://k6.io')
*/
export function get<RT extends ResponseType | undefined>(
url: string,
@ -62,6 +64,10 @@ export function patch<RT extends ResponseType | undefined>(
* @param body - Request body. Object form encoded.
* @param params - Request parameters.
* @returns Resulting response.
* @example
* let formData = {name: 'k6'};
* let headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
* http.post(url, formData, { headers: headers });
*/
export function post<RT extends ResponseType | undefined>(
url: string,
@ -91,6 +97,10 @@ export function put<RT extends ResponseType | undefined>(
* @param body - Request body. Object form encoded.
* @param params - Request parameters.
* @returns Resulting response.
* @example
* let formData = {name: 'k6'};
* let headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
* http.request('POST', url, formData, { headers: headers });
*/
export function request<RT extends ResponseType | undefined>(
method: string,
@ -105,6 +115,22 @@ export function request<RT extends ResponseType | undefined>(
* https://k6.io/docs/javascript-api/k6-http/batch-requests
* @param requests - Request specifications.
* @returns Resulting responses.
* @example
* let req1 = {
* method: 'GET',
* url: 'https://httpbin.org/get',
* };
* let req2 = {
* method: 'POST',
* url: 'https://httpbin.org/post',
* body: {
* hello: 'world!',
* },
* params: {
* headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
* },
* };
* let responses = http.batch([req1, req2]);
*/
export function batch<Q extends BatchRequests>(requests: Q): BatchResponses<Q>;
@ -115,6 +141,15 @@ export function batch<Q extends BatchRequests>(requests: Q): BatchResponses<Q>;
* @param filename - Filename. Included in MIME message.
* @param contentType - Content type. Included in MIME message.
* @returns File data object.
* @example
* let binFile = open('/path/to/file.bin', 'b');
*
* export default function() {
* let f = http.file(binFile, 'test.bin');
* console.log(md5(f.data, 'hex'));
* console.log(f.filename);
* console.log(f.content_type);
* }
*/
export function file(data: string | bytes, filename?: string, contentType?: string): FileData;
@ -122,6 +157,8 @@ export function file(data: string | bytes, filename?: string, contentType?: stri
* Get active cookie jar.
* https://k6.io/docs/javascript-api/k6-http/cookiejar
* @returns Active cookie jar.
* @example
* let jar = http.cookieJar();
*/
export function cookieJar(): CookieJar;
@ -449,6 +486,9 @@ export interface Response {
* https://docs.k6.io/docs/response-k6http
* @param selector - Selector expression.
* @returns Document node or selected elements.
* @example
* let res = http.get("https://stackoverflow.com");
* let doc = res.html();
*/
html(selector?: string): Selection;
@ -457,6 +497,9 @@ export interface Response {
* https://docs.k6.io/docs/response-k6http
* @param selector - GJSON expression.
* @returns Parse result if successful, `undefined` if unsuccessful.
* @example
* let res = http.get(url);
* res.json();
*/
json(selector?: string): JSONValue | undefined;
@ -687,6 +730,8 @@ declare namespace http {
* @param url - Request URL.
* @param params - Request parameters.
* @returns Resulting response.
* @example
* http.get('https://k6.io')
*/
function get<RT extends ResponseType | undefined>(
url: string,
@ -728,6 +773,10 @@ declare namespace http {
* @param body - Request body. Object form encoded.
* @param params - Request parameters.
* @returns Resulting response.
* @example
* let formData = {name: 'k6'};
* let headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
* http.post(url, formData, { headers: headers });
*/
function post<RT extends ResponseType | undefined>(
url: string,
@ -757,6 +806,10 @@ declare namespace http {
* @param body - Request body. Object form encoded.
* @param params - Request parameters.
* @returns Resulting response.
* @example
* let formData = {name: 'k6'};
* let headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
* http.request('POST', url, formData, { headers: headers });
*/
function request<RT extends ResponseType | undefined>(
method: string,
@ -771,6 +824,22 @@ declare namespace http {
* https://k6.io/docs/javascript-api/k6-http/batch-requests
* @param requests - Request specifications.
* @returns Resulting responses.
* @example
* let req1 = {
* method: 'GET',
* url: 'https://httpbin.org/get',
* };
* let req2 = {
* method: 'POST',
* url: 'https://httpbin.org/post',
* body: {
* hello: 'world!',
* },
* params: {
* headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
* },
* };
* let responses = http.batch([req1, req2]);
*/
function batch<Q extends BatchRequests>(requests: Q): BatchResponses<Q>;
@ -781,6 +850,15 @@ declare namespace http {
* @param filename - Filename. Included in MIME message.
* @param contentType - Content type. Included in MIME message.
* @returns File data object.
* @example
* let binFile = open('/path/to/file.bin', 'b');
*
* export default function() {
* let f = http.file(binFile, 'test.bin');
* console.log(md5(f.data, 'hex'));
* console.log(f.filename);
* console.log(f.content_type);
* }
*/
function file(data: string | bytes, filename?: string, contentType?: string): FileData;
@ -788,6 +866,8 @@ declare namespace http {
* Get active cookie jar.
* https://k6.io/docs/javascript-api/k6-http/cookiejar
* @returns Active cookie jar.
* @example
* let jar = http.cookieJar();
*/
function cookieJar(): CookieJar;
}

14
types/k6/index.d.ts vendored
View File

@ -4,6 +4,7 @@
// Book Moons <https://github.com/bookmoons>
// na-- <https://github.com/na-->
// Pepe Cano <https://github.com/ppcano>
// Simon Aronsson <https://github.com/simskij>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.4
@ -48,6 +49,11 @@ import './ws';
* @param sets - Tests (checks) to run on the value.
* @param tags - Extra tags to attach to metrics emitted.
* @returns `true` if all checks have succeeded, otherwise `false`.
* @example
* check(res, {
* "response code was 200": (res) => res.status == 200,
* "body size was 1234 bytes": (res) => res.body.length == 1234,
* });
*/
export function check<VT>(val: VT, sets: Checkers<VT>, tags?: object): boolean;
@ -55,6 +61,8 @@ export function check<VT>(val: VT, sets: Checkers<VT>, tags?: object): boolean;
* Immediately throw an error, aborting the current script iteration.
* https://k6.io/docs/javascript-api/k6/fail-err
* @param err - Error message that gets printed to stderr.
* @example
* fail("abort current iteration");
*/
export function fail(err?: string): never;
@ -65,6 +73,10 @@ export function fail(err?: string): never;
* @param name - Name of the group.
* @param fn - Group body. Code to be executed in the group context.
* @returns The return value of `fn`.
* @example
* group("group name", function() {
* ..
* });
*/
export function group<RT>(name: string, fn: () => RT): RT;
@ -72,6 +84,8 @@ export function group<RT>(name: string, fn: () => RT): RT;
* Suspend VU execution for the specified duration.
* https://k6.io/docs/javascript-api/k6/sleep-t
* @param t - Duration, in seconds.
* @example
* sleep(3);
*/
export function sleep(t: number): void;

View File

@ -26,6 +26,13 @@ export abstract class Metric {
/**
* Cumulative counter.
* https://k6.io/docs/javascript-api/k6-metrics/counter-k6-metrics
*
* @example
* // Create instance on init context
* const myCounter = new Counter('metricName');
* export default function() {
* myCounter.add(1);
* }
*/
export class Counter extends Metric {
protected __brand: never;

64
types/k6/options.d.ts vendored
View File

@ -11,100 +11,100 @@ import { CipherSuite } from './http';
*/
export interface Options {
/** Maximum parallel `http.batch()` connections per VU. */
batch: number;
batch?: number;
/** Maximum parallel `http.batch()` host connections per VU. */
batchPerHost: number;
batchPerHost?: number;
/** Blacklist IP ranges from being called. */
blacklistIPs: string[];
blacklistIPs?: string[];
/** Discard response bodies. */
discardResponseBodies: boolean;
discardResponseBodies?: boolean;
/** Test duration. */
duration: string;
duration?: string;
/** Third party collector configuration. */
ext: { [name: string]: CollectorOptions };
ext?: { [name: string]: CollectorOptions };
/** Static hostname mapping. */
hosts: { [name: string]: string };
hosts?: { [name: string]: string };
/** Log all HTTP requests and responses. */
httpDebug: string;
httpDebug?: string;
/** Disable TLS verification. Insecure. */
insecureSkipTLSVerify: boolean;
insecureSkipTLSVerify?: boolean;
/** Iterations to execute. */
iterations: number;
iterations?: number;
/** Persist the k6 process after test completion. */
linger: boolean;
linger?: boolean;
/** Maximum HTTP redirects to follow. */
maxRedirects: number;
maxRedirects?: number;
/** Minimum test iteration duration. */
minIterationDuration: string;
minIterationDuration?: string;
/** Disable keepalive connections. */
noConnectionReuse: boolean;
noConnectionReuse?: boolean;
/** Disable usage reports. */
noUsageReport: boolean;
noUsageReport?: boolean;
/** Disable cross-VU TCP connection reuse. */
noVUConnectionReuse: boolean;
noVUConnectionReuse?: boolean;
/** Start test in paused state. */
paused: boolean;
paused?: boolean;
/** Maximum requests per second across all VUs. */
rps: number;
rps?: number;
/** Setup function timeout. */
setupTimeout: string;
setupTimeout?: string;
/** Test stage specifications. Program of target VU stages. */
stages: Stage[];
stages?: Stage[];
/** Define stats for trend metrics. */
summaryTrendStats: string[];
summaryTrendStats?: string[];
/** Which system tags to include in collected metrics. */
systemTags: string[];
systemTags?: string[];
/** Tags to set test wide across all metrics. */
tags: { [name: string]: string };
tags?: { [name: string]: string };
/** Teardown function timeout. */
teardownTimeout: string;
teardownTimeout?: string;
/** Threshold specifications. Defines pass and fail conditions. */
thresholds: { [name: string]: Threshold[] };
thresholds?: { [name: string]: Threshold[] };
/** Throw error on failed HTTP request. */
throw: boolean;
throw?: boolean;
/** TLS client certificates. */
tlsAuth: Certificate[];
tlsAuth?: Certificate[];
/** Allowed TLS cipher suites. */
tlsCipherSuites: CipherSuite[];
tlsCipherSuites?: CipherSuite[];
/** Allowed TLS version. Use `http.SSL_*` `http.TLS_*` constants. */
tlsVersion: string | { min: string; max: string };
tlsVersion?: string | { min: string; max: string };
/** User agent string to include in HTTP requests. */
userAgent: string;
userAgent?: string;
/** Number of VUs to run concurrently. */
vus: number;
vus?: number;
/** Maximum VUs. Preallocates VUs to enable faster scaling. */
vusMax: number;
vusMax?: number;
}
/**

6
types/k6/test/options.ts Normal file
View File

@ -0,0 +1,6 @@
import { Options } from 'k6/options';
const options: Options = {
vus: 10,
duration: '10s',
};

View File

@ -27,6 +27,7 @@
"test/http.ts",
"test/index.ts",
"test/metrics.ts",
"test/options.ts",
"test/ws.ts"
]
}

50
types/k6/ws.d.ts vendored
View File

@ -4,6 +4,13 @@
* @param url - Request URL.
* @param callback - Logic to execute with socket.
* @returns HTTP response to connection request.
* @example
* let res = ws.connect(url, function(socket) {
* socket.on('open', function() {
* console.log('WebSocket connection established!');
* socket.close();
* });
* });
*/
export function connect(url: string, callback: Executor): Response;
@ -14,6 +21,13 @@ export function connect(url: string, callback: Executor): Response;
* @param params - Request parameters.
* @param callback - Logic to execute with socket.
* @returns HTTP response to connection request.
* @example
* let res = ws.connect(url, { param1: true }, function(socket) {
* socket.on('open', function() {
* console.log('WebSocket connection established!');
* socket.close();
* });
* });
*/
export function connect(url: string, params: Params | null, callback: Executor): Response;
@ -76,6 +90,8 @@ export abstract class Socket {
* Close connection.
* https://k6.io/docs/javascript-api/k6-ws/socket/socket-close
* @param code - WebSocket status code.
* @example
* socket.close();
*/
close(code?: number): void;
@ -84,12 +100,21 @@ export abstract class Socket {
* https://k6.io/docs/javascript-api/k6-ws/socket/socket-on-event-callback
* @param event - Event type.
* @param handler - Event handler.
* @example
* socket.on('message', function(message) {
* console.log(`Received message: ${message}`);
* });
* socket.on('close', function() {
* console.log('disconnected');
* });
*/
on<ET extends EventType>(event: ET, handler: EventHandler<ET>): void;
/**
* Send ping.
* https://k6.io/docs/javascript-api/k6-ws/socket/socket-ping
* @example
* socket.ping();
*/
ping(): void;
@ -97,6 +122,8 @@ export abstract class Socket {
* Send data.
* https://k6.io/docs/javascript-api/k6-ws/socket/socket-send-data
* @param data - Data to send.
* @example
* socket.send(JSON.stringify({ data: 'hola' }));
*/
send(data: string): void;
@ -105,6 +132,11 @@ export abstract class Socket {
* https://k6.io/docs/javascript-api/k6-ws/socket/socket-setinterval-callback-interval
* @param handler - The function to call every `interval` milliseconds.
* @param interval - Milliseconds between two calls to `callback`.
* @example
* socket.setInterval(function timeout() {
* socket.ping();
* console.log('Pinging every 1sec (setInterval test)');
* }, 1000);
*/
setInterval(handler: TimerHandler, interval: number): void;
@ -114,6 +146,10 @@ export abstract class Socket {
* https://k6.io/docs/javascript-api/k6-ws/socket/socket-settimeout-callback-delay
* @param handler - The function to call when `delay` has expired.
* @param delay - Delay in milliseconds.
* @example
* socket.setTimeout(function timeout() {
* console.log('Call after 1second');
* }, 1000);
*/
setTimeout(handler: TimerHandler, delay: number): void;
}
@ -219,6 +255,13 @@ declare namespace ws {
* @param url - Request URL.
* @param callback - Logic to execute with socket.
* @returns HTTP response to connection request.
* @example
* let res = ws.connect(url, function(socket) {
* socket.on('open', function() {
* console.log('WebSocket connection established!');
* socket.close();
* });
* });
*/
function connect(url: string, callback: Executor): Response;
@ -229,6 +272,13 @@ declare namespace ws {
* @param params - Request parameters.
* @param callback - Logic to execute with socket.
* @returns HTTP response to connection request.
* @example
* let res = ws.connect(url, { param1: true } , function(socket) {
* socket.on('open', function() {
* console.log('WebSocket connection established!');
* socket.close();
* });
* });
*/
function connect(url: string, params: Params | null, callback: Executor): Response;
}