### Run Setup Stage
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/reference/k6-rest-api.md
Executes the setup stage of the test and returns the resulting setup data. Note: The example uses POST, but the endpoint is documented as PUT.
```bash
curl -X POST \
http://localhost:6565/v1/setup \
-H 'Content-Type: application/json'
```
```json
{
"data": {
"type": "setupData",
"id": "default",
"attributes": {
"data": {
"a": 1
}
}
}
}
```
--------------------------------
### Install Netdata with Kickstart Script
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/results-output/real-time/netdata.md
Use the kickstart script to easily download and run Netdata on your system. This is the recommended method for quick setup.
```bash
bash <(curl -Ss https://my-netdata.io/kickstart.sh)
```
--------------------------------
### Example Usage
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-experimental/fs/_index.md
Demonstrates how to use the k6 experimental fs module to open, read, and get file information.
```APIDOC
```javascript
import { open, SeekMode } from 'k6/experimental/fs';
const file = await open('bonjour.txt');
export default async function () {
// Seek to the beginning of the file
await file.seek(0, SeekMode.Start);
// About information about the file
const fileinfo = await file.stat();
if (fileinfo.name != 'bonjour.txt') {
throw new Error('Unexpected file name');
}
const buffer = new Uint8Array(4);
let totalBytesRead = 0;
while (true) {
// Read into the buffer
const bytesRead = await file.read(buffer);
if (bytesRead == null) {
// EOF
break;
}
// Do something useful with the content of the buffer
totalBytesRead += bytesRead;
// If bytesRead is less than the buffer size, we've read the whole file
if (bytesRead < buffer.byteLength) {
break;
}
}
// Check that we read the expected number of bytes
if (totalBytesRead != fileinfo.size) {
throw new Error('Unexpected number of bytes read');
}
}
```
```
--------------------------------
### Example k6 Agent Installation Status Output
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/set-up/configure-ai-assistant/bootstrap-with-k6-x-agent.md
An example output of the `k6 x agent status` command, illustrating the status of different agents and providing hints for missing configurations.
```text
Agent installation status
[+] Claude Code
- .mcp.json detected
[-] Cursor
- Missing: .cursor/mcp.json
- Hint: k6 x agent init cursor
[+] k6 MCP support
- Found at /usr/local/bin/k6
```
--------------------------------
### Setup Function for Pre-Test Checks
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/using-k6-browser/write-your-first-browser-test.md
Implement a setup function to perform initial checks, such as verifying site availability via an HTTP GET request, before the main test execution.
```typescript
export function setup() {
let res = http.get(BASE_URL);
if (res.status !== 200) {
exec.test.abort(`Got unexpected status code ${res.status} when trying to setup. Exiting.`);
}
}
```
--------------------------------
### Installation
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/jslib/k6chaijs/_index.md
Import k6chaijs directly from jslib or use a local copy. The example shows importing from jslib.
```APIDOC
## Installation
This library is hosted on [jslib](https://jslib.k6.io/) and can be imported directly in your k6 script.
```javascript
import { describe, expect } from 'https://jslib.k6.io/k6chaijs/4.5.0.1/index.js';
```
Alternatively, you can use a copy of this file stored locally. The source code is available on [GitHub](https://github.com/grafana/k6-jslib-k6chaijs).
```
--------------------------------
### Run Setup
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/reference/k6-rest-api.md
Executes the Setup stage of the k6 test and returns the result. This endpoint is used to trigger the setup phase of a test.
```APIDOC
## POST /v1/setup
### Description
Executes the Setup stage and returns the result.
### Method
POST
### Endpoint
`http://localhost:6565/v1/setup`
### Response
#### Success Response (200)
- **data** (object) - Contains the setup data.
- **type** (string) - The type of the resource, always "setupData".
- **id** (string) - The ID of the setup data, usually "default".
- **attributes** (object) - The attributes of the setup data.
- **data** (object) - The actual setup data in JSON format.
### Response Example
```json
{
"data": {
"type": "setupData",
"id": "default",
"attributes": {
"data": {
"a": 1
}
}
}
}
```
```
--------------------------------
### Get Setup Data
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/reference/k6-rest-api.md
Retrieves the current JSON-encoded setup data for the test. This endpoint is used to inspect the setup configuration.
```APIDOC
## GET /v1/setup
### Description
Returns the current JSON-encoded setup data.
### Method
GET
### Endpoint
`http://localhost:6565/v1/setup`
### Response
#### Success Response (200)
- **data** (object) - Contains the setup data.
- **type** (string) - The type of the resource, always "setupData".
- **id** (string) - The ID of the setup data, usually "default".
- **attributes** (object) - The attributes of the setup data.
- **data** (object) - The actual setup data in JSON format.
### Response Example
```json
{
"data": {
"type": "setupData",
"id": "default",
"attributes": {
"data": {
"a": 1
}
}
}
}
```
```
--------------------------------
### Get Setup Data
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/reference/k6-rest-api.md
Retrieves the current JSON-encoded setup data for the test. This endpoint is used to inspect the state of the setup stage.
```bash
curl -X GET \
http://localhost:6565/v1/setup \
-H 'Content-Type: application/json'
```
```json
{
"data": {
"type": "setupData",
"id": "default",
"attributes": {
"data": {
"a": 1
}
}
}
}
```
--------------------------------
### Set up Extension Directory
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/extensions/create/subcommand-extensions.md
Create a new directory for your subcommand extension and initialize a Go module.
```bash
mkdir xk6-subcommand-mytool; cd xk6-subcommand-mytool; go mod init xk6-subcommand-mytool
```
--------------------------------
### Install Node.js and npm Dependencies
Source: https://github.com/grafana/k6-docs/blob/main/CONTRIBUTING/legacy-gatsby-docs/troubleshooting.md
Install specific Node.js and npm versions required by your project. Use 'nvm' to manage Node.js versions. After setting the correct version, install dependencies and start the development server.
```sh
nvm ls ## see what versions are available
nvm install 16.16
nvm use 16.16
npm install && npm start
```
--------------------------------
### Start k6 Documentation Local Server
Source: https://github.com/grafana/k6-docs/blob/main/README.md
Run this command after cloning the repository to start the local development server for the k6 documentation. This allows you to preview changes.
```bash
npm start
```
--------------------------------
### Example Output of k6 Version Command
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/extensions/run/build-k6-binary-using-docker.md
This is an example of the output you would see after running `./k6 version`, showing the k6 version and a list of all loaded extensions.
```bash
k6 v0.43.1 ((devel), go1.20.1, darwin/amd64)
Extensions:
github.com/grafana/xk6-output-influxdb v0.3.0, xk6-influxdb [output]
github.com/mostafa/xk6-kafka v0.17.0, k6/x/kafka [js]
```
--------------------------------
### Setting Input Files from Local Filesystem
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/elementhandle/setinputfiles.md
This example demonstrates how to set files for a file input element by reading them from the local filesystem using k6/experimental/fs. Ensure the file path is absolute.
```javascript
import {
browser
} from 'k6/browser';
import encoding from 'k6/encoding';
import {
open
} from 'k6/experimental/fs';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
// Declare the location of the file on the local filesystem.
let file;
(async function () {
file = await open('/abs/path/to/file.txt');
})();
export default async function () {
const page = await browser.newPage();
try {
// In this example we create a simple web page with an upload input field.
// Usually, you would use page.goto to navigate to a page with a file input field.
await page.setContent(
`
`);
const eh = await page.$('input[id="upload"]');
// Read the whole file content into a buffer.
const buffer = await readAll(file);
// The file is set to the input element with the id "upload".
await eh.setInputFiles({
name: 'file.txt',
mimetype: 'text/plain',
buffer: encoding.b64encode(buffer),
});
} finally {
await page.close();
}
}
// readAll will read the whole of the file from the local filesystem into a
// buffer.
async function readAll(file) {
const fileInfo = await file.stat();
const buffer = new Uint8Array(fileInfo.size);
const bytesRead = await file.read(buffer);
if (bytesRead !== fileInfo.size) {
throw new Error('unexpected number of bytes read');
}
return buffer;
}
```
--------------------------------
### Basic Usage Example
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-x-mqtt/client/_index.md
Demonstrates a basic k6 script for connecting to an MQTT broker, subscribing to a topic, publishing a message, and handling connection events.
```javascript
import { Client } from "k6/x/mqtt"
export default function () {
const client = new Client()
client.on("connect", () => {
console.log("Connected to MQTT broker")
client.subscribe("greeting")
client.publish("greeting", "Hello MQTT!")
})
client.on("message", (topic, message) => {
const str = String.fromCharCode.apply(null, new Uint8Array(message))
console.info("topic:", topic, "message:", str)
client.end()
})
client.on("end", () => {
console.log("Disconnected from MQTT broker")
})
client.connect(__ENV["MQTT_BROKER_ADDRESS"] || "mqtt://broker.emqx.io:1883")
}
```
--------------------------------
### Basic expect.configure() example
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/jslib/testing/configure.md
Create a configured expect instance with custom timeout, interval, colorization, and display options. This configured instance can then be used for assertions, while the original expect instance remains available with its default settings.
```javascript
import { expect } from 'https://jslib.k6.io/k6-testing/{{< param "JSLIB_TESTING_VERSION" >}}/index.js';
// Create a configured expect instance
const myExpect = expect.configure({
timeout: 8000,
interval: 200,
colorize: true,
display: 'pretty',
});
export default function () {
// Use the configured instance
myExpect(response.status).toBe(200);
// Original expect instance still works with defaults
expect(response.status).toBe(200);
}
```
--------------------------------
### postData() Usage
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/request/postdata.md
This example demonstrates how to use the postData() method to get the post body of a request after navigating to a page.
```APIDOC
## postData()
### Description
Retrieves the post body of the request.
### Method
`req.postData()`
### Parameters
None
### Returns
- `string | null`: The request's post body, or `null` if none exists.
### Example
```javascript
import { browser } from 'k6/browser';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
try {
const res = await page.goto('https://test.k6.io/');
const req = res.request();
const postData = req.postData();
console.log(`postData: ${postData}`); // postData: null
} finally {
await page.close();
}
}
```
```
--------------------------------
### Get Page Workers
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/page/workers.md
Retrieves all WebWorkers associated with the current page. This example demonstrates how to access and log the workers after navigating to a URL.
```javascript
import { browser } from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
await page.goto('https://test.k6.io/browser.php');
console.log(page.workers());
}
```
--------------------------------
### gRPC Client Example
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-net-grpc/_index.md
This example demonstrates how to use the k6/net/grpc module to make a gRPC call. It shows how to load a proto file, connect to a gRPC server, invoke a service method, and check the response.
```APIDOC
## grpc.Client
### Description
Represents a gRPC client that can be used to connect to and interact with gRPC services.
### Methods
#### `load(protoPath, serviceName)`
Loads a Protocol Buffers definition.
#### `connect(address, options)`
Establishes a connection to a gRPC server.
#### `invoke(method, data)`
Invokes a gRPC method on the connected server.
#### `close()`
Closes the connection to the gRPC server.
### Example
```javascript
import grpc from 'k6/net/grpc';
import { check, sleep } from 'k6';
const client = new grpc.Client();
client.load(null, 'quickpizza.proto');
export default () => {
client.connect('grpc-quickpizza.grafana.com:443', {
// plaintext: false
});
const data = { ingredients: ['Cheese'], dough: 'Thick' };
const response = client.invoke('quickpizza.GRPC/RatePizza', data);
check(response, {
'status is OK': (r) => r && r.status === grpc.StatusOK,
});
console.log(JSON.stringify(response.message));
client.close();
sleep(1);
};
```
```
--------------------------------
### Build k6 with Dynatrace Extension
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/results-output/real-time/dynatrace.md
Install xk6 and build a custom k6 binary with the Dynatrace output extension. Ensure Go and Git are installed.
```bash
go install go.k6.io/xk6/cmd/xk6@latest
xk6 build --with github.com/Dynatrace/xk6-output-dynatrace
```
--------------------------------
### Initial k6 Browser Script Setup
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/using-k6-browser/migrate-from-playwright-to-k6.md
This is the basic setup for a k6 browser script, including necessary imports and options.
```javascript
import { expect } from 'https://jslib.k6.io/k6-testing/{{< param "JSLIB_TESTING_VERSION" >}}/index.js';
import { browser } from 'k6/browser';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
// Paste your test code here
}
```
--------------------------------
### Perform HTTP GET Request with Presigned URL
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/jslib/aws/signaturev4/presign.md
After obtaining a presigned URL and headers, use k6's http module to make a GET request to the S3 object. This example assumes `presignedRequest` is an object containing the `url` and `headers` generated by the presign functionality.
```javascript
const res = http.get(presignedRequest.url, {
headers: presignedRequest.headers,
});
check(res, {
'status is 200': (r) => r.status === 200
});
```
--------------------------------
### Get Page Title with k6 Browser
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/page/title.md
This example demonstrates how to navigate to a URL and then retrieve and log the page's title using the `page.title()` method.
```javascript
import { browser } from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
await page.goto('https://test.k6.io/browser.php');
console.log(await page.title());
}
```
--------------------------------
### Basic Browser Test
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/_index.md
This example demonstrates how to import the browser module, create a new page, navigate to a URL, and close the page. It also includes basic k6 options for running a browser scenario.
```APIDOC
## Basic Browser Test
### Description
This example demonstrates how to import the browser module, create a new page, navigate to a URL, and close the page. It also includes basic k6 options for running a browser scenario.
### Code
```javascript
import { browser } from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
thresholds: {
checks: ['rate==1.0'],
},
};
export default async function () {
const page = await browser.newPage();
try {
await page.goto('https://test.k6.io/');
} finally {
await page.close();
}
}
```
```
--------------------------------
### Preview k6 x agent initialization changes
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/set-up/configure-ai-assistant/bootstrap-with-k6-x-agent.md
Before making any disk writes, use the `--dry-run` flag with a specific target to preview all files that would be created or merged, including byte counts and write modes. This helps in understanding the impact of the `init` command without altering your project.
```sh
k6 x agent init --dry-run
```
--------------------------------
### Get all following siblings
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-html/selection/selection-nextall.md
Use `nextAll()` to select all sibling elements that appear after the current element in the DOM. This example finds all list items following 'list item 3'.
```javascript
import { parseHTML } from 'k6/html';
import { sleep } from 'k6';
export default function () {
const content = `
- list item 1
- list item 2
- list item 3
- list item 4
- list item 5
`;
const doc = parseHTML(content);
const sel = doc.find('li.third-item').nextAll();
console.log(sel.size());
sleep(1);
}
```
--------------------------------
### Go Native Constructor Example
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/extensions/create/go-js-bridge.md
Demonstrates how to implement a native constructor in Go for JavaScript. This allows JavaScript to create instances of Go types using the `new` keyword, and the method receives the sobek runtime.
```go
func (*Compare) XComparator(call sobek.ConstructorCall, rt *sobek.Runtime) *sobek.Object {
return rt.ToValue(&Compare{}).ToObject(rt)
}
```
--------------------------------
### Count Matching Elements
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/locator/count.md
Use `locator.count()` to get the number of elements matching a selector. This example demonstrates how to retry the count if it doesn't match the expected value within a loop.
```javascript
import { expect } from 'https://jslib.k6.io/k6-testing/{{< param "JSLIB_TESTING_VERSION" >}}/index.js';
import { browser } from 'k6/browser';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
await page.goto('https://quickpizza.grafana.com/login');
const expected = 3;
let match = false;
for (let i = 0; i < 5; i++) {
match = await page.locator('input').count();
if (match == expected) {
break;
}
}
expect(match).toEqual(expected);
await page.close();
}
```
--------------------------------
### Build k6 MCP from source
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/set-up/configure-ai-assistant/_index.md
Clone the mcp-k6 repository from GitHub and use `make install` to build and install the k6 MCP server from source.
```bash
git clone https://github.com/grafana/mcp-k6
cd mcp-k6
make install
```
--------------------------------
### Using Selection.not() with a Function
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-html/selection/selection-not.md
Illustrates excluding elements based on a custom test function. This example removes elements whose text content starts with 'definition' from the current selection.
```javascript
sel = sel.not(function (idx, item) {
return item.text().startsWith('definition');
});
```
--------------------------------
### Correct vs. Incorrect Promise Setup for waitForResponse
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/page/waitforresponse.md
This snippet illustrates the best practice for using `waitForResponse`. The 'Correct' example shows initiating the promise before the action, ensuring the response is not missed. The 'Incorrect' example highlights a common mistake where the promise is set up after the action, potentially leading to race conditions and missed responses.
```javascript
// Correct
const responsePromise = page.waitForResponse('/api/data');
await page.click('#submit');
const response = await responsePromise;
// Incorrect - may miss the response
await page.click('#submit');
const response = await page.waitForResponse('/api/data');
```
--------------------------------
### Client Constructor and Usage
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/jslib/http-instrumentation-tempo/client.md
Demonstrates how to instantiate a tracing client using `tempo.Client` and use it to make instrumented HTTP requests. It also shows how to perform non-instrumented requests using the standard `k6/http` module.
```APIDOC
## Client Constructor and Usage
### Description
Instantiate a `tempo.Client` to create an HTTP client that automatically attaches trace context headers to requests. This allows for tracing requests with backends like Grafana Tempo. The `Client` can be configured with options like the propagator type.
### Method
`new tempo.Client(options)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Options Object
- **propagator** (string) - Required - Specifies the trace context propagation format. Supported values include 'w3c' and 'jaeger'.
### Request Example
```javascript
import { check } from 'k6';
import tempo from 'https://jslib.k6.io/http-instrumentation-tempo/{{< param "JSLIB_TEMPO_VERSION" >}}/index.js';
import http from 'k6/http';
const instrumentedHTTP = new tempo.Client({
propagator: 'w3c',
});
const testData = { name: 'Bert' };
export default () => {
// Instrumented request
let res = instrumentedHTTP.request('GET', 'http://httpbin.org/get', null, {
headers: {
'X-Example-Header': 'instrumented/request',
},
});
// Non-instrumented request using standard http module
res = http.post('http://httpbin.org/post', JSON.stringify(testData), {
headers: { 'X-Example-Header': 'noninstrumented/post' },
});
// Another instrumented request
res = instrumentedHTTP.del('http://httpbin.org/delete', null, {
headers: { 'X-Example-Header': 'instrumented/delete' },
});
};
```
### Response
#### Success Response (200)
Responses are standard HTTP responses from the target endpoint. The `Client` adds tracing metadata to the k6 output data points.
```
--------------------------------
### Get Preceding Sibling with Selection.prev()
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-html/selection/selection-prev.md
Use Selection.prev() to find the immediately preceding sibling of a selected element. This example demonstrates selecting an element with a specific class and then finding its previous sibling.
```javascript
import { parseHTML } from 'k6/html';
import { sleep } from 'k6';
export default function () {
const content = `
- list item 1
- list item 2
- list item 3
- list item 4
- list item 5
`;
const doc = parseHTML(content);
const sel = doc.find('li.third-item').prev();
console.log(sel.html());
sleep(1);
}
```
--------------------------------
### Kubectl Commands for Nginx Setup
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/testing-guides/injecting-faults-with-xk6-disruptor/xk6-disruptor/servicedisruptor/_index.md
These bash commands are used to set up a basic nginx pod and expose it as a service, which can then be targeted by the ServiceDisruptor for fault injection testing. Ensure kubectl is installed and configured.
```bash
kubectl run nginx --image=nginx
kubectl expose pod nginx --port 80
```
--------------------------------
### Use Kubernetes Extension
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/using-k6/modules.md
Demonstrates creating a Kubernetes Pod, listing Pods in a namespace, and logging their names using the imported Kubernetes extension. This requires the xk6-kubernetes extension to be built and available.
```javascript
const podSpec = {
apiVersion: 'v1',
kind: 'Pod',
metadata: { name: 'busybox', namespace: 'testns' },
spec: {
containers: [
{
name: 'busybox',
image: 'busybox',
command: ['sh', '-c', 'sleep 30'],
},
],
},
};
export default function () {
const kubernetes = new Kubernetes();
kubernetes.create(podSpec);
const pods = kubernetes.list('Pod', 'testns');
pods.map(function (pod) {
console.log(pod.metadata.name);
});
}
```
--------------------------------
### Complete k6 Browser Test Script
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/using-k6-browser/write-your-first-browser-test.md
A full example of a k6 browser test script, combining imports, options, setup, and the default test function with environment variable support for BASE_URL.
```javascript
import http from 'k6/http';
import exec from 'k6/execution';
import { browser } from 'k6/browser';
import { sleep, check, fail } from 'k6';
const BASE_URL = __ENV.BASE_URL || 'https://quickpizza.grafana.com';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
vus: 1,
iterations: 1,
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export function setup() {
const res = http.get(BASE_URL);
if (res.status !== 200) {
exec.test.abort(`Got unexpected status code ${res.status} when trying to setup. Exiting.`);
}
}
export default async function () {
let checkData;
const page = await browser.newPage();
try {
await page.goto(BASE_URL);
checkData = await page.locator('h1').textContent();
check(page, {
header: checkData === 'Looking to break out of your pizza routine?',
});
await page.locator('//button[. = "Pizza, Please!"]').click();
await page.waitForTimeout(500);
await page.screenshot({ path: 'screenshot.png' });
checkData = await page.locator('div#recommendations').textContent();
check(page, {
recommendation: checkData !== '',
});
} catch (error) {
fail(`Browser iteration failed: ${error.message}`);
} finally {
await page.close();
}
sleep(1);
}
```
--------------------------------
### Run k6 with Full Summary Mode
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/release-notes/v1.0.0.md
Example command to execute a k6 script and display the full, detailed end-of-test summary. This provides granular results for faster debugging.
```bash
k6 run --summary-mode=full script.ts
```
--------------------------------
### Dispatching a Click Event on an Element
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/page/dispatchevent.md
This example demonstrates how to use `page.dispatchEvent()` to simulate a 'click' event on an element with the ID 'counter-button' after navigating to a specific URL. It includes the necessary k6 browser setup.
```javascript
import { browser } from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
await page.goto('https://test.k6.io/browser.php');
await page.dispatchEvent('#counter-button', 'click');
}
```
--------------------------------
### Using frameLocator.locator with text filtering
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/framelocator/locator.md
This example demonstrates how to get a locator for an iframe and then use `frameLocator.locator()` to find a specific button within that frame, filtering by its text content. It then clicks the found button.
```javascript
import {
browser
} from 'k6/browser';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
await page.setContent(``);
// Get a locator for an iframe element
const frameLocator = page.locator('iframe').contentFrame();
// Create a locator within the frame with text filtering options
const submitButton = frameLocator.locator('button', {
hasText: 'Pizza, Please!'
});
await submitButton.click();
}
```
--------------------------------
### Establish TLS Connection and Send HTTP Request
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-x-tcp/_index.md
Demonstrates how to establish a TLS-secured TCP connection to a host, send an HTTP GET request, and process the response. Requires the TLS_HOST environment variable or defaults to 'example.com'.
```javascript
import { Socket } from "k6/x/tcp"
export default async function () {
const socket = new Socket()
const closed = new Promise((resolve) => {
socket.on("close", resolve)
})
socket.on("data", (data) => {
const response = String.fromCharCode.apply(null, new Uint8Array(data))
console.log("Received:", response.substring(0, 100))
socket.destroy()
})
socket.on("error", (err) => {
console.error("Error:", err)
})
const host = __ENV.TLS_HOST || "example.com"
await socket.connect({ port: 443, host, tls: true })
await socket.write(`GET / HTTP/1.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n`)
await closed
}
```
--------------------------------
### Basic Usage
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-x-tcp/_index.md
Demonstrates how to establish a TCP connection, send data, and handle connection events using the k6/x/tcp module.
```APIDOC
## Basic Usage
This example shows a simple TCP client that connects to a server, sends a message, and then closes the connection. It utilizes Promises for asynchronous operations and event handlers for connection lifecycle events.
### Method
`socket.connect(port, [host], [options])`
`socket.write(data)`
`socket.destroy()`
`socket.on(event, handler)`
### Example
```javascript
import { Socket } from "k6/x/tcp"
export default async function () {
const socket = new Socket()
const closed = new Promise((resolve) => {
socket.on("close", () => {
console.log("Connection closed")
resolve()
})
})
socket.on("error", (err) => {
console.error("Error:", err)
})
const host = __ENV.TCP_HOST || "localhost"
const port = __ENV.TCP_PORT || "8080"
await socket.connect(port, host)
console.log("Connected")
socket.destroy()
await closed
}
```
```
--------------------------------
### Interact with iframe content using contentFrame()
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/locator/contentframe.md
Use contentFrame() to get a FrameLocator for an iframe and then interact with elements within that iframe. This example demonstrates setting iframe content, locating it, and clicking elements inside.
```javascript
import {
browser
} from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
try {
await page.setContent(
``
);
const frameLocator = page.locator('#my_frame').contentFrame();
await frameLocator.getByText('Pizza, Please!').click();
const noThanksBtn = frameLocator.getByText('No thanks');
await noThanksBtn.click();
} finally {
await page.close();
}
}
```
--------------------------------
### Get all pages in a BrowserContext
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/browsercontext/pages.md
This example demonstrates how to create a new browser context, open a new page, retrieve all pages within the context using `context.pages()`, and log the number of pages. It then closes the context.
```javascript
import {
browser
} from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const context = await browser.newContext();
await context.newPage();
const pages = context.pages();
console.log(pages.length); // 1
await context.close();
}
```
--------------------------------
### Example: Using toBeDisabled() in a k6 Browser Test
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/jslib/testing/retrying-assertions/toBeDisabled.md
Demonstrates how to use `toBeDisabled()` within a k6 browser test script to assert that a button becomes disabled after an action. It includes necessary imports and test setup.
```javascript
import {
browser
} from 'k6/browser';
import {
expect
} from 'https://jslib.k6.io/k6-testing/{{< param "JSLIB_TESTING_VERSION" >}}/index.js';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
}
};
export default async function () {
const page = await browser.newPage();
await page.goto('https://quickpizza.grafana.com/');
// Click the pizza button to see the recommendation
await page.locator('button[name="pizza-please"]').click();
// Wait for the recommendation to appear
await expect(page.locator('h2[id="pizza-name"]')).toBeVisible();
// The pizza button should now be disabled (no longer clickable)
await expect(page.locator('button[name="pizza-please"]')).toBeDisabled();
// Verify that we can check for disabled state
await expect(page.locator('button[name="pizza-please"]')).not.toBeEnabled();
}
```
--------------------------------
### Device Emulation
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/_index.md
This example shows how to use the `devices` object from `k6/browser` to emulate a specific device, such as an iPhone X, when creating a new browser context.
```APIDOC
## Device Emulation
### Description
This example shows how to use the `devices` object from `k6/browser` to emulate a specific device, such as an iPhone X, when creating a new browser context.
### Code
```javascript
import { browser, devices } from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
thresholds: {
checks: ['rate==1.0'],
},
};
export default async function () {
const iphoneX = devices['iPhone X'];
const context = await browser.newContext(iphoneX);
const page = await context.newPage();
try {
await page.goto('https://test.k6.io/');
} finally {
page.close();
}
}
```
```
--------------------------------
### Run Datadog Agent Docker Container
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/results-output/real-time/datadog.md
Starts the Datadog Agent as a Docker container. Ensure to replace placeholders with your actual Datadog API key and site URL. This setup is necessary for k6 to send metrics to Datadog.
```bash
DOCKER_CONTENT_TRUST=1 \
docker run --rm -d \
--name datadog \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
-v /proc/:/host/proc/:ro \
-v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro \
-e DD_SITE="datadoghq.com" \
-e DD_API_KEY= \
-e DD_DOGSTATSD_NON_LOCAL_TRAFFIC=1 \
-p 8125:8125/udp \
datadog/agent:latest
```
--------------------------------
### Client.connect(url, [options])
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-x-mqtt/client/connect.md
Establishes a connection to an MQTT broker. When the connection is successfully established, the `connect` event is triggered.
```APIDOC
## Client.connect(url, [options])
### Description
Establishes a connection to an MQTT broker. When the connection is successfully established, the `connect` event is triggered.
### Parameters
#### Path Parameters
- **url** (string) - Required - Broker URL (for example, `mqtt://broker.emqx.io:1883`)
- **options** (object) - Optional - Connection configuration
- **keepalive** (number) - Optional - Keep-alive interval in seconds (default: 60)
- **connect_timeout** (number) - Optional - Connection timeout in milliseconds (default: 30000)
- **clean_session** (boolean) - Optional - Whether to start with a clean session (default: true)
- **servers** (string[]) - Optional - Array of broker URLs for failover
- **tags** (object) - Optional - Custom tags for metrics (key-value pairs)
### Supported broker URL schemas
- `mqtt://`: Plain TCP connection (no encryption)
- `mqtts://`: Secure connection over SSL/TLS
- `tcp://`: Alias for `mqtt://`
- `ssl://`: Alias for `mqtts://`
- `tls://`: Alias for `mqtts://`
- `ws://`: MQTT over WebSocket
- `wss://`: MQTT over secure WebSocket
If the schema is omitted, `mqtt://` is used as the default.
### SSL/TLS configuration
The extension uses standard k6 TLS configuration for all SSL/TLS settings. Configure certificates, verification, and other TLS-related options using k6's environment variables and configuration files.
```
--------------------------------
### Using evaluateHandle to get a JSHandle
Source: https://github.com/grafana/k6-docs/blob/main/docs/sources/k6/v2.0.x/javascript-api/k6-browser/locator/evaluatehandle.md
Executes a JavaScript function in the page context and returns a JSHandle to the result. This example demonstrates retrieving a JSHandle to an element's value and then using another `evaluateHandle` to extract specific properties from that handle.
```javascript
import {
browser
} from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
try {
await page.goto("https://quickpizza.grafana.com", { waitUntil: "load" });
await page.getByText('Pizza, Please!').click();
const jsHandle = await page.locator('#pizza-name').evaluateHandle((pizzaName) => pizzaName);
const obj = await jsHandle.evaluateHandle((handle) => {
return { innerText: handle.innerText };
});
console.log(await obj.jsonValue()); // {"innerText":"Our recommendation:"}
} finally {
await page.close();
}
}
```
--------------------------------
### Install and Use Node.js Version
Source: https://github.com/grafana/k6-docs/blob/main/CONTRIBUTING/legacy-gatsby-docs/README.md
Use a Node.js version manager like nvm to install and switch to the required Node.js version specified in package.json.
```bash
nvm install 16.16
nvm use 16.16
```