Best JavaScript code snippet using playwright-internal
index.js
Source:index.js
1'use strict';2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.separateMessageFromStack = exports.formatResultsErrors = exports.formatStackTrace = exports.formatExecError = undefined;6var _fs = require('fs');7var _fs2 = _interopRequireDefault(_fs);8var _path = require('path');9var _path2 = _interopRequireDefault(_path);10var _chalk = require('chalk');11var _chalk2 = _interopRequireDefault(_chalk);12var _micromatch = require('micromatch');13var _micromatch2 = _interopRequireDefault(_micromatch);14var _slash = require('slash');15var _slash2 = _interopRequireDefault(_slash);16var _codeFrame = require('@babel/code-frame');17var _stackUtils = require('stack-utils');18var _stackUtils2 = _interopRequireDefault(_stackUtils);19function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }20// stack utils tries to create pretty stack by making paths relative.21const stackUtils = new _stackUtils2.default({22 cwd: 'something which does not exist'23}); /**24 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.25 *26 * This source code is licensed under the MIT license found in the27 * LICENSE file in the root directory of this source tree.28 *29 * 30 */31let nodeInternals = [];32try {33 nodeInternals = _stackUtils2.default.nodeInternals()34 // this is to have the tests be the same in node 4 and node 6.35 // TODO: Remove when we drop support for node 436 .concat(new RegExp('internal/process/next_tick.js'));37} catch (e) {38 // `StackUtils.nodeInternals()` fails in browsers. We don't need to remove39 // node internals in the browser though, so no issue.40}41const PATH_NODE_MODULES = `${_path2.default.sep}node_modules${_path2.default.sep}`;42const PATH_EXPECT_BUILD = `${_path2.default.sep}expect${_path2.default.sep}build${_path2.default.sep}`;43// filter for noisy stack trace lines44const JASMINE_IGNORE = /^\s+at(?:(?:.*?vendor\/|jasmine\-)|\s+jasmine\.buildExpectationResult)/;45const JEST_INTERNALS_IGNORE = /^\s+at.*?jest(-.*?)?(\/|\\)(build|node_modules|packages)(\/|\\)/;46const ANONYMOUS_FN_IGNORE = /^\s+at <anonymous>.*$/;47const ANONYMOUS_PROMISE_IGNORE = /^\s+at (new )?Promise \(<anonymous>\).*$/;48const ANONYMOUS_GENERATOR_IGNORE = /^\s+at Generator.next \(<anonymous>\).*$/;49const NATIVE_NEXT_IGNORE = /^\s+at next \(native\).*$/;50const TITLE_INDENT = ' ';51const MESSAGE_INDENT = ' ';52const STACK_INDENT = ' ';53const ANCESTRY_SEPARATOR = ' \u203A ';54const TITLE_BULLET = _chalk2.default.bold('\u25cf ');55const STACK_TRACE_COLOR = _chalk2.default.dim;56const STACK_PATH_REGEXP = /\s*at.*\(?(\:\d*\:\d*|native)\)?/;57const EXEC_ERROR_MESSAGE = 'Test suite failed to run';58const ERROR_TEXT = 'Error: ';59const trim = string => (string || '').trim();60// Some errors contain not only line numbers in stack traces61// e.g. SyntaxErrors can contain snippets of code, and we don't62// want to trim those, because they may have pointers to the column/character63// which will get misaligned.64const trimPaths = string => string.match(STACK_PATH_REGEXP) ? trim(string) : string;65const getRenderedCallsite = (fileContent, line) => {66 let renderedCallsite = (0, _codeFrame.codeFrameColumns)(fileContent, { start: { line } }, { highlightCode: true });67 renderedCallsite = renderedCallsite.split('\n').map(line => MESSAGE_INDENT + line).join('\n');68 renderedCallsite = `\n${renderedCallsite}\n`;69 return renderedCallsite;70};71// ExecError is an error thrown outside of the test suite (not inside an `it` or72// `before/after each` hooks). If it's thrown, none of the tests in the file73// are executed.74const formatExecError = exports.formatExecError = (testResult, config, options, testPath) => {75 let error = testResult.testExecError;76 if (!error || typeof error === 'number') {77 error = new Error(`Expected an Error, but "${String(error)}" was thrown`);78 error.stack = '';79 }80 var _error = error;81 let message = _error.message,82 stack = _error.stack;83 if (typeof error === 'string' || !error) {84 error || (error = 'EMPTY ERROR');85 message = '';86 stack = error;87 }88 const separated = separateMessageFromStack(stack || '');89 stack = separated.stack;90 if (separated.message.indexOf(trim(message)) !== -1) {91 // Often stack trace already contains the duplicate of the message92 message = separated.message;93 }94 message = message.split(/\n/).map(line => MESSAGE_INDENT + line).join('\n');95 stack = stack && !options.noStackTrace ? '\n' + formatStackTrace(stack, config, options, testPath) : '';96 if (message.match(/^\s*$/) && stack.match(/^\s*$/)) {97 // this can happen if an empty object is thrown.98 message = MESSAGE_INDENT + 'Error: No message was provided';99 }100 return TITLE_INDENT + TITLE_BULLET + EXEC_ERROR_MESSAGE + '\n\n' + message + stack + '\n';101};102const removeInternalStackEntries = (lines, options) => {103 let pathCounter = 0;104 return lines.filter(line => {105 if (ANONYMOUS_FN_IGNORE.test(line)) {106 return false;107 }108 if (ANONYMOUS_PROMISE_IGNORE.test(line)) {109 return false;110 }111 if (ANONYMOUS_GENERATOR_IGNORE.test(line)) {112 return false;113 }114 if (NATIVE_NEXT_IGNORE.test(line)) {115 return false;116 }117 if (nodeInternals.some(internal => internal.test(line))) {118 return false;119 }120 if (!STACK_PATH_REGEXP.test(line)) {121 return true;122 }123 if (JASMINE_IGNORE.test(line)) {124 return false;125 }126 if (++pathCounter === 1) {127 return true; // always keep the first line even if it's from Jest128 }129 if (options.noStackTrace) {130 return false;131 }132 if (JEST_INTERNALS_IGNORE.test(line)) {133 return false;134 }135 return true;136 });137};138const formatPaths = (config, options, relativeTestPath, line) => {139 // Extract the file path from the trace line.140 const match = line.match(/(^\s*at .*?\(?)([^()]+)(:[0-9]+:[0-9]+\)?.*$)/);141 if (!match) {142 return line;143 }144 let filePath = (0, _slash2.default)(_path2.default.relative(config.rootDir, match[2]));145 // highlight paths from the current test file146 if (config.testMatch && config.testMatch.length && (0, _micromatch2.default)(filePath, config.testMatch) || filePath === relativeTestPath) {147 filePath = _chalk2.default.reset.cyan(filePath);148 }149 return STACK_TRACE_COLOR(match[1]) + filePath + STACK_TRACE_COLOR(match[3]);150};151const getTopFrame = lines => {152 for (const line of lines) {153 if (line.includes(PATH_NODE_MODULES) || line.includes(PATH_EXPECT_BUILD)) {154 continue;155 }156 const parsedFrame = stackUtils.parseLine(line.trim());157 if (parsedFrame && parsedFrame.file) {158 return parsedFrame;159 }160 }161 return null;162};163const formatStackTrace = exports.formatStackTrace = (stack, config, options, testPath) => {164 let lines = stack.split(/\n/);165 let renderedCallsite = '';166 const relativeTestPath = testPath ? (0, _slash2.default)(_path2.default.relative(config.rootDir, testPath)) : null;167 lines = removeInternalStackEntries(lines, options);168 const topFrame = getTopFrame(lines);169 if (topFrame) {170 const filename = topFrame.file;171 if (_path2.default.isAbsolute(filename)) {172 let fileContent;173 try {174 // TODO: check & read HasteFS instead of reading the filesystem:175 // see: https://github.com/facebook/jest/pull/5405#discussion_r164281696176 fileContent = _fs2.default.readFileSync(filename, 'utf8');177 renderedCallsite = getRenderedCallsite(fileContent, topFrame.line);178 } catch (e) {179 // the file does not exist or is inaccessible, we ignore180 }181 }182 }183 const stacktrace = lines.map(line => STACK_INDENT + formatPaths(config, options, relativeTestPath, trimPaths(line))).join('\n');184 return renderedCallsite + stacktrace;185};186const formatResultsErrors = exports.formatResultsErrors = (testResults, config, options, testPath) => {187 const failedResults = testResults.reduce((errors, result) => {188 result.failureMessages.forEach(content => errors.push({ content, result }));189 return errors;190 }, []);191 if (!failedResults.length) {192 return null;193 }194 return failedResults.map((_ref) => {195 let result = _ref.result,196 content = _ref.content;197 var _separateMessageFromS = separateMessageFromStack(content);198 let message = _separateMessageFromS.message,199 stack = _separateMessageFromS.stack;200 stack = options.noStackTrace ? '' : STACK_TRACE_COLOR(formatStackTrace(stack, config, options, testPath)) + '\n';201 message = message.split(/\n/).map(line => MESSAGE_INDENT + line).join('\n');202 const title = _chalk2.default.bold.red(TITLE_INDENT + TITLE_BULLET + result.ancestorTitles.join(ANCESTRY_SEPARATOR) + (result.ancestorTitles.length ? ANCESTRY_SEPARATOR : '') + result.title) + '\n';203 return title + '\n' + message + '\n' + stack;204 }).join('\n');205};206// jasmine and worker farm sometimes don't give us access to the actual207// Error object, so we have to regexp out the message from the stack string208// to format it.209const separateMessageFromStack = exports.separateMessageFromStack = content => {210 if (!content) {211 return { message: '', stack: '' };212 }213 const messageMatch = content.match(/(^(.|\n)*?(?=\n\s*at\s.*\:\d*\:\d*))/);214 let message = messageMatch ? messageMatch[0] : 'Error';215 const stack = messageMatch ? content.slice(message.length) : content;216 // If the error is a plain error instead of a SyntaxError or TypeError217 // we remove it from the message because it is generally not useful.218 if (message.startsWith(ERROR_TEXT)) {219 message = message.substr(ERROR_TEXT.length);220 }221 return { message, stack };...
formatFailureMessage.js
Source:formatFailureMessage.js
1/**2 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.3 *4 * This source code is licensed under the BSD-style license found in the5 * LICENSE file in the root directory of this source tree. An additional grant6 * of patent rights can be found in the PATENTS file in the same directory.7 *8 * @flow9 */10'use strict';11import type {Config, Path} from 'types/Config';12import type {TestResult} from 'types/TestResult';13const chalk = require('chalk');14const path = require('path');15const separateMessageFromStack = require('./separateMessageFromStack');16// filter for noisy stack trace lines17const JASMINE_IGNORE =18 /^\s+at(?:(?:.*?vendor\/|jasmine\-)|\s+jasmine\.buildExpectationResult)/;19const STACK_TRACE_IGNORE =20 /^\s+at.*?jest(-.*?)?(\/|\\)(vendor|build|node_modules|packages)(\/|\\)/;21const TITLE_INDENT = ' ';22const MESSAGE_INDENT = ' ';23const STACK_INDENT = ' ';24const ANCESTRY_SEPARATOR = ' \u203A ';25const TITLE_BULLET = chalk.bold('\u25cf ');26const STACK_TRACE_COLOR = chalk.dim;27const STACK_PATH_REGEXP = /\s*at.*\(?(\:\d*\:\d*|native)\)?/;28const EXEC_ERROR_MESSAGE = 'Test suite failed to run';29const trim = string => (string || '').replace(/^\s+/, '').replace(/\s+$/, '');30// Some errors contain not only line numbers in stack traces31// e.g. SyntaxErrors can contain snippets of code, and we don't32// want to trim those, because they may have pointers to the column/character33// which will get misaligned.34const trimPaths = string =>35 string.match(STACK_PATH_REGEXP) ? trim(string) : string;36// ExecError is an error thrown outside of the test suite (not inside an `it` or37// `before/after each` hooks). If it's thrown, none of the tests in the file38// are executed.39const formatExecError = (40 testResult: TestResult,41 config: Config,42 testPath: Path,43) => {44 let error = testResult.testExecError;45 if (!error || typeof error === 'number') {46 error = new Error(`Expected an Error, but "${String(error)}" was thrown`);47 error.stack = '';48 }49 let {message, stack} = error;50 if (typeof error === 'string' || !error) {51 error || (error = 'EMPTY ERROR');52 message = '';53 stack = error;54 }55 const separated = separateMessageFromStack(stack || '');56 stack = separated.stack;57 if (separated.message.indexOf(trim(message)) !== -1) {58 // Often stack trace already contains the duplicate of the message59 message = separated.message;60 } else {61 message = message + '\n' + separated.message;62 }63 message = message.split(/\n/).map(line => MESSAGE_INDENT + line).join('\n');64 stack = stack && !config.noStackTrace65 ? '\n' + STACK_TRACE_COLOR(formatStackTrace(stack, config, testPath))66 : '';67 if (message.match(/^\s*$/) && stack.match(/^\s*$/)) {68 // this can happen if an empty object is thrown.69 message = 'ERROR: No message was provided';70 }71 return TITLE_INDENT + TITLE_BULLET + EXEC_ERROR_MESSAGE + '\n\n' +72 message + stack + '\n';73};74const removeInternalStackEntries = (lines, config) => {75 let pathCounter = 0;76 return lines.filter(line => {77 const isPath = STACK_PATH_REGEXP.test(line);78 if (!isPath) {79 return true;80 }81 if (JASMINE_IGNORE.test(line)) {82 return false;83 }84 if (++pathCounter === 1) {85 return true; // always keep the first line even if it's from Jest86 }87 return !(STACK_TRACE_IGNORE.test(line) || config.noStackTrace);88 });89};90const formatPaths = (config, relativeTestPath, line) => {91 // Extract the file path from the trace line.92 let matches = line.match(/(^\s*at .*?\()([^()]+)(:[0-9]+:[0-9]+\).*$)/);93 if (!matches) {94 matches = line.match(/(^\s+at )([^()]+)(:[0-9]+:[0-9]+.*$)/);95 if (!matches) {96 return line;97 }98 }99 let filePath = matches[2];100 filePath = path.relative(config.rootDir, filePath);101 if (new RegExp(config.testRegex).test(filePath)) {102 filePath = chalk.reset.blue(filePath);103 } else if (filePath === relativeTestPath) {104 // highlight paths from the current test file105 filePath = chalk.reset.cyan(filePath);106 }107 // make paths relative to the <rootDir>108 return STACK_TRACE_COLOR(matches[1])109 + filePath + STACK_TRACE_COLOR(matches[3]);110};111const formatStackTrace = (stack, config, testPath) => {112 let lines = stack.split(/\n/);113 const relativeTestPath = testPath114 ? path.relative(config.rootDir, testPath)115 : null;116 lines = removeInternalStackEntries(lines, config);117 return lines.map(trimPaths)118 .map(formatPaths.bind(null, config, relativeTestPath))119 .map(line => STACK_INDENT + line)120 .join('\n');121};122const formatResultsErrors = (123 testResults: TestResult,124 config: Config,125 testPath: ?Path,126): ?string => {127 const failedResults = testResults.testResults.reduce(128 (errors, result) => {129 result.failureMessages.forEach(content => errors.push({result, content}));130 return errors;131 },132 [],133 );134 if (!failedResults.length) {135 return null;136 }137 return failedResults.map(({result, content}) => {138 let {message, stack} = separateMessageFromStack(content);139 stack = config.noStackTrace140 ? ''141 : STACK_TRACE_COLOR(formatStackTrace(stack, config, testPath)) + '\n';142 message = message143 .split(/\n/)144 .map(line => MESSAGE_INDENT + line)145 .join('\n');146 const title = chalk.bold.red(147 TITLE_INDENT + TITLE_BULLET +148 result.ancestorTitles.join(ANCESTRY_SEPARATOR) +149 (result.ancestorTitles.length ? ANCESTRY_SEPARATOR : '') +150 result.title,151 ) + '\n';152 return title + '\n' + message + '\n' + stack;153 }).join('\n');154};155module.exports = {156 formatExecError,157 formatResultsErrors,...
messages.js
Source:messages.js
1/**2 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.3 *4 * This source code is licensed under the BSD-style license found in the5 * LICENSE file in the root directory of this source tree. An additional grant6 * of patent rights can be found in the PATENTS file in the same directory.7 *8 * 9 */10'use strict';11const chalk = require('chalk');12const path = require('path');13const separateMessageFromStack = require('./separateMessageFromStack');14// filter for noisy stack trace lines15const JASMINE_IGNORE =16/^\s+at(?:(?:.*?vendor\/|jasmine\-)|\s+jasmine\.buildExpectationResult)/;17const STACK_TRACE_IGNORE =18/^\s+at.*?jest(-.*?)?(\/|\\)(vendor|build|node_modules|packages)(\/|\\)/;19const TITLE_INDENT = ' ';20const MESSAGE_INDENT = ' ';21const STACK_INDENT = ' ';22const ANCESTRY_SEPARATOR = ' \u203A ';23const TITLE_BULLET = chalk.bold('\u25cf ');24const STACK_TRACE_COLOR = chalk.dim;25const STACK_PATH_REGEXP = /\s*at.*\(?(\:\d*\:\d*|native)\)?/;26const EXEC_ERROR_MESSAGE = 'Test suite failed to run';27const trim = string => (string || '').replace(/^\s+/, '').replace(/\s+$/, '');28// Some errors contain not only line numbers in stack traces29// e.g. SyntaxErrors can contain snippets of code, and we don't30// want to trim those, because they may have pointers to the column/character31// which will get misaligned.32const trimPaths = string =>33string.match(STACK_PATH_REGEXP) ? trim(string) : string;34// ExecError is an error thrown outside of the test suite (not inside an `it` or35// `before/after each` hooks). If it's thrown, none of the tests in the file36// are executed.37const formatExecError = (38testResult,39config,40testPath) =>41{42 let error = testResult.testExecError;43 if (!error || typeof error === 'number') {44 error = new Error(`Expected an Error, but "${ String(error) }" was thrown`);45 error.stack = '';46 }var _error =47 error;let message = _error.message,stack = _error.stack;48 if (typeof error === 'string' || !error) {49 error || (error = 'EMPTY ERROR');50 message = '';51 stack = error;52 }53 const separated = separateMessageFromStack(stack || '');54 stack = separated.stack;55 if (separated.message.indexOf(trim(message)) !== -1) {56 // Often stack trace already contains the duplicate of the message57 message = separated.message;58 } else {59 message = message + '\n' + separated.message;60 }61 message = message.split(/\n/).map(line => MESSAGE_INDENT + line).join('\n');62 stack = stack && !config.noStackTrace ?63 '\n' + STACK_TRACE_COLOR(formatStackTrace(stack, config, testPath)) :64 '';65 if (message.match(/^\s*$/) && stack.match(/^\s*$/)) {66 // this can happen if an empty object is thrown.67 message = MESSAGE_INDENT + 'Error: No message was provided';68 }69 return TITLE_INDENT + TITLE_BULLET + EXEC_ERROR_MESSAGE + '\n\n' +70 message + stack + '\n';71};72const removeInternalStackEntries = (lines, config) => {73 let pathCounter = 0;74 return lines.filter(line => {75 const isPath = STACK_PATH_REGEXP.test(line);76 if (!isPath) {77 return true;78 }79 if (JASMINE_IGNORE.test(line)) {80 return false;81 }82 if (++pathCounter === 1) {83 return true; // always keep the first line even if it's from Jest84 }85 return !(STACK_TRACE_IGNORE.test(line) || config.noStackTrace);86 });87};88const formatPaths = (89config,90relativeTestPath,91line) =>92{93 // Extract the file path from the trace line.94 const match = line.match(/(^\s*at .*?\(?)([^()]+)(:[0-9]+:[0-9]+\)?.*$)/);95 if (!match) {96 return line;97 }98 let filePath = path.relative(config.rootDir, match[2]);99 // highlight paths from the current test file100 if (101 config.testRegex && new RegExp(config.testRegex).test(filePath) ||102 filePath === relativeTestPath)103 {104 filePath = chalk.reset.cyan(filePath);105 }106 return STACK_TRACE_COLOR(match[1]) + filePath + STACK_TRACE_COLOR(match[3]);107};108const formatStackTrace = (109stack,110config,111testPath) =>112{113 let lines = stack.split(/\n/);114 const relativeTestPath = testPath ?115 path.relative(config.rootDir, testPath) :116 null;117 lines = removeInternalStackEntries(lines, config);118 return lines.map(trimPaths).119 map(formatPaths.bind(null, config, relativeTestPath)).120 map(line => STACK_INDENT + line).121 join('\n');122};123const formatResultsErrors = (124testResults,125config,126testPath) =>127{128 const failedResults = testResults.reduce(129 (errors, result) => {130 result.failureMessages.forEach(content => errors.push({ content, result }));131 return errors;132 },133 []);134 if (!failedResults.length) {135 return null;136 }137 return failedResults.map((_ref) => {let result = _ref.result,content = _ref.content;var _separateMessageFromS =138 separateMessageFromStack(content);let message = _separateMessageFromS.message,stack = _separateMessageFromS.stack;139 stack = config.noStackTrace ?140 '' :141 STACK_TRACE_COLOR(formatStackTrace(stack, config, testPath)) + '\n';142 message = message.143 split(/\n/).144 map(line => MESSAGE_INDENT + line).145 join('\n');146 const title = chalk.bold.red(147 TITLE_INDENT + TITLE_BULLET +148 result.ancestorTitles.join(ANCESTRY_SEPARATOR) + (149 result.ancestorTitles.length ? ANCESTRY_SEPARATOR : '') +150 result.title) +151 '\n';152 return title + '\n' + message + '\n' + stack;153 }).join('\n');154};155module.exports = {156 formatExecError,157 formatResultsErrors,...
runner.js
Source:runner.js
1const os = require('os');2const fs = require('fs');3const path = require('path');4const { transformFileSync, loadPartialConfig } = require('@babel/core');5const {6 pass,7 skip,8 runner,9 utils,10} = require('@tunnckocore/create-jest-runner');11const isWin32 = os.platform() === 'win32';12process.env.NODE_ENV = 'build';13/* eslint max-statements: ["error", 25] */14module.exports = runner('babel', async (ctx) => {15 const start = Date.now();16 const { testPath, config, runnerName, runnerConfig, memoizer } = ctx;17 let options = runnerConfig;18 const cfgs = [].concat(options).filter(Boolean);19 if (cfgs.length === 0) {20 const babelCfg = loadPartialConfig();21 if (babelCfg.config) {22 cfgs.push(babelCfg.options);23 } else {24 return skip({25 start,26 end: Date.now(),27 test: {28 path: testPath,29 title: 'babel',30 },31 });32 }33 }34 const results = cfgs.reduce(async (prevPromise, { config: cfg, ...opts }) => {35 const acc = await prevPromise;36 options = normalizeOptions({ ...opts });37 const babelConfig = { ...cfg };38 const result = await utils.tryCatch(39 async () => {40 const transform = await memoizer.memoize(41 (...args) => transformFileSync(...args),42 babelConfig,43 { cacheId: 'transform-with-cfg' },44 );45 const res = await transform(testPath, babelConfig);46 return res;47 },48 { start, testPath, runnerName, runnerConfig },49 );50 if (result.hasError) return acc.concat(result.error);51 let relativeTestPath = path.relative(config.rootDir, testPath);52 if (isWin32 && !relativeTestPath.includes('/')) {53 relativeTestPath = relativeTestPath.replace(/\\/g, '/');54 }55 // eslint-disable-next-line prefer-const56 let { outFile, outDir } = createOuts({ relativeTestPath, config, options });57 outFile = path.join(58 outDir,59 `${path.basename(outFile, path.extname(outFile))}.js`,60 );61 fs.mkdirSync(outDir, { recursive: true });62 fs.writeFileSync(outFile, result.code);63 const passing = pass({64 start,65 end: Date.now(),66 test: { path: outFile, title: 'babel' },67 });68 if (result.map || babelConfig.sourceMaps === true) {69 const mapFile = `${outFile}.map`;70 fs.writeFileSync(mapFile, JSON.stringify(result.map));71 return acc.concat(72 passing,73 pass({74 start,75 end: Date.now(),76 test: { path: mapFile, title: 'babel' },77 }),78 );79 }80 return acc.concat(passing);81 }, Promise.resolve([]));82 // eslint-disable-next-line no-return-await83 return await Promise.all(await results);84});85function normalizeOptions(cfg) {86 const runnerConfig = {87 monorepo: false,88 outDir: 'dist',89 srcDir: 'src',90 ...cfg,91 };92 runnerConfig.outDir = runnerConfig.outDir || runnerConfig.outdir;93 if (typeof runnerConfig.outDir !== 'string') {94 runnerConfig.outDir = 'dist';95 }96 if (typeof runnerConfig.srcDir !== 'string') {97 runnerConfig.srcDir = 'src';98 }99 runnerConfig.isMonorepo =100 typeof runnerConfig.isMonorepo === 'function'101 ? runnerConfig.isMonorepo102 : () => runnerConfig.monorepo;103 return runnerConfig;104}105function createOuts({ relativeTestPath, config, options }) {106 // if not in monorepo, the `outs.dir` will be empty107 const outs = relativeTestPath.split('/').reduce(108 (accumulator, item, idx) => {109 // only if we are in monorepo we want to get the first 2 items110 if (options.isMonorepo(config.cwd) && idx < 2) {111 return { ...accumulator, dir: accumulator.dir.concat(item) };112 }113 return {114 ...accumulator,115 file: accumulator.file116 .concat(item === options.srcDir ? null : item)117 .filter(Boolean),118 };119 },120 { file: [], dir: [] },121 );122 const outFile = path.join(123 config.rootDir,124 ...outs.dir.filter(Boolean),125 options.outDir,126 ...outs.file.filter(Boolean),127 );128 const outDir = path.dirname(outFile);129 return { outFile, outDir };...
run.js
Source:run.js
1const os = require('os');2const fs = require('fs');3const path = require('path');4const { pass, fail } = require('create-jest-runner');5const babel = require('@babel/core');6const cosmiconfig = require('cosmiconfig');7const explorer = cosmiconfig('jest-runner-babel');8const isWin32 = os.platform() === 'win32';9module.exports = async ({ testPath, config }) => {10 const start = new Date();11 const cfg = explorer.searchSync();12 const runnerConfig = Object.assign(13 { monorepo: false, outDir: 'dist', srcDir: 'src' },14 cfg.config15 );16 runnerConfig.isMonorepo =17 typeof runnerConfig.isMonorepo === 'function'18 ? runnerConfig.isMonorepo19 : () => runnerConfig.monorepo;20 let result = null;21 try {22 result = babel.transformFileSync(testPath, runnerConfig.babel);23 } catch (err) {24 return fail({25 start,26 end: new Date(),27 test: { path: testPath, title: 'Babel', errorMessage: err.message },28 });29 }30 // Classics in the genre! Yes, it's possible, sometimes.31 // Old habit for ensurance32 if (!result) {33 return fail({34 start,35 end: new Date(),36 test: {37 path: testPath,38 title: 'Babel',39 errorMessage: 'Babel failing to transform...',40 },41 });42 }43 runnerConfig.outDir = runnerConfig.outDir || runnerConfig.outdir;44 if (typeof runnerConfig.outDir !== 'string') {45 runnerConfig.outDir = 'dist';46 }47 if (typeof runnerConfig.srcDir !== 'string') {48 runnerConfig.srcDir = 'src';49 }50 let { rootDir } = config;51 let relativeTestPath = path.relative(rootDir, testPath);52 if (isWin32 && !relativeTestPath.includes('/')) {53 relativeTestPath = relativeTestPath.replace(/\\/g, '/');54 }55 // [ 'index.js' ]56 // [ 'src', 'index.js' ]57 // [ 'src', 'some', 'index.js' ]58 // [ 'packages', 'foo', 'index.js' ]59 // [ 'packages', 'foo', 'src', 'index.js' ]60 // [ 'packages', 'foo', 'src', 'some', 'index.js' ]61 // so usually need to get the first 2 items62 const segments = relativeTestPath.split('/');63 // if not in monorepo, the `outs.dir` will be empty64 const outs = segments.reduce(65 (acc, item, index) => {66 // only if we are in monorepo we want to get the first 2 items67 if (runnerConfig.isMonorepo(config.cwd) && index < 2) {68 return { ...acc, dir: acc.dir.concat(item) };69 }70 return {71 ...acc,72 file: acc.file73 .concat(item === runnerConfig.srcDir ? null : item)74 .filter(Boolean),75 };76 },77 { file: [], dir: [] }78 );79 let outFile = path.join(80 rootDir,81 ...outs.dir.filter(Boolean),82 runnerConfig.outDir,83 ...outs.file.filter(Boolean)84 );85 const filename = path.basename(outFile, path.extname(outFile));86 const outDir = path.dirname(outFile);87 outFile = path.join(outDir, `${filename}.js`);88 fs.mkdirSync(outDir, { recursive: true });89 fs.writeFileSync(outFile, result.code);90 return pass({91 start,92 end: new Date(),93 test: { path: outFile },94 });...
utils.js
Source:utils.js
1// @flow2/* eslint-disable no-plusplus */3import {4 Test,5 TestResult,6} from '../types';7const matchTestFileName = /([A-Za-z_])\w+(_test.go)/g;8export const pathContainsFailedTest = (line: string, relativeTestPath: string) => {9 // eslint-disable-next-line max-len10 const testFile = line.match(new RegExp(matchTestFileName)) &&11 line.match(new RegExp(matchTestFileName)).length > 0 &&12 line.match(new RegExp(matchTestFileName))[0];13 return relativeTestPath.indexOf(testFile) > -1;14};15// eslint-disable-next-line max-len16export const parseGoOutput = (relativeTestPath: string, start: number, output: Array<string>): Test => {17 const report = {18 passed: 0,19 failed: 0,20 failureMessage: '',21 duration: 0,22 end: 0,23 name: relativeTestPath,24 };25 output.forEach((line) => {26 if (27 line &&28 line.indexOf('.go:') > -1 &&29 pathContainsFailedTest(line, relativeTestPath)30 ) {31 report.failed++;32 report.failureMessage = line;33 }34 if (line && line.indexOf('ok') > -1) {35 report.passed++;36 }37 });38 return report;39};40export const toTestResult = (test: Test): TestResult => ({41 ancestorTitles: [],42 duration: test.duration,43 failureMessages: test.failed > 0 ? test.failureMessage : '',44 fullName: test.name,45 numPassingAsserts: test.failed === 0 ? 1 : 0,46 status: test.failed === 0 ? 'passed' : 'failed',47 title: test.name,...
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.screenshot({ path: page.relativeTestPath('example.png') });6 await browser.close();7})();8const {chromium} = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const page = await browser.newPage();12 await page.screenshot({ path: page.relativeTestPath('example.png') });13 await browser.close();14})();
Using AI Code Generation
1const { relativeTestPath } = require('@playwright/test');2const { relativeTestPath } = require('@playwright/test');3const { test, expect } = require('@playwright/test');4test('should be able to use relativeTestPath method', async ({ page }) => {5 const path = relativeTestPath(__filename);6 expect(path).toBe('test.js');7});
Using AI Code Generation
1const path = require('path');2const { _electron } = require('playwright');3const relativeTestPath = _electron.relativeTestPath;4const testPath = relativeTestPath(path.join(__dirname, 'test.js'));5console.log(testPath);6const path = require('path');7const { _electron } = require('playwright');8const relativeTestPath = _electron.relativeTestPath;9const testPath = relativeTestPath(path.join(__dirname, 'test.js'));10console.log(testPath);11const path = require('path');12const { _electron } = require('playwright');13const relativeTestPath = _electron.relativeTestPath;14const testPath = relativeTestPath(path.join(__dirname, 'test.js'));15console.log(testPath);16const path = require('path');17const { _electron } = require('playwright');18const relativeTestPath = _electron.relativeTestPath;19const testPath = relativeTestPath(path.join(__dirname, 'test.js'));20console.log(testPath);21const path = require('path');22const { _electron } = require('playwright');23const relativeTestPath = _electron.relativeTestPath;24const testPath = relativeTestPath(path.join(__dirname, 'test.js'));25console.log(testPath);26const path = require('path');27const { _electron } = require('playwright');28const relativeTestPath = _electron.relativeTestPath;29const testPath = relativeTestPath(path.join(__dirname, 'test.js'));
Using AI Code Generation
1const path = require('path');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4 const relativePath = page.relativeTestPath('test.js');5 expect(relativePath).toBe(path.join(__dirname, 'test.js'));6});
Using AI Code Generation
1const { relativeTestPath } = require('@playwright/test');2const path = require('path');3const test = relativeTestPath(path.join(__dirname, 'test.spec.ts'));4module.exports = test;5import { test, expect } from '@playwright/test';6test('my test', async ({ page }) => {7 const name = await page.innerText('.navbar__title');8 expect(name).toBe('Playwright');9});
Using AI Code Generation
1const { relativeTestPath } = require('@playwright/test');2const test = require('@playwright/test').test;3const path = require('path');4test('test', async ({ page }) => {5 await page.goto(relativeTestPath(path.join(__dirname, 'index.html')));6 const title = await page.title();7 expect(title).toBe('Playwright Test');8});9const { test } = require('@playwright/test');10test.describe('My Test Suite', () => {11 test('test', async ({ page, testInfo }) => {12 await page.goto(`${testInfo.workingDirectory}/index.html`);13 const title = await page.title();14 expect(title).toBe('Playwright Test');15 });16});17const { test } = require('@playwright/test');18test.describe('My Test Suite', () => {19 test('test', async ({ page, testInfo }) => {20 await page.goto(`${testInfo.outputPath('index.html')}`);21 const title = await page.title();22 expect(title).toBe('Playwright Test');23 });24});25const { test } = require('@playwright/test');26test.describe('My Test Suite', () => {27 test('test', async ({ page, testInfo }) => {28 await page.screenshot({ path: testInfo.attachmentsPath('screenshot.png') });29 });30});31const { test } = require('@playwright/test');32test.describe('My Test Suite', () => {33 test('test', async ({ page, testInfo }) => {34 await page.screenshot({ path: testInfo.attachments.path('screenshot.png') });35 });36});37const { test } = require('@playwright/test');38test.describe('My Test Suite', () => {39 test('test', async ({ page, testInfo }) => {40 await page.screenshot({ path: testInfo.attachments.path('screenshot.png') });
Using AI Code Generation
1const { relativeTestPath } = require('@playwright/test');2const path = require('path');3const test = relativeTestPath(import.meta.url);4const testDir = path.dirname(test);5console.log(testDir);6const { test } = require('@playwright/test');7test('test', async ({ page }) => {8});
Using AI Code Generation
1const path = require('path');2const { test } = require('@playwright/test');3const { relativeTestPath } = require('@playwright/test/lib/utils/testPath');4test('test', async ({ page }) => {5 const relativePath = relativeTestPath(path.resolve(__dirname, './test.js'));6 console.log(relativePath);7});
Using AI Code Generation
1const { test } = require('@playwright/test');2test('relativeTestPath', async ({ page }) => {3 const testPath = test.relativeTestPath();4 console.log(testPath);5});6const { test } = require('@playwright/test');7test('relativeTestPath', async ({ page }) => {8 const testPath = test.relativeTestPath();9 console.log(testPath);10});11const { test } = require('@playwright/test');12test('relativeTestPath', async ({ page }) => {13 const testPath = test.relativeTestPath();14 console.log(testPath);15});16const { test } = require('@playwright/test');17test('relativeTestPath', async ({ page }) => {18 const testPath = test.relativeTestPath();19 console.log(testPath);20});21const { test } = require('@playwright/test');22test('relativeTestPath', async ({ page }) => {23 const testPath = test.relativeTestPath();24 console.log(testPath);25});26const { test } = require('@playwright/test');27test('relativeTestPath', async ({ page }) => {28 const testPath = test.relativeTestPath();29 console.log(testPath);30});31const { test } = require('@playwright/test');32test('relativeTestPath', async ({ page }) => {33 const testPath = test.relativeTestPath();34 console.log(testPath);35});36const { test } = require('@playwright/test');37test('relativeTestPath', async ({ page }) => {38 const testPath = test.relativeTestPath();39 console.log(testPath);40});
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!