### k6 API Testing Example Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md An example demonstrating API testing with k6. It includes a setup function to check API health and a default function to perform GET requests, assert response status, and validate JSON payload structure and content. ```javascript import { expect } from "https://jslib.k6.io/k6-testing/0.3.0/index.js"; import http from "k6/http"; export function setup() { // Ensure the API is up and running before running the tests // If the response is not 200, the test will fail immediately with // a non-zero exit code, display a user-friendly message, and stop the test. const response = http.get("https://api.example.com/health"); expect(response.status).toBe(200); } export default function () { const response = http.get("https://api.example.com/users"); expect(response.status).toBe(200); const json = response.json(); expect(json.users).toBeDefined(); expect(json.users).toBeInstanceOf(Array); expect(json.users[0].id).toBeGreaterThan(0); } ``` -------------------------------- ### Install k6-testing Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Demonstrates how to import the k6-testing library into a k6 script using its jslib URL. ```javascript import { expect } from "https://jslib.k6.io/k6-testing/0.3.0/index.js"; ``` -------------------------------- ### k6 Browser UI Testing Example Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md This example showcases browser UI testing using k6. It navigates to a web page, interacts with input fields by typing text, and uses assertions to verify element visibility and content, including a failing assertion for demonstration. ```javascript import { expect } from "https://jslib.k6.io/k6-testing/0.3.0/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(); try { // Navigate to the page await page.goto("https://test.k6.io/my_messages.php"); // Type into the login input field: 'testlogin' const loc = await page.locator('input[name="login"]'); await loc.type("testlogin"); // Assert that the login input field is visible await expect(page.locator('input[name="login"]')).toBeVisible(); // Expecting this to fail as we have typed 'testlogin' into the input instead of 'foo' await expect(page.locator('input[name="login"]')).toHaveValue("foo"); } finally { await page.close(); } } ``` -------------------------------- ### k6 Script with k6-testing Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md A comprehensive k6 script showcasing the use of k6-testing for both protocol-level and UI (browser) testing. It includes setup for scenarios, HTTP requests, and Playwright-like browser interactions with assertions. ```javascript import { browser } from "k6/browser"; import http from "k6/http"; import { expect } from "https://jslib.k6.io/k6-testing/0.3.0/index.js"; export const options = { scenarios: { // Protocol tests protocol: { executor: "shared-iterations", vus: 1, iterations: 1, exec: "protocol", }, // Browser tests ui: { executor: "shared-iterations", options: { browser: { type: "chromium", }, }, exec: "ui", }, }, }; export function protocol() { // Get the home page of k6's Quick Pizza app const response = http.get("https://quickpizza.grafana.com/"); // Simple assertions expect(response.status).toBe(200); } export async function ui() { const page = await browser.newPage(); try { await page.goto("https://quickpizza.grafana.com/"); await page.waitForLoadState("networkidle"); // waits until the `networkidle` event // Assert the "Pizza Please" button is visible await expect(page.locator("button[name=pizza-please]")).toBeVisible(); } finally { await page.close(); } } ``` -------------------------------- ### Playwright-Compatible Assertions Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Examples of using Playwright-like assertion syntax provided by k6-testing for common UI element checks, such as visibility and attribute values. ```javascript // These Playwright assertions work exactly the same in k6 await expect(page.locator(".button")).toBeVisible(); await expect(page.locator("input")).toHaveValue("test"); ``` -------------------------------- ### Build Commands Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Commands used to build the distributable files for the k6-jslib-testing project. Includes options for standard and release builds. ```shell deno task build ``` ```shell deno task release ``` -------------------------------- ### Configuring Expect Instances Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Explains how to create and configure custom `expect` instances using the `.configure()` method. This allows fine-tuning of assertion behavior like colorization, display format, and timeouts. ```javascript // Example of creating a configured instance (actual code not provided in source) // const configuredExpect = expect.configure({ colorize: false, timeout: 10000 }); // configuredExpect(value).toBe(10); ``` -------------------------------- ### Configure Expect Display and Colorization Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Demonstrates how to create a new expect instance with custom configurations for assertion display format and colorization. The configured instance can then be used for assertions, while the default expect instance remains unaffected. ```javascript export default function () { // Create a new expect instance with the default configuration const myExpect = expect.configure({ // Display assertions using an inline format, aimed towards making them more readable in logs display: "inline", // Disable colorization of the output of the expect function colorize: false, }); // Use myExpect instead of expect, and it will use the configured display format and colorization await myExpect(true).toBe(false); // Note that you're still free to use the default expect instance, and it will not be affected by the configuration expect(true).toBe(false); } ``` -------------------------------- ### Code Quality Commands Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Commands for maintaining code quality, including linting to report errors and formatting to ensure consistent style. ```shell deno lint *.ts ``` ```shell deno fmt *.ts ``` -------------------------------- ### Run k6 in Headless Mode Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Command-line instructions to execute k6 tests in headless mode, disabling summaries and quiet mode. It also shows how to check the exit status for assertion failures. ```sh # Run k6 in headless mode k6 run --no-summary --quiet examples/browser.js # If any assertion/expectation fail, a non-zero exit code will be returned echo $status ``` -------------------------------- ### Testing Commands Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Commands for executing tests within the k6-jslib-testing project. Covers both unit tests and integration tests. ```shell deno test ``` ```shell deno task test ``` -------------------------------- ### Customizing Assertion Timeouts Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Illustrates how to customize the timeout and polling interval for auto-retrying assertions in k6-testing by passing an options object. ```javascript await expect(page.locator(".button")).toBeVisible({ timeout: 10000, interval: 500, }); ``` -------------------------------- ### Standard Assertions Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md A comprehensive list of standard assertion methods for testing conditions in k6 JavaScript libraries. These assertions perform strict checks on values but do not implement auto-retry logic. ```APIDOC Standard Assertions: toBe(expected) - Performs a strict equality comparison (===). - Parameters: - expected: The value to compare against. toBeCloseTo(number, precision?) - Compares two numbers for approximate equality, allowing for a specified precision. - Parameters: - number: The number to compare against. - precision: Optional. The number of decimal places to check (defaults to 2). toBeDefined() - Asserts that a value is not undefined. toBeFalsy() - Asserts that a value is falsy (e.g., false, 0, '', null, undefined, NaN). toBeGreaterThan(number) - Asserts that a value is strictly greater than the provided number. - Parameters: - number: The number to compare against. toBeGreaterThanOrEqual(number) - Asserts that a value is greater than or equal to the provided number. - Parameters: - number: The number to compare against. toBeInstanceOf(expected) - Asserts that a value is an instance of a specific class or constructor. - Parameters: - expected: The constructor function or class. toBeLessThan(number) - Asserts that a value is strictly less than the provided number. - Parameters: - number: The number to compare against. toBeLessThanOrEqual(number) - Asserts that a value is less than or equal to the provided number. - Parameters: - number: The number to compare against. toBeNaN() - Asserts that a value is NaN (Not-a-Number). toBeNull() - Asserts that a value is strictly null. totoBeTruthy() - Asserts that a value is truthy (any value that coerces to true in a boolean context). toBeUndefined() - Asserts that a value is strictly undefined. toContain(expected) - For strings: Asserts that the string contains the specified substring. - For Arrays or Sets: Asserts that the collection contains the specified element. - Parameters: - expected: The substring, element, or object to search for. toContainEqual(expected) - Asserts that an Array or Set contains an element that is deeply equal to the expected value. - Parameters: - expected: The element to search for. toEqual(expected) - Performs a deep equality comparison between two values. - Parameters: - expected: The value to compare against. toHaveLength(expected) - Asserts that a value (like an Array, String, or Set) has a 'length' property equal to the expected value. - Parameters: - expected: The expected length. toHaveProperty(keyPath, expected?) - Ensures that a property at the provided `keyPath` exists in the object. - Optionally checks that the property's value is equal to `expected`. - Parameters: - keyPath: The path to the property (e.g., 'name', 'user.address.city'). - expected: Optional. The expected value of the property. ``` -------------------------------- ### Using Soft Assertions Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Illustrates the use of soft assertions with `expect.soft()`. Failed soft assertions do not terminate the test immediately but mark the test as failed, allowing execution to continue. ```javascript import exec from "k6/execution"; import { expect } from "https://jslib.k6.io/k6-testing/0.4.0/index.js"; export const options = { vus: 2, iterations: 10, }; export default function () { // Iteration 3 will mark the test as failed, but the test execution // will keep going until its end condition, and eventually exit with // code 110. if (exec.scenario.iterationInInstance === 3) { expect.soft(false).toBeTruthy(); } } ``` -------------------------------- ### Custom Expect Messages Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Shows how to provide custom error messages to assertions. The custom message is displayed alongside the standard assertion failure details, aiding in debugging. ```javascript expect(value, "Custom message").toHaveProperty("a.b[0]", 43); ``` -------------------------------- ### Negating Assertions with .not Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Demonstrates how to invert assertion logic using the `.not` modifier. This applies to both standard assertions and retrying assertions, allowing checks for conditions that should not be met. ```javascript import { expect } from "https://jslib.k6.io/k6-testing/0.4.0/index.js"; // Standard assertions expect(response.status).not.toBe(404); // Assert status is NOT 404 expect(response.json().items).not.toBeEmpty(); // Assert items array is not empty expect(user.permissions).not.toContain("admin"); // Assert user doesn't have admin permission // Retrying assertions (must be awaited) await expect(page.locator(".error-message")).not.toBeVisible(); // Assert error is not shown await expect(page.locator('button[type="submit"]')).not.toBeDisabled(); // Assert button is not disabled ``` -------------------------------- ### Configure Assertion Timeout and Polling Interval Source: https://github.com/grafana/k6-jslib-testing/blob/main/README.md Shows how to configure a new expect instance with specific timeout and polling intervals for assertions. This allows controlling how long assertions retry and the frequency of those retries, useful for asynchronous operations like waiting for elements to become visible. ```javascript export default function () { const myExpect = new expect.configure({ timeout: 10000, interval: 500 }); // Use myExpect instead of expect, and it will use the configured timeout and interval // for all assertions. // // In this specific case, the assertion will retry until the button is visible, or the timeout is reached: every // 500ms, for a maximum of 10 seconds. await myExpect(page.locator(".button")).toBeVisible(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.