playwright-bdd
Version:
BDD Testing with Playwright runner
74 lines • 2.86 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCodeSnippet = getCodeSnippet;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const stripAnsiEscapes_1 = require("../utils/stripAnsiEscapes");
const stackTrace_1 = require("../playwright/stackTrace");
const filesCache = new Map();
/**
* Get code snippet by the error stack.
* See: https://github.com/microsoft/playwright/blob/release-1.49/packages/playwright/src/reporters/internalReporter.ts#L115
*
* Some downside here is that it's done in a test worker, not in the reporter process.
*/
function getCodeSnippet(error) {
const location = getErrorLocation(error);
if (!location?.file || !location.line)
return;
const source = getFileContent(location.file);
const lines = source.split('\n');
const startLine = Math.max(0, location.line - 3);
const snippetLines = lines.slice(startLine, location.line + 4);
return trimEmptyLines(snippetLines).join('\n');
}
/**
* Extracts location of the first user's file in error stack trace.
* See: https://github.com/microsoft/playwright/blob/release-1.49/packages/playwright/src/reporters/base.ts#L466
*/
// eslint-disable-next-line visual/complexity
function getErrorLocation(error) {
const lines = (0, stripAnsiEscapes_1.stripAnsiEscapes)(error.stack || '').split('\n');
let firstStackLine = lines.findIndex((line) => line.startsWith(' at '));
if (firstStackLine === -1)
firstStackLine = lines.length;
const stackLines = lines.slice(firstStackLine);
for (const line of stackLines) {
const frame = (0, stackTrace_1.parseStackFrame)(line, node_path_1.default.sep, false);
if (!frame || !frame.file || belongsToNodeModules(frame.file))
continue;
return { file: frame.file, column: frame.column || 0, line: frame.line || 0 };
}
}
function getFileContent(file) {
let content = filesCache.get(file);
if (content === undefined) {
content = readFileSyncSafe(file);
filesCache.set(file, content);
}
return content;
}
function readFileSyncSafe(file) {
try {
return node_fs_1.default.readFileSync(file, 'utf8');
}
catch {
return '';
}
}
function belongsToNodeModules(file) {
return file.includes(`${node_path_1.default.sep}node_modules${node_path_1.default.sep}`);
}
function trimEmptyLines(lines) {
let start = 0;
let end = lines.length - 1;
while (start <= end && !lines[start].trim())
start++;
while (end >= start && !lines[end].trim())
end--;
return lines.slice(start, end + 1);
}
//# sourceMappingURL=snippet.js.map