k6-cucumber-steps
Version:
Cucumber step definitions for running k6 performance tests.
75 lines (66 loc) • 2.26 kB
JavaScript
const fs = require("fs");
const path = require("path");
const faker = require("@faker-js/faker").faker;
/**
* Recursively resolves all placeholders in an object.
* @param {*} data - The parsed JSON (object, array, string, etc)
* @param {object} env - Environment variables + aliases
* @returns {*} - Fully resolved structure
*/
function resolveDeep(data, env) {
if (typeof data === "string") {
// 1. Resolve env vars like {{username}}
data = data.replace(/{{(\w+)}}/g, (_, key) => {
return env[key] || "";
});
// 2. Resolve faker like {{faker.internet.email}}
data = data.replace(/{{faker\.([\w.]+)}}/g, (_, methodPath) => {
const parts = methodPath.split(".");
let fn = faker;
for (const part of parts) {
fn = fn?.[part];
if (!fn) throw new Error(`Invalid Faker method: faker.${methodPath}`);
}
return typeof fn === "function" ? fn() : fn;
});
// 3. Replace JSON file includes like <address.json>
data = data.replace(/<([\w-]+\.json)>/g, (_, fileName) => {
const filePath = path.join(__dirname, "../payloads", fileName);
if (!fs.existsSync(filePath)) {
throw new Error(`Payload file not found: ${fileName}`);
}
const fileContent = fs.readFileSync(filePath, "utf-8");
return fileContent.trim();
});
return data;
}
if (Array.isArray(data)) {
return data.map((item) => resolveDeep(item, env));
}
if (typeof data === "object" && data !== null) {
const resolved = {};
for (const key in data) {
resolved[key] = resolveDeep(data[key], env);
}
return resolved;
}
return data;
}
/**
* Resolves JSON templates using env vars, Faker, and JSON includes.
* @param {string} template - The raw JSON string template
* @param {object} env - Object containing environment variables or aliases
* @returns {object} - Fully resolved JS object
*/
module.exports = function resolveBody(template, env = {}) {
try {
const parsed = JSON.parse(template);
return resolveDeep(parsed, env);
} catch (err) {
console.error(
"❌ Failed to parse input JSON before resolving:",
err.message
);
throw new Error("Invalid JSON template provided to resolveBody");
}
};