UNPKG

k6-cucumber-steps

Version:

Cucumber step definitions for running k6 performance tests.

84 lines (72 loc) 2.5 kB
module.exports = function buildK6Script(config) { const { method, endpoints, endpoint, body, headers, options, baseUrl } = config; const BASE_URL = baseUrl || (config.worldParameters && config.worldParameters.baseUrl) || process.env.API_BASE_URL || process.env.BASE_URL; if (!BASE_URL) { throw new Error( "No base URL found: please provide baseUrl inline (step/world/feature) or set API_BASE_URL/BASE_URL in environment variables." ); } const resolveEndpoint = (url) => { return url.startsWith("/") ? `${BASE_URL}${url}` : url; }; const safeHeaders = headers && Object.keys(headers).length ? headers : {}; const safeBody = body !== undefined ? body : null; const safeOptions = options && Object.keys(options).length ? options : {}; const stringifiedHeaders = JSON.stringify(safeHeaders, null, 2); const stringifiedBody = JSON.stringify(safeBody, null, 2); const reportDir = process.env.REPORT_OUTPUT_DIR || process.env.K6_REPORT_DIR || process.env.npm_config_report_output_dir || "reports"; return ` import http from 'k6/http'; import { check } from 'k6'; import { htmlReport } from "https://raw.githubusercontent.com/benc-uk/k6-reporter/main/dist/bundle.js"; import { textSummary } from "https://jslib.k6.io/k6-summary/0.0.1/index.js"; export const options = ${JSON.stringify(safeOptions, null, 2)}; export default function () { const headers = ${stringifiedHeaders}; const body = ${stringifiedBody}; ${ endpoints?.length ? endpoints .map( (url, i) => ` const resolvedUrl${i} = "${resolveEndpoint(url)}"; const res${i} = http.request("${method}", resolvedUrl${i}, ${ method === "GET" || method === "DELETE" ? "null" : "JSON.stringify(body)" }, { headers }); check(res${i}, { "status is 2xx": (r) => r.status >= 200 && r.status < 300 }); ` ) .join("\n") : ` const resolvedUrl = "${resolveEndpoint(endpoint)}"; const res = http.request("${method}", resolvedUrl, ${ method === "GET" || method === "DELETE" ? "null" : "JSON.stringify(body)" }, { headers }); check(res, { "status is 2xx": (r) => r.status >= 200 && r.status < 300 }); ` } } export function handleSummary(data) { return { "${reportDir}/k6-report.html": htmlReport(data), stdout: textSummary(data, { indent: " ", enableColors: true }), }; } `; };