Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install k6@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin k6 v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install k6

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/k6/

Extract the ZIP to .github/skills/ in your repo. The folder name must match k6 for Copilot to auto-discover it.

Skill Files (22)

SETUP.md 1.4 KB
# k6 skill: `k6 x docs` Setup Guide

Read this file when `k6 x docs` is not working — it covers how to provision (or build) the docs binary, and how to message the user if neither path succeeds.

## k6 v1.7.0+ (recommended) — no build required

As of k6 v1.7.0, the docs subcommand is **auto-provisioned** on first use (~30s, then cached).

```bash
k6 version   # confirm v1.7.0+

# Try without a version flag first (uses the bundle matching your k6 version):
k6 x docs 2>&1 | head -3

# If you get a 404 error, fall back to the previous version:
k6 x docs --version v1.6.1 2>&1 | head -3
```

Use the first command that returns a topic list as `DOCS_CMD`.

---

## Older k6 — manual build

If you're on k6 < v1.7.0, build the binary manually:

```bash
# Requires Go 1.21+ and xk6
go install go.k6.io/xk6/cmd/xk6@latest
xk6 build --with github.com/grafana/xk6-subcommand-docs@latest -o ./k6-with-docs
./k6-with-docs x docs 2>&1 | head -3
```

If this succeeds, set `DOCS_CMD = ./k6-with-docs x docs` and continue.

---

## Note for this session

Tell the user:

> `k6 x docs` is not working in this environment.
>
> **If you have k6 v1.7.0+:** run `k6 x docs` — it auto-provisions the docs binary.
> If that returns a 404 error, try `k6 x docs --version v1.6.1` as a fallback.
>
> **If you have an older k6:** I can build `./k6-with-docs` if `xk6` and Go 1.21+ are available.
> Would you like me to try?
>
> If nothing works, I'll fall back to web docs from grafana.com.
SKILL.md 12.7 KB
---
name: k6
license: Apache-2.0
description: Generate, validate, and review k6 test scripts — load, stress, spike, soak, smoke, breakpoint, functional, and protocol. Covers HTTP, WebSocket, gRPC, browser, all executors, thresholds, checks, custom metrics, the k6-testing library, k6 Cloud execution, and the xk6 extension ecosystem; uses the xk6-docs CLI (with grafana.com web fallback) for docs lookup and validates every script by running it. Use when writing, generating, validating, or debugging any k6 or load-test script (including plain-language asks like "load test this API" or "stress test my service"), choosing executors/scenarios, or setting thresholds. For end-to-end website performance suites use k6-perf-test-website; for documenting k6 itself use k6-docs; for a browser/UI test authored from a plain-language user journey (selectors discovered by exploring the live site) use k6-browser-test.
---

# k6 Script Generation

> **Efficiency note:** This is a short linear recipe (read example → adapt → save → validate → review). A todo list would just mirror the headings without adding value, so skip the planning overhead and execute the steps directly.
>
> **Agent-agnostic:** The steps below describe capabilities, not specific tools. Where a step says "fetch a URL" or "write a file", use whatever your agent provides for that capability (e.g. a web-fetch tool, a file-write tool, or shell `curl`/`tee`).

---

## Step 1: Pick the right example file

Read only the file that matches the user's request. Examples provide structural scaffolding — the correct scaffold, option shapes, and import patterns.

| User needs | Read this file |
|-----------|---------------|
| HTTP REST, auth flow, batch requests | `examples/http.js` |
| HTML parsing with parseHTML, SharedArray | `examples/html.js` |
| WebSocket | `examples/websocket.js` |
| gRPC | `examples/grpc.js` |
| Browser automation | `examples/browser.js` |
| Browser + functional test / `expect()` / k6-testing | `examples/functional.js` (browser scenario) |
| Functional/integration tests, `expect()`, k6-testing | `examples/functional.js` |
| Custom metrics, execution module, handleSummary, per-vu-iterations | `examples/metrics.js` |
| Load patterns, all executors (ramping, arrival rate, per-VU, etc.) | `examples/executors.js` |
| Cloud run, `--local-execution`, `cloud` options | `examples/cloud.js` |
| Crypto (HMAC, MD5, SHA256) or encoding (base64) | `examples/crypto-encoding.js` |
| xk6-faker | `examples/ext-faker.js` |
| xk6-redis | `examples/ext-redis.js` |
| xk6-sql / sqlite3 / postgres | `examples/ext-sql.js` |
| xk6-exec | `examples/ext-exec.js` |
| xk6-dns | `examples/ext-dns.js` |
| xk6-tls | `examples/ext-tls.js` |
| xk6-tcp | `examples/ext-tcp.js` |
| xk6-crawler | `examples/ext-crawler.js` |

Example files live in the `examples/` directory alongside this `SKILL.md`.

**When the request matches multiple rows** (e.g. "browser" + "functional test"), prefer the row whose assertion style fits the intent. If the user says "functional test", "assert", "verify", or "expect", use `functional.js` even if the test involves a browser — it demonstrates `expect()` with auto-retrying browser matchers. Use `browser.js` for browser load/performance tests that don't emphasize correctness assertions.

**Browser test from a plain-language journey?** If the user describes a browser flow in prose and the selectors aren't known yet — i.e. they must be discovered by driving the live site — defer to the **k6-browser-test** skill, which explores the live page to resolve real `getBy*` locators before writing the test. Use the browser rows above when the page structure and selectors are already known.

---

## Step 2: Adapt the example

Use the loaded example as the starting point. Adapt it to the user's exact requirements:
- Change endpoints, VU counts, durations, thresholds
- Add or remove scenario steps
- Rename functions and variables to match the domain
- Every expression must be complete and runnable — no `{ ... }`, `// TODO`, or stubs
- **Match the request — don't over-build.** Implement exactly what was asked. Don't add custom request tags, extra `sleep()` calls, additional endpoints, or `options` the user didn't request. Unrequested complexity lowers quality and reduces adherence to the spec.

For multi-scenario scripts (browser + HTTP, cloud): use named `scenarios` with `exec` pointing to separate exported functions.

---

## Step 3: Fill gaps with docs (only if needed)

The example covers common patterns. Adapt from it directly. **Skip this step entirely** if the example provides everything you need.

**Only reach for docs if**:
- The user asks for an API or option not demonstrated in the example, **or**
- You are not confident about the exact signature, option name, or return type

When a gap exists, first establish the docs command (one-time per session).

The `k6 x docs` CLI renders content only when it detects a TTY. Since agents
run non-interactively, wrap every call with `script` to allocate a pseudo-TTY
and pipe the ANSI-stripped content to stdout:

```bash
# Detect OS once (macOS vs Linux have different `script` flags):
if [[ "$(uname -s)" == "Darwin" ]]; then
  DOCS_CMD="script -q /dev/null k6 x docs"
else
  DOCS_CMD="script -qc 'k6 x docs' /dev/null"
fi

# Verify it works — should print a topic list, NOT a "browse files" guide:
$DOCS_CMD 2>/dev/null | head -5
```

If the output still shows "k6 documentation is a directory of markdown files",
the TTY wrapper isn't working. Fall back to **web docs** under
`https://grafana.com/docs/k6/latest/` — fetch pages with whatever web-fetch
capability your agent has (a built-in fetch tool, or `curl` in a shell).

If `k6 x docs` fails outright (command not found, provisioning or 404 errors),
read `SETUP.md` — it covers auto-provisioning on k6 v1.7.0+ and the manual
xk6 build for older versions.

Then look up what you need:

```bash
$DOCS_CMD <path>              # e.g. javascript-api k6-http
$DOCS_CMD <path> --depth 2
$DOCS_CMD search <term>
```

Common CLI paths and the 2-call strategy are in `docs-guidance.md`.

**Do not use unpkg, @types/k6, or any npm type definition URLs.**

---

## Step 4: Save

Line 1 of every script must be a generated-by comment. Get the current UTC timestamp first (the file content depends on it, so this can't be parallelized with the write):

```bash
date -u +%Y-%m-%dT%H:%M:%SZ
```

Then include it as line 1:
```javascript
// Generated by grafana-k6 on 2026-03-25T22:02:20.203Z
```

Save to `k6/scripts/<descriptive-name>.js`. Use lowercase kebab-case filenames. If your file-write capability doesn't create parent directories automatically, `mkdir -p k6/scripts` first.

**The script file on disk is the deliverable** — always write it. Never end the task with the script shown only in chat: Steps 5–7 (validate, review, present) all require the file to exist at `k6/scripts/<name>.js`. If a write fails, retry it before continuing.

---

## Step 5: Validate

Match top-down — the first matching row wins:

| Script type | Command |
|------------|---------|
| Imports `k6/browser` | `k6 run k6/scripts/<name>.js` |
| Any `ramping-vus` or `*-arrival-rate` scenario | `k6 inspect k6/scripts/<name>.js` — a full run would execute the entire load profile against the target |
| Other named `executor:` blocks (short scenarios) | `k6 run k6/scripts/<name>.js` |
| Everything else (HTTP, WS, gRPC) | `k6 run --vus 1 --iterations 1 k6/scripts/<name>.js` |

**What counts as passing:** for functional and browser scripts, validation passes only when the exit code is 0 *and* the summary shows no failed checks or `expect()` errors — a script that completes with failing assertions is not validated. k6's error output names the exact locator or assertion that failed (and what it waited for); use it to fix the selector or logic. For load tests, exit code 0 is a pass, and a pure threshold breach under load (exit code 99) is acceptable.

If validation fails: read stderr, fix the root cause, retry up to **3 attempts**. After 3 failures, present the error and ask the user how to proceed (or, when running unattended, deliver the best attempt and clearly report the unresolved error).

---

## Step 6: Best-practices review

### General checks (all scripts)

Review the script against the rules below. The checklist is authoritative — only look up docs (`$DOCS_CMD best-practices` or `https://grafana.com/docs/k6/latest/using-k6/`) if you're uncertain about a specific rule.

- **`export const options` with realistic VUs/duration.** Default VUs/durations make the test meaningful out of the box.
- **Define `thresholds` for every load test.** Without thresholds the run can't fail in CI even when performance regresses, which defeats the point of running a load test. At minimum include `http_req_duration` and `http_req_failed` (or the protocol equivalent). Pure functional tests — single-iteration `expect()`-only scripts — can skip this.
- **Include `sleep()` in closed-model (VU-based) load tests.** `sleep()` represents user think time; without it, VUs hammer endpoints faster than any real user would, inflating throughput and crowding out the system under test. This applies to VU-based HTTP, WebSocket, gRPC, crypto, and extension scripts. **Open-model executors** (`constant-arrival-rate`, `ramping-arrival-rate`) already pace iterations to a target rate, so `sleep()` there is usually unnecessary — it only ties up VUs without changing the offered load. Browser scripts use `page.waitForTimeout()` instead; single-iteration functional tests and one-shot connectivity/demo scripts can skip it. In event-driven WebSocket scripts, put the `sleep()` inside the `close` handler (see `examples/websocket.js`) — sleeping in the main function body blocks the event loop before any messages arrive.
- **Assert every response.** **Browser scripts**: use `expect()` from k6-testing — it auto-retries against locators and replaces `waitFor()` + `isVisible()` + `check()` chains. If you need a metric-tracked `check()` inside an async browser function, the standard `check` from `k6` works fine **as long as the predicate is synchronous** — `await` the value first, then check it. Only reach for the k6-utils wrapper (`https://jslib.k6.io/k6-utils/1.5.0/index.js`) when the predicate itself must `await` something: a bare `async` predicate returns a Promise, which is always truthy, so the check silently passes. **HTTP/gRPC/WS scripts**: use `check()` for metric-tracked assertions, or `expect()` for functional tests. Silent failures are worse than loud ones.
- **Browser scripts:** wrap interactions in `try/finally` with `page.close()` in `finally`, so pages clean up even when assertions throw.
- **gRPC scripts:** wrap the iteration's calls in `try/finally` and call `client.close()` in the `finally` block, so the connection is released even when a check throws mid-iteration.
- **WebSocket scripts:** wrap `JSON.parse` of incoming messages in `try/catch` — servers can send non-JSON frames, and one bad frame shouldn't kill the VU.
- **No `let`/`var` at top level** — use `const`, since module-scope state is shared across VUs and mutability there is almost always a bug.
- **No deprecated imports** — use `k6/websockets` for WebSockets; both `k6/ws` and `k6/experimental/websockets` are deprecated.

### Load & breakpoint tests

- **Breakpoint tests: ramp *offered load*, not VUs.** Use an open-model executor (`ramping-arrival-rate`) so the request rate is independent of how slow the system gets; a closed model (`ramping-vus`) throttles itself as latency rises and masks the breaking point. Pair thresholds with `abortOnFail: true` and a short `delayAbortEval` so the run stops (and reports) once an SLO is crossed.
- **Track SLO-relevant custom metrics** for reporting: per-endpoint latency (`Trend`), an error `Rate`, and any domain counters — plus a `handleSummary` that surfaces p95/p99, throughput (req/s), and error rate. See `examples/executors.js` and `examples/metrics.js`.
- **Hybrid protocol + browser load tests:** wrap the browser flow in `try/catch` and record failures to a custom error metric instead of letting an `expect()` throw — a single flaky browser iteration must not abort a long protocol load run.

### Browser scripts — recommended practices

If the script imports `k6/browser`, read `browser-best-practices.md` and apply all checks. Fix issues and re-validate.

---

## Step 7: Present results

1. Full script with file path
2. Validation output
3. Best-practices notes (issues found, or "all checks passed")
4. Suggested run command

```bash
k6 run --vus 10 --duration 30s k6/scripts/api-load-test.js
k6 run k6/scripts/browser-test.js
k6 cloud run k6/scripts/cloud-test.js
k6 cloud run --local-execution k6/scripts/hybrid-test.js
./k6-with-faker run k6/scripts/faker-test.js
K6_BROWSER_HEADLESS=true k6 run k6/scripts/browser-test.js
```

## Step 8: Execute

If the user confirms, run the command.
browser-best-practices.md 6.5 KB
# Browser Recommended Practices

Apply these checks to any script that imports `k6/browser`.

If you are uncertain about any topic, look it up using `DOCS_CMD` (establish it per Step 3 in SKILL.md if not yet set):

```bash
# With CLI:
$DOCS_CMD using-k6-browser/recommended-practices/select-elements
$DOCS_CMD using-k6-browser/recommended-practices/handle-dynamic-elements
$DOCS_CMD using-k6-browser/recommended-practices/sleep-vs-page-wait-for-timeout
$DOCS_CMD using-k6-browser/recommended-practices/clean-up-test-resources-page-close
$DOCS_CMD using-k6-browser/recommended-practices/prevent-cookie-banners-blocking
$DOCS_CMD using-k6-browser/recommended-practices/prevent-too-many-time-series-error
$DOCS_CMD using-k6-browser/recommended-practices/hybrid-approach-to-performance
$DOCS_CMD using-k6-browser/recommended-practices/page-object-model-pattern
$DOCS_CMD using-k6-browser/recommended-practices/simulate-user-input-delay

# Web fallback — fetch with whatever capability your agent has (built-in fetch, or curl):
# https://grafana.com/docs/k6/latest/using-k6-browser/recommended-practices/<topic>/
```

---

## Element selection — use `getBy*` APIs first

More readable and resilient than CSS/XPath:

- `page.getByRole('button', { name: 'Submit' })` — preferred for interactive elements
- `page.getByLabel('Username')` — preferred for form inputs
- `page.getByText('Rated!')` — preferred for text content
- `page.getByTestId('pizza-btn')` — preferred when `data-testid` attributes exist
- `page.getByPlaceholder('Enter email')` — preferred for inputs with placeholders
- Fall back to `page.locator('#id')` or `page.locator('[data-test="x"]')` only when no `getBy*` applies
- Avoid generic `page.locator('button')` (no context) and absolute XPath

## Locator actionability — no `waitFor()` before interactions

Locator APIs (`click()`, `fill()`, `selectOption()`, etc.) have built-in actionability checks. They automatically wait for the element to be visible, enabled, and stable. **Do not call `waitFor()` before an action** — it is redundant and adds unnecessary coupling.

```javascript
// ✅ correct — actionability check is built in
await page.getByRole('button', { name: 'Submit' }).click();

// ❌ wrong — waitFor() before an interaction is redundant
await page.getByRole('button', { name: 'Submit' }).waitFor({ state: 'visible' });
await page.getByRole('button', { name: 'Submit' }).click();
```

`waitFor()` is only appropriate when asserting an element's state **without** interacting with it (e.g., checking that a confirmation message appeared).

## No `waitForLoadState()` after navigation or clicks

Do not call `waitForLoadState()` after `page.goto()` or after clicking a link/button. Instead, interact directly with the first element you expect on the new page — the locator's actionability checks handle the waiting automatically.

```javascript
// ✅ correct — just interact with what you expect next
await page.goto('https://example.com/login');
await page.getByLabel('Username').fill('user');

// ❌ wrong — waitForLoadState adds a slow, brittle wait
await page.goto('https://example.com/login');
await page.waitForLoadState('networkidle');
await page.getByLabel('Username').fill('user');
```

## Assertions — use `expect()` from k6-testing, not `check()`

k6-testing `expect()` provides auto-retrying matchers purpose-built for browser locators. They replace the verbose `waitFor()` → `isVisible()` → `check()` anti-pattern:

```javascript
import { expect } from 'https://jslib.k6.io/k6-testing/0.6.1/index.js';

// ✅ correct — one line, auto-retries until visible or timeout
await expect(page.getByText('Rated!')).toBeVisible();
await expect(page.locator('#result')).toContainText('Success');
await expect(page).toHaveTitle(/Dashboard/);

// ❌ wrong — verbose, redundant (if waitFor succeeds, isVisible is always true)
const el = page.getByText('Rated!');
await el.waitFor({ state: 'visible', timeout: 5000 });
check(await el.isVisible(), { 'visible': (v) => v === true });
```

Available retrying matchers:
- `toBeVisible()`, `toBeHidden()`, `toBeEnabled()`, `toBeChecked()`
- `toHaveText(text)`, `toContainText(text)`
- `toHaveAttribute(name, value)`, `toHaveValue(value)`
- `toHaveTitle(titleOrRegex)` (on page objects)

Use `expect()` for browser correctness assertions. When you need a metric-tracked `check()` in a browser script, the standard `import { check } from 'k6'` works fine inside async functions **as long as the predicate is synchronous** — `await` the value first, then check it:

```javascript
import { check } from 'k6';

// ✅ standard check on an already-awaited value — works in async functions
const title = await page.title();
check(title, { 'has title': (t) => t.length > 0 });

// ❌ standard check does NOT await async predicates — a returned Promise is
// always truthy, so the check silently "passes":
// check(page, { 'title ok': async (p) => (await p.title()).length > 0 });
```

Prefer `expect()` for assertions. Only reach for the k6-utils wrapper (`import { check } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js'`) when the predicate itself must `await` something — otherwise use the standard import, which avoids an unnecessary CDN dependency.

## UI text — verbatim when the user quotes it, forgiving regex when inferring

When the user's prompt quotes exact UI text (e.g. *make sure you see "Rated!"*), use that string **verbatim** in locators and assertions — the user has verified it, and the literal string documents intent precisely.

Exact button/link copy you're *inferring* from a loose description is easy to get wrong ("Love it" vs "Love it!", casing, trailing punctuation). When you haven't confirmed the exact string on the live page, match with a case-insensitive regex instead of a string literal:

```javascript
// ✅ resilient — survives punctuation and casing differences
await page.getByRole('button', { name: /love it/i }).click();

// ❌ brittle — times out if the real label is "Love it!"
await page.getByRole('button', { name: 'Love it' }).click();
```

When a validation run fails on a locator, k6's error output names the exact locator it timed out waiting for — read it, fix the selector, and re-validate. A functional test whose validation run still has failing assertions is not done: the deliverable is a script that passes.

## Other rules

- **User delays**: use `page.waitForTimeout()` not `sleep()` in browser scripts
- **Page cleanup**: `page.close()` must be in a `finally` block
- **Cookie banners**: dismiss consent dialogs before interacting
- **Time series**: avoid high-cardinality tags on browser metrics

If issues found: fix and re-validate. Minor style issues: note but do not re-validate.
docs-guidance.md 2.6 KB
# k6 Docs Lookup Guidance

Use this file when you need to look up k6 documentation with the docs subcommand.
`DOCS_CMD` is established in Step 3 of `SKILL.md` — substitute it in the commands below.

> **Important:** `DOCS_CMD` must include the `script` TTY wrapper set up in
> Step 3. Without it, every invocation returns a generic "browse files" guide
> instead of actual content.
>
> Two rules that must both be followed on every call:
> 1. **Redirect stderr** — AER provisioning log lines go to stderr; merging them
>    with `2>&1` injects noise before the content and can cause the preamble to
>    look like a failure: `$DOCS_CMD <path> 2>/dev/null`
> 2. **Never pipe through `head`** — docs pages are long; truncating with
>    `| head -N` cuts off the actual API content and leaves only the preamble,
>    making the output look like the "browse files" fallback even when the tool
>    is working correctly.

---

## Commands

```
$DOCS_CMD 2>/dev/null                        # overview of all topics
$DOCS_CMD <path> 2>/dev/null                 # read a topic; shows content + subtopics at the bottom
$DOCS_CMD <path> --depth 2 2>/dev/null      # read a topic + 2 levels of subtopics in one call
$DOCS_CMD search <term> 2>/dev/null         # fuzzy search; returns matching paths
```

Paths use spaces or slashes interchangeably.

## Strategy

**2 calls is the target.**

Try a direct path first — wrong paths don't error, they return subtopics to
guide your next call. Only use search or overview when you have no idea where
to look.

Once you have a path (from a subtopics list or search), go to it directly —
don't visit the parent to confirm first.

When a topic page shows a method table with descriptions, that is the complete
API — no need to read individual method sub-pages.

## Rules

- Full parent path required: `using-k6 thresholds` works, `thresholds` alone fails.
- `k6-` prefix is auto-added on `javascript-api` paths where needed.

## Common paths

| Need | Path |
|------|------|
| HTTP | `javascript-api k6-http` |
| Browser | `javascript-api k6-browser` |
| WebSocket | `javascript-api k6-websockets` |
| gRPC | `javascript-api k6-net-grpc` |
| Custom metrics | `javascript-api k6-metrics` |
| SharedArray | `javascript-api k6-data` |
| Execution info | `javascript-api k6-execution` |
| Crypto | `javascript-api k6-crypto` |
| Encoding | `javascript-api k6-encoding` |
| HTML parsing | `javascript-api k6-html` |
| Scenarios/Executors | `using-k6 scenarios` |
| Thresholds | `using-k6 thresholds` |
| Checks | `using-k6 checks` |
| Test lifecycle | `using-k6 test-lifecycle` |
| Cloud run | `cloud` |
| Best practices | `$DOCS_CMD best-practices` |
examples/
browser.js 3.5 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 browser example — k6/browser with expect() assertions
 *
 * Covers: browser.newPage(), goto(), getBy* APIs, locator(),
 *         expect() retrying assertions, try/finally page.close(),
 *         shared-iterations scenario with browser options
 *
 * ELEMENT SELECTION — use getBy* APIs as the first choice:
 *   page.getByRole('button', { name: 'Submit' })  ← preferred for interactive elements
 *   page.getByRole('button', { name: /submit/i }) ← regex when inferring UI copy you haven't
 *                                                    verified (punctuation/casing won't break it);
 *                                                    text the user quotes verbatim stays literal
 *   page.getByLabel('Username')                    ← preferred for labelled inputs
 *   page.getByText('Rated!')                       ← preferred for text content
 *   page.getByTestId('pizza-btn')                  ← preferred when data-testid exists
 *   page.getByPlaceholder('Enter email')           ← preferred for placeholder inputs
 *   page.locator('#id')                            ← fallback: stable ID attribute
 *   page.locator('button').first()                 ← last resort only — no context
 *
 * ASSERTIONS — use expect() from k6-testing, NOT check() from k6:
 *   expect() on browser locators auto-retries until timeout, replacing the
 *   verbose waitFor() + isVisible() + check() pattern.
 *   Retrying matchers: toBeVisible, toBeHidden, toBeEnabled, toBeChecked,
 *     toHaveText, toContainText, toHaveAttribute, toHaveValue, toHaveTitle
 *
 *   For a metric-tracked check(), the standard import { check } from 'k6'
 *   works inside async functions — await the value first, then check it with
 *   a sync predicate. Only use the k6-utils jslib check when the predicate
 *   itself must await something.
 *
 * LOCATOR ACTIONABILITY — locators have built-in waits:
 *   - Do NOT call waitFor() before interacting (click, fill, etc.)
 *   - Do NOT use waitForLoadState() after navigation or clicks
 *   - Just interact with the next element you expect — locators wait automatically
 *
 * IMPORTANT:
 * - Default function MUST be async
 * - Do NOT use --vus or --iterations CLI flags — options.scenarios controls load
 * - browser options go inside the scenario, not at the top level
 */
import { expect } from 'https://jslib.k6.io/k6-testing/0.6.1/index.js';
import { browser } from 'k6/browser';

export const options = {
  scenarios: {
    default: {
      executor: 'shared-iterations',
      options: {
        browser: { type: 'chromium' },
      },
    },
  },
};

export default async function () {
  const page = await browser.newPage();

  try {
    await page.goto('https://quickpizza.grafana.com');
    await page.screenshot({ path: 'screenshots/1-homepage.png' });

    // getBy* locators wait automatically — no waitFor() needed before click()
    await page.getByRole('button', { name: 'Pizza, Please!' }).click();
    await page.screenshot({ path: 'screenshots/2-after-click.png' });

    await page.getByRole('button', { name: 'Love it!' }).click();

    // expect() auto-retries on browser locators — replaces waitFor + isVisible + check
    await expect(page.getByText('Rated!')).toBeVisible();
    await page.screenshot({ path: 'screenshots/3-rated.png' });

    // Other useful retrying assertions:
    // await expect(page).toHaveTitle(/QuickPizza/);
    // await expect(page.locator('#result')).toContainText('Success');
  } finally {
    await page.close();
  }
}
cloud.js 2.0 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 cloud execution example
 *
 * Covers: cloud options (cloud run), multi-region distribution,
 *         k6 cloud run and k6 cloud run --local-execution
 *
 * Run commands:
 *   k6 cloud login --token <YOUR_API_TOKEN>
 *   k6 cloud run k6/scripts/cloud-test.js           # remote execution
 *   k6 cloud run --local-execution k6/scripts/cloud-test.js  # hybrid
 *
 * The script itself is identical for both run modes.
 * --local-execution is a CLI flag only — it runs the test on your machine
 * but streams results to Grafana Cloud for storage and dashboarding.
 *
 * Get your projectID from app.k6.io → project settings.
 */
import http from 'k6/http';
import { check, sleep } from 'k6';

const BASE_URL = 'https://quickpizza.grafana.com';

export const options = {
  // ── Cloud-specific configuration ────────────────────────────────────────
  cloud: {
    projectID: 1234567,                    // replace with your project ID
    name: 'QuickPizza Cloud Load Test',

    // Optional: multi-region distribution (percentages must sum to 100)
    distribution: {
      'amazon:us:ashburn': { loadZone: 'amazon:us:ashburn', percent: 60 },
      'amazon:eu:dublin':  { loadZone: 'amazon:eu:dublin',  percent: 40 },
    },
  },

  // ── Load configuration (same as local) ──────────────────────────────────
  scenarios: {
    cloud_load: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '2m', target: 50  },  // ramp up
        { duration: '5m', target: 50  },  // hold
        { duration: '1m', target: 0   },  // ramp down
      ],
      gracefulRampDown: '30s',
    },
  },

  thresholds: {
    http_req_duration: ['p(95)<500'],
    http_req_failed:   ['rate<0.01'],
  },
};

export default function () {
  const res = http.get(`${BASE_URL}/api/quotes`);
  check(res, {
    'status 200':  (r) => r.status === 200,
    'has quotes':  (r) => r.json('quotes') != null, // loose != also catches undefined
  });
  sleep(1);
}
crypto-encoding.js 2.2 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 crypto and encoding example
 *
 * Covers: k6/crypto (hmac, md5, sha256, randomBytes),
 *         k6/encoding (b64encode, b64decode),
 *         request signing, Basic Auth, request ID generation
 *
 * All crypto functions are synchronous and available in k6/crypto.
 * No import needed for the global WebCrypto API (crypto.getRandomValues etc.)
 */
import { hmac, md5, sha256, randomBytes } from 'k6/crypto';
import encoding from 'k6/encoding';
import http from 'k6/http';
import { check, sleep } from 'k6';

const BASE_URL = 'https://quickpizza.grafana.com';
const SECRET   = 'my-signing-secret';

export const options = {
  vus: 3,
  duration: '20s',
  thresholds: {
    http_req_duration: ['p(95)<500'],
    checks:            ['rate>0.99'],
  },
};

export default function () {
  // ── Unique request ID ─────────────────────────────────────────────────
  const reqId = encoding.b64encode(randomBytes(16));

  // ── Request body + HMAC signature ─────────────────────────────────────
  const body = JSON.stringify({ action: 'get_quotes', ts: Date.now() });
  const signature = hmac('sha256', SECRET, body, 'hex');

  // ── MD5 content hash (e.g. for ETag / integrity checks) ───────────────
  const contentHash = md5(body, 'hex');

  // ── Basic Auth via base64 ─────────────────────────────────────────────
  const credentials = encoding.b64encode('apiuser:apipassword');

  // ── SHA-256 password hash example ─────────────────────────────────────
  const passwordHash = sha256('userpassword', 'hex');

  const res = http.get(`${BASE_URL}/api/quotes`, {
    headers: {
      'X-Request-ID':   reqId,
      'X-Signature':    signature,
      'X-Content-Hash': contentHash,
      'Authorization':  `Basic ${credentials}`,
    },
  });

  check(res, {
    'status 200':      (r) => r.status === 200,
    'req-id non-empty': () => reqId.length > 0,
    'sig non-empty':    () => signature.length > 0,
  });

  // ── Decode example ────────────────────────────────────────────────────
  const decoded = encoding.b64decode(reqId, 'rawurl', 's');
  console.log(`VU ${__VU} | reqId_len=${reqId.length} | hash=${contentHash.substring(0, 8)}...`);

  sleep(1);
}
executors.js 3.4 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 executors and load patterns example
 *
 * Covers all 7 executors with realistic configuration examples.
 * Pick the relevant scenario block and remove the others.
 *
 * Executors:
 *   constant-vus          — fixed VU count for a duration
 *   ramping-vus           — variable VU count (realistic traffic curves)
 *   constant-arrival-rate — fixed iteration rate (RPS), regardless of response time
 *   ramping-arrival-rate  — variable RPS over time
 *   per-vu-iterations     — each VU runs N iterations exactly
 *   shared-iterations     — total iteration budget shared across VUs
 *   externally-controlled — VU count controlled at runtime via k6 REST API
 */
import http from 'k6/http';
import { check, sleep } from 'k6';

const BASE_URL = 'https://quickpizza.grafana.com';

// ── Choose ONE scenario block for your script ────────────────────────────────

export const options = {

  // ── 1. constant-vus: steady load for a fixed duration ──────────────────
  // scenarios: {
  //   steady: { executor: 'constant-vus', vus: 10, duration: '30s' },
  // },

  // ── 2. ramping-vus: dinner-time peak for a takeaway site ───────────────
  scenarios: {
    dinner_rush: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '10m', target: 20  },  // 5–6pm: background traffic
        { duration: '15m', target: 80  },  // 6–7pm: building
        { duration: '30m', target: 150 },  // 7–8pm: dinner peak
        { duration: '15m', target: 40  },  // 8–9pm: tapering
        { duration: '10m', target: 0   },  // 9pm: quiet
      ],
      gracefulRampDown: '2m',
    },
  },

  // ── 3. constant-arrival-rate: fixed RPS (e.g. 30 orders/sec) ──────────
  // scenarios: {
  //   steady_orders: {
  //     executor: 'constant-arrival-rate',
  //     rate: 30,
  //     timeUnit: '1s',        // 30 iterations per second
  //     duration: '5m',
  //     preAllocatedVUs: 50,   // initial VU pool
  //     maxVUs: 200,           // hard cap
  //   },
  // },

  // ── 4. ramping-arrival-rate: variable RPS ─────────────────────────────
  // scenarios: {
  //   lunch_ramp: {
  //     executor: 'ramping-arrival-rate',
  //     startRate: 5,
  //     timeUnit: '1s',
  //     stages: [
  //       { duration: '3m', target: 50 },
  //       { duration: '5m', target: 50 },
  //       { duration: '2m', target: 0  },
  //     ],
  //     preAllocatedVUs: 30,
  //     maxVUs: 150,
  //   },
  // },

  // ── 5. per-vu-iterations: each VU completes a full user journey ────────
  // scenarios: {
  //   user_journey: {
  //     executor: 'per-vu-iterations',
  //     vus: 10,
  //     iterations: 5,     // each VU runs exactly 5 times
  //     maxDuration: '5m',
  //   },
  // },

  // ── 6. shared-iterations: fixed total budget shared across VUs ─────────
  // scenarios: {
  //   smoke: {
  //     executor: 'shared-iterations',
  //     vus: 5,
  //     iterations: 50,
  //     maxDuration: '2m',
  //   },
  // },

  // ── 7. externally-controlled: VU count set via k6 REST API ─────────────
  // scenarios: {
  //   dynamic: {
  //     executor: 'externally-controlled',
  //     vus: 10,
  //     maxVUs: 100,
  //     duration: '10m',
  //   },
  // },

  thresholds: {
    http_req_duration: ['p(95)<1000'],
    http_req_failed:   ['rate<0.02'],
  },
};

export default function () {
  const res = http.get(`${BASE_URL}/api/quotes`);
  check(res, { 'status 200': (r) => r.status === 200 });
  sleep(1);
}
ext-crawler.js 1.1 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * xk6-crawler — web crawling
 *
 * Build: xk6 build --with github.com/grafana/xk6-crawler@latest -o ./k6-with-crawler
 * Run:   ./k6-with-crawler run k6/scripts/crawler-test.js
 *
 * crawler.crawl(url) fetches the page and extracts the title and all links.
 * Returns: { title: string, links: string[] }
 * It is async — use await.
 */
import { Crawler } from 'k6/x/crawler';
import { check } from 'k6';

export const options = {
  vus: 1,
  iterations: 1,
  thresholds: {
    checks: ['rate==1'],
  },
};

export default async function () {
  const crawler = new Crawler();
  const result = await crawler.crawl('https://quickpizza.grafana.com');

  check(result, {
    'has title':       (r) => r.title && r.title.length > 0,
    'has links':       (r) => r.links && r.links.length > 0,
    'title not empty': (r) => r.title.trim() !== '',
  });

  console.log(`Title: "${result.title}" | Links found: ${result.links.length}`);
  // Log first few links
  result.links.slice(0, 3).forEach(link => console.log(' -', link));
}
ext-dns.js 1.3 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * xk6-dns — DNS resolution
 *
 * Build: xk6 build --with github.com/grafana/xk6-dns@latest -o ./k6-with-dns
 * Run:   ./k6-with-dns run k6/scripts/dns-test.js
 *
 * Two methods — both return Promise<string[]> (array of IP addresses):
 *
 *   dns.lookup(host)
 *     Uses the system's default DNS resolver. Simplest option — no nameserver needed.
 *
 *   dns.resolve(host, recordType, nameserver)
 *     Uses a specific DNS server (e.g. '8.8.8.8:53'). recordType: 'A', 'AAAA', 'CNAME', etc.
 *
 * Both are async — use await.
 */
import dns from 'k6/x/dns';
import { check } from 'k6';

export const options = {
  scenarios: {
    dns_check: {
      executor: 'shared-iterations',
      vus: 1,
      iterations: 1,
    },
  },
  thresholds: {
    checks: ['rate==1'],
  },
};

export default async function () {
  const host = 'quickpizza.grafana.com';

  // System DNS lookup (simplest)
  const ips = await dns.lookup(host);
  check(ips, {
    'lookup resolved':     (r) => r !== null && r.length > 0,
  });
  console.log(`${host} system DNS: ${JSON.stringify(ips)}`);

  // Custom nameserver lookup
  const ips2 = await dns.resolve(host, 'A', '8.8.8.8:53');
  check(ips2, {
    'resolve via 8.8.8.8': (r) => r !== null && r.length > 0,
  });
  console.log(`${host} via 8.8.8.8: ${JSON.stringify(ips2)}`);
}
ext-exec.js 1.0 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * xk6-exec — run external shell commands from k6 scripts
 *
 * Build: xk6 build --with github.com/grafana/xk6-exec@latest -o ./k6-with-exec
 * Run:   ./k6-with-exec run k6/scripts/exec-test.js
 *
 * Use cases: health-check scripts, data setup, calling CLIs.
 * exec.command(cmd, args) blocks until the command completes and returns stdout.
 */
import exec from 'k6/x/exec';
import http from 'k6/http';
import { check } from 'k6';

export const options = {
  vus: 1,
  iterations: 3,
};

export function setup() {
  // Run a setup command before the test
  const out = exec.command('echo', ['k6 exec test starting']);
  console.log('setup:', out.trim());
}

export default function () {
  // Run a command and use its output
  const timestamp = exec.command('date', ['+%s']).trim();

  const res = http.get(`https://quickpizza.grafana.com/api/quotes`);
  check(res, { 'status 200': (r) => r.status === 200 });

  console.log(`[${timestamp}] VU ${__VU}: status=${res.status}`);
}
ext-faker.js 1.3 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * xk6-faker — fake data generation
 *
 * Build: xk6 build --with github.com/grafana/xk6-faker@latest -o ./k6-with-faker
 * Run:   ./k6-with-faker run k6/scripts/faker-test.js
 */
import { Faker } from 'k6/x/faker';
import http from 'k6/http';
import { check, sleep } from 'k6';

// Seeded for reproducibility. Change seed to get different (but stable) data.
const fake = new Faker(42);

export const options = {
  vus: 5,
  duration: '20s',
  thresholds: {
    http_req_duration: ['p(95)<1000'],
    checks:            ['rate>0.95'],
  },
};

export default function () {
  // Generate a unique username by appending VU+timestamp to the fake name
  const username = `${fake.internet.username()}_${__VU}_${Date.now()}`;
  const user = {
    username,
    password: 'pass123',
    name: `${fake.person.firstName()} ${fake.person.lastName()}`,
    email: fake.internet.email(),
  };

  const res = http.post(
    'https://quickpizza.grafana.com/api/users',
    JSON.stringify({ username: user.username, password: user.password }),
    { headers: { 'Content-Type': 'application/json' } },
  );

  check(res, {
    'registered 201': (r) => r.status === 201,
  });

  console.log(`VU ${__VU} registered: ${user.username} (${user.name})`);
  sleep(1);
}
ext-redis.js 1.8 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * xk6-redis — Redis client
 *
 * Build: xk6 build --with github.com/grafana/xk6-redis@latest -o ./k6-with-redis
 * Run:   ./k6-with-redis run k6/scripts/redis-test.js
 *
 * IMPORTANT API NOTES:
 * - Constructor takes a URL string: new redis.Client('redis://localhost:6379')
 *   Do NOT pass an options object — that will throw.
 * - All methods are async — use await.
 * - client.get() throws 'redis: nil' when the key does not exist.
 *   Wrap in try/catch and check e.message for 'redis: nil' to handle cache misses.
 */
import redis from 'k6/x/redis';
import { Counter } from 'k6/metrics';
import http from 'k6/http';
import { check, sleep } from 'k6';

const client = new redis.Client('redis://localhost:6379');
const cacheHits = new Counter('cache_hits');

export const options = {
  vus: 5,
  duration: '30s',
  thresholds: {
    http_req_duration: ['p(95)<2000'],
    checks:            ['rate>0.95'],
    // cache_hits threshold only meaningful across multiple iterations
    // cache_hits: ['count>0'],
  },
};

export default async function () {
  const cacheKey = 'quickpizza:quotes';
  let body;

  try {
    // Cache hit path — get() throws 'redis: nil' on miss
    body = await client.get(cacheKey);
    cacheHits.add(1);
    console.log('cache hit');
  } catch (e) {
    if (e.message && e.message.includes('redis: nil')) {
      // Cache miss — fetch from API and store with 30s TTL
      const res = http.get('https://quickpizza.grafana.com/api/quotes');
      check(res, { 'api 200': (r) => r.status === 200 });
      body = res.body;
      await client.set(cacheKey, body, 30);
      console.log('cache miss, stored');
    } else {
      throw e; // unexpected Redis error
    }
  }

  check(body, { 'got value': (b) => b != null && b.length > 0 });
  sleep(1);
}
ext-sql.js 2.1 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * xk6-sql + sqlite3 driver — SQL database client
 *
 * Build: CGO_ENABLED=1 xk6 build \
 *          --with github.com/grafana/xk6-sql@latest \
 *          --with github.com/grafana/xk6-sql-driver-sqlite3@latest \
 *          -o ./k6-with-sql
 * Run:   ./k6-with-sql run k6/scripts/sql-test.js
 *
 * For other databases, replace the driver import:
 *   postgres: 'k6/x/sql/driver/postgres'
 *   mysql:    'k6/x/sql/driver/mysql'
 *
 * IMPORTANT API NOTES:
 * - db.query() returns a plain JavaScript ARRAY of row objects.
 *   NOT a ResultSet with .next() — that does not exist.
 *   Access rows like: rows[0].column_name
 * - db.exec(query, ...args) uses positional ? placeholders.
 * - SQLite requires CGO_ENABLED=1 at build time.
 */
import sql from 'k6/x/sql';
import driver from 'k6/x/sql/driver/sqlite3';
import http from 'k6/http';
import { check, sleep } from 'k6';

const db = sql.open(driver, '/tmp/k6_results.db');

export const options = {
  vus: 3,
  duration: '20s',
  thresholds: {
    http_req_duration: ['p(95)<1000'],
    checks:            ['rate>0.95'],
  },
};

export function setup() {
  // Drop and recreate for a clean run
  db.exec('DROP TABLE IF EXISTS results');
  db.exec(`CREATE TABLE results (
    id       INTEGER PRIMARY KEY AUTOINCREMENT,
    endpoint TEXT,
    status   INTEGER,
    duration REAL,
    ts       TEXT
  )`);
}

export default function () {
  const res = http.get('https://quickpizza.grafana.com/api/quotes');

  db.exec(
    'INSERT INTO results (endpoint, status, duration, ts) VALUES (?, ?, ?, ?)',
    '/api/quotes',
    res.status,
    res.timings.duration,
    new Date().toISOString(),
  );

  check(res, { 'status 200': (r) => r.status === 200 });
  sleep(1);
}

export function teardown() {
  // db.query() returns a plain array — access rows[0].column_name
  const rows = db.query('SELECT count(*) as cnt FROM results');
  console.log(`Total results recorded: ${rows[0].cnt}`);

  const slowRows = db.query('SELECT endpoint, duration FROM results WHERE duration > 500');
  if (slowRows.length > 0) {
    console.log(`Slow requests (>500ms): ${slowRows.length}`);
  }
}
ext-tcp.js 1.6 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * xk6-tcp — raw TCP connections
 *
 * Build: xk6 build --with github.com/grafana/xk6-tcp@latest -o ./k6-with-tcp
 * Run:   ./k6-with-tcp run k6/scripts/tcp-test.js
 *
 * IMPORTANT API NOTES:
 * - open() does NOT exist — use new tcp.Socket()
 * - The API mirrors Node.js net.Socket: event-driven with socket.on(event, handler)
 * - socket.connect(port, host) — note port FIRST, then host (not a URL string)
 * - socket.destroy() closes the connection
 * - Must be async — use await with a Promise that resolves on the 'close' event
 *
 * Events: 'connect', 'data', 'close', 'error', 'timeout'
 */
import tcp from 'k6/x/tcp';
import { check } from 'k6';

export const options = {
  scenarios: {
    tcp_check: {
      executor: 'shared-iterations',
      vus: 1,
      iterations: 1,
    },
  },
  thresholds: {
    checks: ['rate==1'],
  },
};

export default async function () {
  const socket = new tcp.Socket();
  let connected = false;

  socket.on('connect', () => {
    connected = true;
    console.log('TCP connected to quickpizza.grafana.com:443');
    socket.destroy(); // close immediately — we only need to verify connectivity
  });

  socket.on('error', (err) => {
    console.error('TCP error:', err);
  });

  // Wait for the connection lifecycle to complete before the function returns
  await new Promise((resolve) => {
    socket.on('close', resolve);
    // connect(port, host) — port first
    socket.connect(443, 'quickpizza.grafana.com');
  });

  check(connected, {
    'tcp connected': (v) => v === true,
  });
}
ext-tls.js 1.2 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * xk6-tls — TLS certificate inspection
 *
 * Build: xk6 build --with github.com/grafana/xk6-tls@latest -o ./k6-with-tls
 * Run:   ./k6-with-tls run k6/scripts/tls-test.js
 *
 * IMPORTANT API NOTES:
 * - getCertificate(host) — async, takes the hostname ONLY (no port argument).
 * - cert.expires is a millisecond timestamp — compare with Date.now(), not new Date().
 *   Do NOT use cert.notAfter — that property does not exist.
 */
import tls from 'k6/x/tls';
import { check } from 'k6';

export const options = {
  scenarios: {
    tls_check: {
      executor: 'shared-iterations',
      vus: 1,
      iterations: 1,
    },
  },
  thresholds: {
    checks: ['rate==1'],
  },
};

export default async function () {
  const host = 'quickpizza.grafana.com';

  // No port argument — just the hostname
  const cert = await tls.getCertificate(host);

  check(cert, {
    'cert not expired':     (c) => c.expires > Date.now(),
    'cert expires > 7 days': (c) => c.expires > Date.now() + 7 * 24 * 60 * 60 * 1000,
  });

  const expiresAt = new Date(cert.expires).toISOString();
  console.log(`${host} TLS cert expires: ${expiresAt}`);
}
functional.js 3.2 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 functional test example — k6-testing library
 *
 * Covers: expect() for HTTP assertions, expect(page/locator) for browser
 *         with automatic retry, multi-scenario script with named exec functions,
 *         HTTP + browser in the same script
 *
 * Use this pattern for functional/integration tests instead of check().
 * expect() on browser locators/pages automatically retries until timeout.
 *
 * Key matchers:
 *   HTTP values (instant): toEqual, toBe, toContain, toBeDefined, toBeTruthy,
 *                          toBeGreaterThan, toBeLessThan, toHaveLength, toHaveProperty
 *   Browser (retrying):    toBeVisible, toBeHidden, toBeEnabled, toBeChecked,
 *                          toHaveText, toContainText, toHaveAttribute, toHaveValue,
 *                          toHaveTitle (on page objects)
 *   Non-throwing:          expect.soft(value).toEqual(...) — collects all failures
 *
 * LOCATOR ACTIONABILITY:
 *   - Do NOT call waitFor() before interacting (click, fill, select). Locators
 *     automatically wait for visibility, enabled state, and stability.
 *   - Only use waitFor() when asserting an element state WITHOUT interacting with it.
 *   - Do NOT use waitForLoadState(). Interact directly with the next element you
 *     expect — actionability checks handle the waiting.
 */
import { expect } from 'https://jslib.k6.io/k6-testing/0.6.1/index.js';
import { browser } from 'k6/browser';
import http from 'k6/http';

const BASE_URL = 'https://quickpizza.grafana.com';

export const options = {
  scenarios: {
    http_functional: {
      executor: 'shared-iterations',
      vus: 1,
      iterations: 1,
      exec: 'httpTest',
    },
    browser_functional: {
      executor: 'shared-iterations',
      vus: 1,
      iterations: 1,
      exec: 'browserTest',
      options: {
        browser: { type: 'chromium' },
      },
    },
  },
};

// ── HTTP functional test ──────────────────────────────────────────────────────
export function httpTest() {
  const res = http.get(`${BASE_URL}/api/quotes`);

  // Instant assertions (no retry)
  expect(res.status).toEqual(200);
  expect(res.json('quotes')).toBeDefined();
  expect(res.timings.duration).toBeLessThan(2000);

  // Soft assertions — collects all failures instead of throwing on first
  expect.soft(res.headers['Content-Type']).toContain('application/json');
}

// ── Browser functional test ───────────────────────────────────────────────────
export async function browserTest() {
  const page = await browser.newPage();

  try {
    // Navigate — no waitForLoadState(). Interact directly with elements
    // on the new page; actionability checks handle the waiting.
    await page.goto(BASE_URL);

    // Page-level retrying assertion (not an interaction — waitFor is via expect)
    await expect(page).toHaveTitle(/QuickPizza/);

    // Click directly — no waitFor() needed before interacting with a locator.
    // getByRole automatically waits for the button to be visible and enabled.
    await page.getByRole('button', { name: 'Pizza, Please!' }).click();

    // Assert the result appeared (not interacting — waitFor via expect is correct)
    await expect(page.getByText('Our recommendation:')).toBeVisible();

  } finally {
    await page.close();
  }
}
grpc.js 2.2 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 gRPC example — k6/net/grpc
 *
 * Covers: Client, load(), connect(), invoke(), StatusOK, close() in finally,
 *         plaintext and TLS connections, thresholds, check()
 *
 * IMPORTANT: client.load() paths are resolved relative to the SCRIPT FILE
 * location, not the working directory. Place the .proto file next to the
 * script, or adjust the path accordingly.
 *
 * For servers with gRPC reflection: use client.load(null) and connect
 * with { reflect: true } instead of providing a proto file.
 */
import { Client, StatusOK } from 'k6/net/grpc';
import { check, sleep } from 'k6';

// Load proto relative to this script file's location
const client = new Client();
client.load(['./proto'], 'quickpizza.proto');
// Reflection alternative: client.load(null);

const GRPC_ADDR = 'localhost:3334'; // plaintext
// const GRPC_ADDR = 'api.example.com:443'; // TLS (remove plaintext: true below)

export const options = {
  vus: 3,
  duration: '20s',
  thresholds: {
    grpc_req_duration: ['p(95)<500'],
    checks:            ['rate>0.99'],
  },
};

export default function () {
  // Connect (with plaintext for local/dev servers without TLS)
  client.connect(GRPC_ADDR, { plaintext: true });
  // TLS: client.connect(GRPC_ADDR);

  try {
    // ── Unary call: Status check ────────────────────────────────────────────
    const statusRes = client.invoke('quickpizza.GRPC/Status', {});
    check(statusRes, {
      'status ok':    (r) => r && r.status === StatusOK,
      'service ready': (r) => r && r.message && r.message.ready === true,
    });

    // ── Unary call: RatePizza ───────────────────────────────────────────────
    const ratingRes = client.invoke('quickpizza.GRPC/RatePizza', {
      ingredients: ['Pepperoni', 'Mozzarella'],
      dough: 'Traditional',
    });
    check(ratingRes, {
      'rating ok':      (r) => r && r.status === StatusOK,
      'stars in range': (r) => r && r.message &&
                               r.message.starsRating >= 1 &&
                               r.message.starsRating <= 5,
    });
  } finally {
    // Release the connection even if invoke() or a check throws mid-iteration.
    client.close();
  }

  sleep(1);
}
html.js 2.0 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 HTML parsing + SharedArray example — k6/html + k6/data
 *
 * Covers: parseHTML(), jQuery-style selectors (.find, .text, .size, .toArray),
 *         SharedArray (inline array, loaded once at init time)
 *
 * IMPORTANT: QuickPizza's root URL (/) is a SvelteKit SPA.
 * Its server-rendered HTML shell contains NO <button>, <form>, or visible
 * content — those are injected by JavaScript at runtime, which k6's HTTP
 * client does not execute. Use /login or API endpoints when testing with
 * parseHTML, as those pages have server-rendered content.
 */
import { parseHTML } from 'k6/html';
import { SharedArray } from 'k6/data';
import http from 'k6/http';
import { check, sleep } from 'k6';

const BASE_URL = 'https://quickpizza.grafana.com';

// SharedArray: loaded ONCE at init time, shared read-only across all VUs.
// Replace with JSON.parse(open('./endpoints.json')) to load from a file.
const endpoints = new SharedArray('endpoints', () => [
  '/api/quotes',
  '/api/names',
  '/api/adjectives',
]);

export const options = {
  vus: 5,
  duration: '30s',
  thresholds: {
    http_req_duration: ['p(95)<500'],
    checks:            ['rate>0.95'],
  },
};

export default function () {
  // ── Pick endpoint via SharedArray ─────────────────────────────────────────
  const path = endpoints[__VU % endpoints.length];
  const apiRes = http.get(`${BASE_URL}${path}`);
  check(apiRes, { 'api status 200': (r) => r.status === 200 });

  // ── HTML parsing — use /login, NOT / (which is a JS SPA) ──────────────────
  const htmlRes = http.get(`${BASE_URL}/login`);
  const doc = parseHTML(htmlRes.body);

  check(doc, {
    'has button':   (d) => d.find('button').size() > 0,
    'has heading':  (d) => d.find('h1').size() > 0,
  });

  // Extract text content
  const heading = doc.find('h1').text();
  const buttons = doc.find('button').toArray().map(el => el.text().trim());
  console.log(`VU ${__VU} | endpoint=${path} | heading="${heading}" | buttons=${buttons.join(',')}`);

  sleep(1);
}
http.js 3.3 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 HTTP example — load test + authenticated flow
 *
 * Covers: http.get/post/batch, check(), sleep(), thresholds,
 *         auth token flow, JSON body, SharedArray
 *
 * Adapt BASE_URL, endpoints, and credentials to your target.
 * Keep it lean: add per-request tags ({ tags: { endpoint: 'x' } }) or extra
 * sleep() calls only when the user asks for them.
 */
import http from 'k6/http';
import { check, sleep, fail } from 'k6';
import { SharedArray } from 'k6/data';

const BASE_URL = 'https://quickpizza.grafana.com';

// SharedArray is loaded once at init time and shared across all VUs (read-only).
const users = new SharedArray('users', () => [
  { username: 'alice', password: 'pass1' },
  { username: 'bob',   password: 'pass2' },
]);

export const options = {
  vus: 10,
  duration: '30s',
  thresholds: {
    http_req_duration: ['p(95)<500', 'p(99)<1000'],
    http_req_failed:   ['rate<0.01'],
    checks:            ['rate>0.99'],
  },
};

export default function () {
  // ── Simple GET ────────────────────────────────────────────────────────────
  const quotesRes = http.get(`${BASE_URL}/api/quotes`);
  check(quotesRes, {
    'quotes status 200': (r) => r.status === 200,
    'quotes has body':   (r) => r.body.length > 0,
  });

  // ── Authenticated flow ────────────────────────────────────────────────────
  // Step 1: register a unique user
  const username = `user_${__VU}_${Date.now()}`;
  const password = 'password123';

  const registerRes = http.post(
    `${BASE_URL}/api/users`,
    JSON.stringify({ username, password }),
    { headers: { 'Content-Type': 'application/json' } },
  );
  check(registerRes, { 'register 201': (r) => r.status === 201 });

  // Step 2: login for a token
  const loginRes = http.post(
    `${BASE_URL}/api/users/token/login`,
    JSON.stringify({ username, password }),
    { headers: { 'Content-Type': 'application/json' } },
  );
  const loginOk = check(loginRes, {
    'login 200':   (r) => r.status === 200,
    'has token':   (r) => r.json('token') != null, // loose != also catches undefined
  });
  if (!loginOk) {
    fail('login failed');
  }
  const token = loginRes.json('token');

  // Step 3: authenticated request
  const authHeaders = {
    'Authorization': `Token ${token}`,
    'Content-Type': 'application/json',
  };

  // Send an explicit empty JSON object — the API rejects a literal null body.
  const pizzaRes = http.post(`${BASE_URL}/api/pizza`, JSON.stringify({}), {
    headers: authHeaders,
  });
  const pizzaOk = check(pizzaRes, {
    'pizza 200':  (r) => r.status === 200,
    'has pizza':  (r) => r.json('pizza') != null, // loose != also catches undefined
  });

  // Step 4: use data from the previous response
  if (pizzaOk) {
    const pizzaId = pizzaRes.json('pizza.id');
    const ratingRes = http.post(
      `${BASE_URL}/api/ratings`,
      JSON.stringify({ stars: 5, pizza_id: pizzaId }),
      { headers: authHeaders },
    );
    check(ratingRes, { 'rating 201': (r) => r.status === 201 });
  }

  // ── Batch requests ────────────────────────────────────────────────────────
  const [r1, r2] = http.batch([
    ['GET', `${BASE_URL}/api/quotes`],
    ['GET', `${BASE_URL}/api/names`],
  ]);
  check(r1, { 'batch quotes 200': (r) => r.status === 200 });
  check(r2, { 'batch names 200':  (r) => r.status === 200 });

  sleep(1);
}
metrics.js 3.6 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 metrics, data, and lifecycle example
 *
 * Covers: Counter, Gauge, Rate, Trend (custom metrics),
 *         SharedArray (shared test data, loaded once),
 *         execution module (VU/scenario runtime info),
 *         per-vu-iterations executor,
 *         setup() / teardown() / handleSummary()
 *
 * Notes:
 * - SharedArray initialiser runs once at init time — keep it cheap.
 * - execution.vu.idInTest is 1-indexed and unique per VU across all scenarios.
 * - handleSummary receives the same data object as the built-in summary.
 * - textSummary comes from the k6-summary jslib (imported below); it is NOT a global.
 */
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Counter, Gauge, Rate, Trend } from 'k6/metrics';
import { SharedArray } from 'k6/data';
import execution from 'k6/execution';
import { textSummary } from 'https://jslib.k6.io/k6-summary/0.1.0/index.js';

// ── Custom metrics ─────────────────────────────────────────────────────────
const requestCount   = new Counter('pizza_requests');          // cumulative count
const activeVUs      = new Gauge('active_vus');                // current value
const successRate    = new Rate('pizza_success_rate');          // 0–1 ratio
const requestTrend   = new Trend('pizza_req_duration_ms', true); // distribution

// ── Shared test data ───────────────────────────────────────────────────────
// Inline array — replace JSON.parse(open('./data.json')) for external files.
const ingredients = new SharedArray('ingredients', () => [
  'Pepperoni',
  'Mozzarella',
  'Mushrooms',
  'Olives',
  'Basil',
]);

export const options = {
  scenarios: {
    user_journey: {
      executor: 'per-vu-iterations',
      vus: 5,
      iterations: 3,        // each VU runs exactly 3 iterations
      maxDuration: '5m',
    },
  },
  thresholds: {
    pizza_success_rate:    ['rate>0.95'],
    pizza_req_duration_ms: ['p(95)<1000', 'avg<500'],
    pizza_requests:        ['count>0'],
  },
};

export function setup() {
  // Runs once before all VUs start. Return value is passed to default + teardown.
  const health = http.get('https://quickpizza.grafana.com/api/quotes');
  if (health.status !== 200) {
    throw new Error(`Service not healthy: ${health.status}`);
  }
  return { baseUrl: 'https://quickpizza.grafana.com', startedAt: Date.now() };
}

export default function (data) {
  // execution gives runtime context
  const vuId        = execution.vu.idInTest;
  const scenarioIter = execution.scenario.iterationInInstance;

  // Pick an ingredient based on VU ID (deterministic)
  const ingredient = ingredients[vuId % ingredients.length];

  activeVUs.add(1);

  const start = Date.now();
  const res = http.get(`${data.baseUrl}/api/quotes`, {
    tags: { vu_id: String(vuId), iteration: String(scenarioIter) },
  });
  const duration = Date.now() - start;

  requestTrend.add(duration);
  requestCount.add(1);

  const ok = check(res, {
    'status 200':  (r) => r.status === 200,
    'has quotes':  (r) => r.json('quotes') !== undefined,
  });
  successRate.add(ok);

  console.log(`VU ${vuId} iter ${scenarioIter} | ${ingredient} | ${duration}ms | ok=${ok}`);

  activeVUs.add(-1);
  sleep(1);
}

export function teardown(data) {
  const elapsed = ((Date.now() - data.startedAt) / 1000).toFixed(1);
  console.log(`Test finished. Elapsed: ${elapsed}s`);
}

export function handleSummary(data) {
  // Return a custom summary. textSummary is imported from the k6-summary jslib above.
  return {
    'k6-summary.json': JSON.stringify(data, null, 2),
    stdout: textSummary(data, { indent: '  ', enableColors: true }),
  };
}
websocket.js 1.9 KB
// Generated by grafana-k6 on {{GENERATED_AT}}
/**
 * k6 WebSocket example — k6/websockets
 *
 * Covers: WebSocket constructor, addEventListener, send/receive/close,
 *         error handling, check(), shared-iterations scenario
 *
 * Note: use k6/websockets for new scripts. Both k6/experimental/websockets
 * (now deprecated) and the older k6/ws are legacy — avoid both.
 * The default function must be synchronous — WebSocket events resolve in the
 * k6 event loop automatically.
 */
import { WebSocket } from 'k6/websockets';
import { check, sleep } from 'k6';

const WS_URL = 'wss://quickpizza.grafana.com/ws';

export const options = {
  scenarios: {
    ws_load: {
      executor: 'shared-iterations',
      vus: 5,
      iterations: 20,
      maxDuration: '2m',
    },
  },
  thresholds: {
    ws_session_duration: ['p(95)<5000'],
    checks:              ['rate>0.95'],
  },
};

export default function () {
  let opened = false;
  let receivedMsg = null;

  const ws = new WebSocket(WS_URL);

  ws.addEventListener('open', () => {
    opened = true;
    // Send a JSON message on connect
    ws.send(JSON.stringify({
      ws_visitor_id: `VU_${__VU}_${Date.now()}`,
      msg: 'order_pizza',
    }));
  });

  ws.addEventListener('message', (e) => {
    try {
      receivedMsg = JSON.parse(e.data);
    } catch (_) {
      receivedMsg = { msg: e.data };
    }
    // Close after receiving the first message
    ws.close();
  });

  ws.addEventListener('error', (e) => {
    // e.error is a string property, not a method
    console.error(`WS error [VU ${__VU}]:`, e.error);
  });

  ws.addEventListener('close', () => {
    check(null, {
      'ws opened':   () => opened,
      'msg received': () => receivedMsg !== null,
    });
    // Think time between iterations. It must live here in the close handler:
    // sleep() in the main function body would block the event loop before any
    // WebSocket events could fire.
    sleep(1);
  });
}

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/grafana/skills/blob/main/LICENSE