Best JavaScript code snippet using playwright-internal
parse.js
Source:parse.js
1/**2 * @fileoverview JSON parser3 * @author Nicholas C. Zakas4 */5//-----------------------------------------------------------------------------6// Imports7//-----------------------------------------------------------------------------8import { tokenize } from "./tokens.js";9import { types as t } from "./types.js";10import { escapeToChar } from "./syntax.js";11import { UnexpectedToken, ErrorWithLocation } from "./errors.js";12//-----------------------------------------------------------------------------13// Helpers14//-----------------------------------------------------------------------------15const DEFAULT_OPTIONS = {16 tokens: false,17 comments: false,18 ranges: false19};20/**21 * Converts a JSON-encoded string into a JavaScript string, interpreting each22 * escape sequence.23 * @param {Token} token The string token to convert into a JavaScript string.24 * @returns {string} A JavaScript string.25 */26function getStringValue(token) {27 28 // slice off the quotation marks29 let value = token.value.slice(1, -1);30 let result = "";31 let escapeIndex = value.indexOf("\\");32 let lastIndex = 0;33 // While there are escapes, interpret them to build up the result34 while (escapeIndex >= 0) {35 // append the text that happened before the escape36 result += value.slice(lastIndex, escapeIndex);37 // get the character immediately after the \38 const escapeChar = value.charAt(escapeIndex + 1);39 40 // check for the non-Unicode escape sequences first41 if (escapeToChar.has(escapeChar)) {42 result += escapeToChar.get(escapeChar);43 lastIndex = escapeIndex + 2;44 } else if (escapeChar === "u") {45 const hexCode = value.slice(escapeIndex + 2, escapeIndex + 6);46 if (hexCode.length < 4 || /[^0-9a-f]/i.test(hexCode)) {47 throw new ErrorWithLocation(48 `Invalid unicode escape \\u${ hexCode}.`,49 {50 line: token.loc.start.line,51 column: token.loc.start.column + escapeIndex,52 offset: token.loc.start.offset + escapeIndex53 }54 );55 }56 57 result += String.fromCharCode(parseInt(hexCode, 16));58 lastIndex = escapeIndex + 6;59 } else {60 throw new ErrorWithLocation(61 `Invalid escape \\${ escapeChar }.`,62 {63 line: token.loc.start.line,64 column: token.loc.start.column + escapeIndex,65 offset: token.loc.start.offset + escapeIndex66 }67 );68 }69 // find the next escape sequence70 escapeIndex = value.indexOf("\\", lastIndex);71 }72 // get the last segment of the string value73 result += value.slice(lastIndex);74 return result;75}76/**77 * Gets the JavaScript value represented by a JSON token.78 * @param {Token} token The JSON token to get a value for.79 * @returns {*} A number, string, boolean, or `null`. 80 */81function getLiteralValue(token) {82 switch (token.type) {83 case "Boolean":84 return token.value === "true";85 86 case "Number":87 return Number(token.value);88 case "Null":89 return null;90 case "String":91 return getStringValue(token);92 }93}94//-----------------------------------------------------------------------------95// Main Function96//-----------------------------------------------------------------------------97/**98 * 99 * @param {string} text The text to parse.100 * @param {boolean} [options.tokens=false] Determines if tokens are returned in101 * the AST. 102 * @param {boolean} [options.comments=false] Determines if comments are allowed103 * in the JSON.104 * @param {boolean} [options.ranges=false] Determines if ranges will be returned105 * in addition to `loc` properties.106 * @returns {Object} The AST representing the parsed JSON.107 * @throws {Error} When there is a parsing error. 108 */109export function parse(text, options) {110 options = Object.freeze({111 ...DEFAULT_OPTIONS,112 ...options113 });114 const tokens = tokenize(text, {115 comments: !!options.comments,116 ranges: !!options.ranges117 });118 let tokenIndex = 0;119 function nextNoComments() {120 return tokens[tokenIndex++];121 }122 123 function nextSkipComments() {124 const nextToken = tokens[tokenIndex++];125 if (nextToken && nextToken.type.endsWith("Comment")) {126 return nextSkipComments();127 }128 return nextToken;129 }130 // determine correct way to evaluate tokens based on presence of comments131 const next = options.comments ? nextSkipComments : nextNoComments;132 function assertTokenValue(token, value) {133 if (!token || token.value !== value) {134 throw new UnexpectedToken(token);135 }136 }137 function assertTokenType(token, type) {138 if (!token || token.type !== type) {139 throw new UnexpectedToken(token);140 }141 }142 function createRange(start, end) {143 return options.ranges ? {144 range: [start.offset, end.offset]145 } : undefined;146 }147 function createLiteralNode(token) {148 const range = createRange(token.loc.start, token.loc.end);149 return {150 type: token.type,151 value: getLiteralValue(token),152 loc: {153 start: {154 ...token.loc.start155 },156 end: {157 ...token.loc.end158 }159 },160 ...range161 };162 }163 function parseProperty(token) {164 assertTokenType(token, "String");165 const name = createLiteralNode(token);166 token = next();167 assertTokenValue(token, ":");168 const value = parseValue();169 const range = createRange(name.loc.start, value.loc.end);170 return t.member(name, value, {171 loc: {172 start: {173 ...name.loc.start174 },175 end: {176 ...value.loc.end177 }178 },179 ...range180 });181 }182 function parseObject(firstToken) {183 // The first token must be a { or else it's an error184 assertTokenValue(firstToken, "{");185 const members = [];186 let token = next();187 if (token && token.value !== "}") {188 do {189 190 // add the value into the array191 members.push(parseProperty(token));192 193 token = next();194 195 if (token.value === ",") {196 token = next();197 } else {198 break;199 }200 } while (token);201 }202 assertTokenValue(token, "}");203 const range = createRange(firstToken.loc.start, token.loc.end);204 return t.object(members, {205 loc: {206 start: {207 ...firstToken.loc.start208 },209 end: {210 ...token.loc.end211 }212 },213 ...range214 });215 }216 function parseArray(firstToken) {217 // The first token must be a [ or else it's an error218 assertTokenValue(firstToken, "[");219 const elements = [];220 let token = next();221 222 if (token && token.value !== "]") {223 do {224 // add the value into the array225 elements.push(parseValue(token));226 token = next();227 228 if (token.value === ",") {229 token = next();230 } else {231 break;232 }233 } while (token);234 }235 assertTokenValue(token, "]");236 const range = createRange(firstToken.loc.start, token.loc.end);237 return t.array(elements, {238 type: "Array",239 elements,240 loc: {241 start: {242 ...firstToken.loc.start243 },244 end: {245 ...token.loc.end246 }247 },248 ...range249 });250 }251 function parseValue(token) {252 token = token || next();253 254 switch (token.type) {255 case "String":256 case "Boolean":257 case "Number":258 case "Null":259 return createLiteralNode(token);260 case "Punctuator":261 if (token.value === "{") {262 return parseObject(token);263 } else if (token.value === "[") {264 return parseArray(token);265 }266 /*falls through*/267 default:268 throw new UnexpectedToken(token);269 }270 }271 272 const docBody = parseValue();273 274 const unexpectedToken = next();275 if (unexpectedToken) {276 throw new UnexpectedToken(unexpectedToken);277 }278 279 280 const docParts = {281 loc: {282 start: {283 line: 1,284 column: 1,285 offset: 0286 },287 end: {288 ...docBody.loc.end289 }290 }291 };292 293 if (options.tokens) {294 docParts.tokens = tokens;295 }296 if (options.ranges) {297 docParts.range = createRange(docParts.loc.start, docParts.loc.end);298 }299 return t.document(docBody, docParts);...
testType.js
Source:testType.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.rootTestType = exports.TestTypeImpl = exports.DeclaredFixtures = void 0;6var _expect = require("./expect");7var _globals = require("./globals");8var _test = require("./test");9var _transform = require("./transform");10var _util = require("./util");11/**12 * Copyright (c) Microsoft Corporation.13 *14 * Licensed under the Apache License, Version 2.0 (the "License");15 * you may not use this file except in compliance with the License.16 * You may obtain a copy of the License at17 *18 * http://www.apache.org/licenses/LICENSE-2.019 *20 * Unless required by applicable law or agreed to in writing, software21 * distributed under the License is distributed on an "AS IS" BASIS,22 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.23 * See the License for the specific language governing permissions and24 * limitations under the License.25 */26const countByFile = new Map();27class DeclaredFixtures {28 constructor() {29 this.testType = void 0;30 this.location = void 0;31 }32}33exports.DeclaredFixtures = DeclaredFixtures;34class TestTypeImpl {35 constructor(fixtures) {36 this.fixtures = void 0;37 this.test = void 0;38 this.fixtures = fixtures;39 const test = (0, _transform.wrapFunctionWithLocation)(this._createTest.bind(this, 'default'));40 test.expect = _expect.expect;41 test.only = (0, _transform.wrapFunctionWithLocation)(this._createTest.bind(this, 'only'));42 test.describe = (0, _transform.wrapFunctionWithLocation)(this._describe.bind(this, 'default'));43 test.describe.only = (0, _transform.wrapFunctionWithLocation)(this._describe.bind(this, 'only'));44 test.describe.serial = (0, _transform.wrapFunctionWithLocation)(this._describe.bind(this, 'serial'));45 test.describe.serial.only = (0, _transform.wrapFunctionWithLocation)(this._describe.bind(this, 'serial.only'));46 test.beforeEach = (0, _transform.wrapFunctionWithLocation)(this._hook.bind(this, 'beforeEach'));47 test.afterEach = (0, _transform.wrapFunctionWithLocation)(this._hook.bind(this, 'afterEach'));48 test.beforeAll = (0, _transform.wrapFunctionWithLocation)(this._hook.bind(this, 'beforeAll'));49 test.afterAll = (0, _transform.wrapFunctionWithLocation)(this._hook.bind(this, 'afterAll'));50 test.skip = (0, _transform.wrapFunctionWithLocation)(this._modifier.bind(this, 'skip'));51 test.fixme = (0, _transform.wrapFunctionWithLocation)(this._modifier.bind(this, 'fixme'));52 test.fail = (0, _transform.wrapFunctionWithLocation)(this._modifier.bind(this, 'fail'));53 test.slow = (0, _transform.wrapFunctionWithLocation)(this._modifier.bind(this, 'slow'));54 test.setTimeout = (0, _transform.wrapFunctionWithLocation)(this._setTimeout.bind(this));55 test.step = (0, _transform.wrapFunctionWithLocation)(this._step.bind(this));56 test.use = (0, _transform.wrapFunctionWithLocation)(this._use.bind(this));57 test.extend = (0, _transform.wrapFunctionWithLocation)(this._extend.bind(this));58 test.declare = (0, _transform.wrapFunctionWithLocation)(this._declare.bind(this));59 this.test = test;60 }61 _createTest(type, location, title, fn) {62 throwIfRunningInsideJest();63 const suite = (0, _globals.currentlyLoadingFileSuite)();64 if (!suite) throw (0, _util.errorWithLocation)(location, `test() can only be called in a test file`);65 const ordinalInFile = countByFile.get(suite._requireFile) || 0;66 countByFile.set(suite._requireFile, ordinalInFile + 1);67 const test = new _test.TestCase('test', title, fn, ordinalInFile, this, location);68 test._requireFile = suite._requireFile;69 suite._addTest(test);70 if (type === 'only') test._only = true;71 if (type === 'skip') test.expectedStatus = 'skipped';72 }73 _describe(type, location, title, fn) {74 throwIfRunningInsideJest();75 const suite = (0, _globals.currentlyLoadingFileSuite)();76 if (!suite) throw (0, _util.errorWithLocation)(location, `describe() can only be called in a test file`);77 if (typeof title === 'function') {78 throw (0, _util.errorWithLocation)(location, ['It looks like you are calling describe() without the title. Pass the title as a first argument:', `test.describe('my test group', () => {`, ` // Declare tests here`, `});`].join('\n'));79 }80 const child = new _test.Suite(title);81 child._requireFile = suite._requireFile;82 child._isDescribe = true;83 child.location = location;84 suite._addSuite(child);85 if (type === 'only' || type === 'serial.only') child._only = true;86 if (type === 'serial' || type === 'serial.only') child._serial = true;87 (0, _globals.setCurrentlyLoadingFileSuite)(child);88 fn();89 (0, _globals.setCurrentlyLoadingFileSuite)(suite);90 }91 _hook(name, location, fn) {92 const suite = (0, _globals.currentlyLoadingFileSuite)();93 if (!suite) throw (0, _util.errorWithLocation)(location, `${name} hook can only be called in a test file`);94 if (name === 'beforeAll' || name === 'afterAll') {95 const hook = new _test.TestCase(name, name, fn, 0, this, location);96 hook._requireFile = suite._requireFile;97 suite._addAllHook(hook);98 } else {99 suite._eachHooks.push({100 type: name,101 fn,102 location103 });104 }105 }106 _modifier(type, location, ...modifierArgs) {107 const suite = (0, _globals.currentlyLoadingFileSuite)();108 if (suite) {109 if (typeof modifierArgs[0] === 'string' && typeof modifierArgs[1] === 'function') {110 // Support for test.skip('title', () => {})111 this._createTest('skip', location, modifierArgs[0], modifierArgs[1]);112 return;113 }114 if (typeof modifierArgs[0] === 'function') {115 suite._modifiers.push({116 type,117 fn: modifierArgs[0],118 location,119 description: modifierArgs[1]120 });121 } else {122 if (modifierArgs.length >= 1 && !modifierArgs[0]) return;123 const description = modifierArgs[1];124 suite._annotations.push({125 type,126 description127 });128 }129 return;130 }131 const testInfo = (0, _globals.currentTestInfo)();132 if (!testInfo) throw (0, _util.errorWithLocation)(location, `test.${type}() can only be called inside test, describe block or fixture`);133 if (typeof modifierArgs[0] === 'function') throw (0, _util.errorWithLocation)(location, `test.${type}() with a function can only be called inside describe block`);134 testInfo[type](...modifierArgs);135 }136 _setTimeout(location, timeout) {137 const suite = (0, _globals.currentlyLoadingFileSuite)();138 if (suite) {139 suite._timeout = timeout;140 return;141 }142 const testInfo = (0, _globals.currentTestInfo)();143 if (!testInfo) throw (0, _util.errorWithLocation)(location, `test.setTimeout() can only be called from a test`);144 testInfo.setTimeout(timeout);145 }146 _use(location, fixtures) {147 const suite = (0, _globals.currentlyLoadingFileSuite)();148 if (!suite) throw (0, _util.errorWithLocation)(location, `test.use() can only be called in a test file`);149 suite._use.push({150 fixtures,151 location152 });153 }154 async _step(location, title, body) {155 const testInfo = (0, _globals.currentTestInfo)();156 if (!testInfo) throw (0, _util.errorWithLocation)(location, `test.step() can only be called from a test`);157 const complete = testInfo._addStep('test.step', title);158 try {159 await body();160 complete();161 } catch (e) {162 complete((0, _util.serializeError)(e));163 throw e;164 }165 }166 _extend(location, fixtures) {167 const fixturesWithLocation = {168 fixtures,169 location170 };171 return new TestTypeImpl([...this.fixtures, fixturesWithLocation]).test;172 }173 _declare(location) {174 const declared = new DeclaredFixtures();175 declared.location = location;176 const child = new TestTypeImpl([...this.fixtures, declared]);177 declared.testType = child;178 return child.test;179 }180}181exports.TestTypeImpl = TestTypeImpl;182function throwIfRunningInsideJest() {183 if (process.env.JEST_WORKER_ID) {184 throw new Error(`Playwright Test needs to be invoked via 'npx playwright test' and excluded from Jest test runs.\n` + `Creating one directory for Playwright tests and one for Jest is the recommended way of doing it.\n` + `See https://playwright.dev/docs/intro/ for more information about Playwright Test.`);185 }186}187const rootTestType = new TestTypeImpl([]);...
util.js
Source:util.js
...179}180function errorWithFile(file, message) {181 return new Error(`${relativeFilePath(file)}: ${message}`);182}183function errorWithLocation(location, message) {184 return new Error(`${formatLocation(location)}: ${message}`);185}186function expectType(receiver, type, matcherName) {187 if (typeof receiver !== 'object' || receiver.constructor.name !== type) throw new Error(`${matcherName} can be only used with ${type} object`);188}189function sanitizeForFilePath(s) {190 return s.replace(/[\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, '-');...
formatCode.js
Source:formatCode.js
1/*2 * Copyright (c) 2015-present, Facebook, Inc.3 * All rights reserved.4 *5 * This source code is licensed under the license found in the LICENSE file in6 * the root directory of this source tree.7 *8 * @flow9 */10/* globals atom */11import type {SourceOptions} from '../common/options/SourceOptions';12type ErrorWithLocation = {loc?: {line: number, column: number}};13async function formatCode(options: SourceOptions, editor_: ?TextEditor): Promise<void> {14 const editor = editor_ || atom.workspace.getActiveTextEditor();15 if (!editor) {16 // eslint-disable-next-line no-console17 console.log('- format-js: No active text editor');18 return;19 }20 // Save things21 const buffer = editor.getBuffer();22 const inputSource = buffer.getText();23 // Auto-require transform.24 const {outputSource, error} = transformCodeOrShowError(inputSource, options);25 // Update position if source has a syntax error26 if (error && atom.config.get('nuclide-format-js.moveCursorToSyntaxError')) {27 const position = syntaxErrorPosition(error);28 if (position) {29 editor.setCursorBufferPosition(position);30 }31 }32 // Update the source and position after all transforms are done. Do nothing33 // if the source did not change at all.34 if (outputSource === inputSource) {35 return;36 }37 buffer.setTextViaDiff(outputSource);38 // Save the file if that option is specified.39 if (atom.config.get('nuclide-format-js.saveAfterRun')) {40 editor.save();41 }42}43function transformCodeOrShowError(44 inputSource: string,45 options: SourceOptions,46): {outputSource: string, error?: ErrorWithLocation} {47 const {transform} = require('../common');48 // TODO: Add a limit so the transform is not run on files over a certain size.49 let outputSource;50 try {51 outputSource = transform(inputSource, options);52 } catch (error) {53 showErrorNotification(error);54 return {outputSource: inputSource, error};55 }56 dismissExistingErrorNotification();57 if (58 outputSource === inputSource &&59 // Do not confirm success if user opted out60 atom.config.get('nuclide-format-js.confirmNoChangeSuccess')61 ) {62 showSuccessNotification();63 }64 return {outputSource};65}66const ERROR_TITLE = 'Nuclide Format JS: Fix Requires failed';67function showErrorNotification(error: Error): void {68 dismissExistingErrorNotification();69 dismissExistingSuccessNotification();70 atom.notifications.addError(ERROR_TITLE, {71 detail: error.toString(),72 stack: error.stack,73 dismissable: true,74 });75}76function dismissExistingErrorNotification(): void {77 dismissNotification(ERROR_TITLE);78}79const SUCCESS_TITLE = 'Nuclide Format JS: Fix Requires succeeded';80let dismissSuccessNotificationTimeout;81function showSuccessNotification(): void {82 dismissExistingSuccessNotification();83 atom.notifications.addSuccess(SUCCESS_TITLE, {84 detail: 'No changes were needed.',85 dismissable: true,86 });87 dismissSuccessNotificationTimeout = setTimeout(() => {88 dismissExistingSuccessNotification();89 }, 2000);90}91function dismissExistingSuccessNotification(): void {92 dismissNotification(SUCCESS_TITLE);93 clearTimeout(dismissSuccessNotificationTimeout);94}95function dismissNotification(title: string): void {96 atom.notifications.getNotifications()97 .filter(notification => notification.getMessage() === title)98 .forEach(notification => notification.dismiss());99}100function syntaxErrorPosition(error: ErrorWithLocation): ?[number, number] {101 const {line, column} = error.loc || {};102 return Number.isInteger(line) && Number.isInteger(column)103 ? [line - 1, column]104 : null;105}...
errors.js
Source:errors.js
1/**2 * @fileoverview JSON tokenization/parsing errors3 * @author Nicholas C. Zakas4 */5/**6 * Base class that attaches location to an error.7 */8export class ErrorWithLocation extends Error {9 /**10 * 11 * @param {string} message The error message to report. 12 * @param {int} loc.line The line on which the error occurred.13 * @param {int} loc.column The column in the line where the error occurrred.14 * @param {int} loc.index The index in the string where the error occurred.15 */16 constructor(message, { line, column, index }) {17 super(`${ message } (${ line }:${ column})`);18 /**19 * The line on which the error occurred.20 * @type int21 * @property line22 */23 this.line = line;24 /**25 * The column on which the error occurred.26 * @type int27 * @property column28 */29 this.column = column;30 31 /**32 * The index into the string where the error occurred.33 * @type int34 * @property index35 */36 this.index = index;37 }38}39/**40 * Error thrown when an unexpected character is found during tokenizing.41 */42export class UnexpectedChar extends ErrorWithLocation {43 /**44 * Creates a new instance.45 * @param {string} unexpected The character that was found.46 * @param {Object} loc The location information for the found character.47 */48 constructor(unexpected, loc) {49 super(`Unexpected character ${ unexpected } found.`, loc);50 }51}52/**53 * Error thrown when an unexpected token is found during parsing.54 */55export class UnexpectedToken extends ErrorWithLocation {56 /**57 * Creates a new instance.58 * @param {string} expected The character that was expected. 59 * @param {string} unexpected The character that was found.60 * @param {Object} loc The location information for the found character.61 */62 constructor(token) {63 super(`Unexpected token ${ token.type }(${ token.value }) found.`, token.loc.start);64 }65}66/**67 * Error thrown when the end of input is found where it isn't expected.68 */69export class UnexpectedEOF extends ErrorWithLocation {70 /**71 * Creates a new instance.72 * @param {Object} loc The location information for the found character.73 */74 constructor(loc) {75 super("Unexpected end of input found.", loc);76 }...
index.js
Source:index.js
1#!/usr/bin/env node2import meow from "meow";3import { getLogger } from "./logger";4import { getSources } from "./file-system";5import { importModule } from "./module";6import { createGlobalScope } from "@hegel/core";7import { createASTGenerator } from "./parser";8import { mixTypeDefinitions } from "./typings";9import { getConfig, createConfig } from "./config";10import { getErrorsPrint, getVerdictPrint } from "./printer";11import type { ErrorWithLocation } from "./printer";12import type { ExtendedFile, HegelError } from "@hegel/core";13const logger = getLogger();14const helpMessage = `15Usage16 $ hegel [COMMAND]17Valid values for COMMAND:18 init Initializes a directory to be used as a Hegel root directory 19 version Print version number and exit20`;21const CLI = meow(helpMessage, {22 input: ["init"],23});24const COMMAND = CLI.input[0];25switch (COMMAND) {26 case "init":27 createConfig();28 logger.log("Project initialized.");29 break;30 case "version":31 CLI.showVersion();32 break;33 case undefined:34 main();35 break;36 default:37 logger.error(`Unsupported command "${COMMAND}"!`);38}39async function main() {40 try {41 const config = await getConfig();42 const getFileAST = createASTGenerator(config);43 const sources = await getSources(config);44 let errors: Array<ErrorWithLocation> = [];45 try {46 const asts: Array<ExtendedFile> = await Promise.all(47 sources.map((file) => getFileAST(file))48 );49 const result = await createGlobalScope(50 asts,51 importModule(config, getFileAST, true),52 false,53 await mixTypeDefinitions(config, getFileAST)54 );55 errors = result[1];56 } catch (e) {57 if (!(e instanceof SyntaxError)) {58 throw e;59 }60 errors = [e];61 }62 const result = await getErrorsPrint(errors);63 const verdict = getVerdictPrint(errors);64 logger.log(`${result}${verdict}`);65 void process.exit(errors.length);66 } catch (e) {67 if (e instanceof Error) {68 logger.error(e.message);69 }70 void process.exit(1);71 }...
printer.js
Source:printer.js
1import chalk from "chalk";2import { getFileContent } from "./parser";3import { codeFrameColumns } from "@babel/code-frame";4import type { HegelError } from "@hegel/core";5import type { ExtendedSyntaxError } from "@babel/parser";6export type ErrorWithLocation = HegelError | ExtendedSyntaxError;7export function printSingleError(8 error: ErrorWithLocation,9 fileContent: string10) {11 const loc =12 "start" in error.loc13 ? error.loc14 : {15 start: error.loc,16 end: Object.assign(error.loc, { column: error.loc.column + 1 }),17 };18 const line = chalk.dim.underline(`${error.source}:${String(loc.start.line)}`);19 const codeFrame = codeFrameColumns(fileContent, loc, {20 highlightCode: true,21 message: error.message.replace(/\([\d:]+\)/gi, ""),22 });23 return `${line}\n${codeFrame}`;24}25export async function getErrorsPrint(errors: Array<ErrorWithLocation>) {26 let result = "";27 for (const error of errors) {28 if (error === undefined || error.source === "") {29 continue;30 }31 const content = await getFileContent(error.source);32 result = `${result}${printSingleError(error, content)}\n\n`;33 }34 return result;35}36export function getVerdictPrint(errors) {37 return errors.length > 038 ? `Found ${String(errors.length)} error${errors.length > 1 ? "s" : ""}`39 : "No errors!";...
utils.js
Source:utils.js
1// @flow2import { type Position } from "./tokenizer";3export function positionToString( pos: Position ) {4 return `${pos.line}:${pos.column}`;5}6class ErrorWithLocation extends Error {7 +originalMessage: string;8 +loc: Position;9 constructor( message: string, loc: Position ) {10 super( `${message} (at ${positionToString( loc )})` );11 this.originalMessage = message;12 this.loc = loc;13 }14}15export function error( message: string, loc: Position ): ErrorWithLocation {16 return new ErrorWithLocation( message, loc );...
Using AI Code Generation
1const { errorWithLocation } = require('@playwright/test/lib/utils/stackTrace');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 const element = await page.$('foobar');5 throw errorWithLocation('Element not found', element);6});7 at Object.<anonymous> (/home/suraj/playwright/test.js:8:11)8 at step (/home/suraj/playwright/test.js:33:23)9 at Object.throw (/home/suraj/playwright/test.js:14:53)10 at rejected (/home/suraj/playwright/test.js:6:65)11 at process._tickCallback (internal/process/next_tick.js:188:7)12 at step (/home/suraj/playwright/test.js:33:23)13 at Object.throw (/home/suraj/playwright/test.js:14:53)14 at rejected (/home/suraj/playwright/test.js:6:65)15 at process._tickCallback (internal/process/next_tick.js:188:7)16const { errorWithLocation } = require('@playwright/test/lib/utils/stackTrace');17const { test } = require('@playwright/test');18test('test', async ({ page }) => {19 const element = await page.$('foobar');20 throw errorWithLocation('Element not found', element);21});22 at Object.<anonymous> (/home/suraj/playwright/test.js:8:11)23 at step (/home/suraj/playwright/test.js:33:23)24 at Object.throw (/home/suraj/playwright/test.js:14:53)25 at rejected (/home/suraj/playwright/test.js:6:65)
Using AI Code Generation
1const { errorWithLocation } = require('playwright/lib/utils/stackTrace');2const { parseError } = require('playwright/lib/utils/stackTrace');3const err = new Error('some error');4 at Object.<anonymous> (C:\\Users\\user\\Desktop\\test.js:7:11)5 at Module._compile (internal/modules/cjs/loader.js:1158:30)6 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)7 at Module.load (internal/modules/cjs/loader.js:1002:32)8 at Function.Module._load (internal/modules/cjs/loader.js:901:14)9 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)10`;11const errWithLocation = errorWithLocation(err, 'test.js', 7, 11);12console.log(parseError(errWithLocation));
Using AI Code Generation
1const { InternalError } = require('playwright/lib/server/errors');2const { errorWithLocation } = InternalError;3console.log(err.stack);4console.log(err.message);5console.log(err.location);6console.log(err.name);7 at Object.<anonymous> (/Users/xxxxx/xxxxx/xxxxx/test.js:7:28)8 at Module._compile (internal/modules/cjs/loader.js:1063:30)9 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)10 at Module.load (internal/modules/cjs/loader.js:928:32)11 at Function.Module._load (internal/modules/cjs/loader.js:769:14)12 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Using AI Code Generation
1const { errorWithLocation } = require('@playwright/test/lib/utils/stackTrace');2const error = new Error('Error with location');3errorWithLocation(error);4const { errorWithCallLocation } = require('@playwright/test/lib/utils/stackTrace');5const error = new Error('Error with call location');6errorWithCallLocation(error);7const { errorWithMetadata } = require('@playwright/test/lib/utils/stackTrace');8const error = new Error('Error with metadata');9errorWithMetadata(error, { metadata: 'metadata' });10const { formatError } = require('@playwright/test/lib/utils/stackTrace');11const error = new Error('Error with format');12formatError(error);13const { formatStackTrace } = require('@playwright/test/lib/utils/stackTrace');14const error = new Error('Error with format');15formatStackTrace(error);16const { getCallFrames } = require('@playwright/test/lib/utils/stackTrace');17const error = new Error('Error with call frames');18getCallFrames(error);19const { getErrorLocation } = require('@playwright/test/lib/utils/stackTrace');20const error = new Error('Error with location');21getErrorLocation(error);22const { getErrorMetadata } = require('@playwright/test/lib/utils/stackTrace');23const error = new Error('Error with metadata');24getErrorMetadata(error);25const { getErrorTitle } = require('@playwright/test/lib/utils/stackTrace');26const error = new Error('Error with title');27getErrorTitle(error);28const { getErrorTitleFromFrames } = require('@playwright/test/lib/utils/stackTrace');29const error = new Error('Error with title from frames');30getErrorTitleFromFrames(error);31const { getErrorTitleFromMessage } = require('@playwright/test/lib
Using AI Code Generation
1const { InternalError } = require('playwright/lib/utils/errors');2const error = new InternalError('Error message');3const newError = error.errorWithLocation('file.js', 2, 10);4console.log(newError);5import { errorWithLocation } from '@playwright/test';6const newError = errorWithLocation(new Error('Error message'), 'file.js', 2, 10);7console.log(newError);8 at errorWithLocation (file.js:2:10)9I am using playwright test runner for my project. I need to write a custom reporter in which I need to use errorWithLocation method of Playwright Test Runner. I am not able to import it in my reporter. I tried importing it in the following ways:10import { errorWithLocation } from '@playwright/test';11import { errorWithLocation } from 'playwright/lib/utils/errors';12import { errorWithLocation } from 'playwright';13import { errorWithLocation } from 'playwright-core';14import { errorWithLocation } from 'playwright-test';15import { errorWithLocation } from 'playwright-test-core';16import { errorWithLocation } from 'playwright-test-core';
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('should fail', async ({ page }) => {3 try {4 await page.click('non-existing');5 } catch (error) {6 console.log(error);7 }8});9const { test, expect } = require('@playwright/test');10test('should fail', async ({ page }) => {11 try {12 await page.click('non-existing');13 } catch (error) {14 console.log(error.errorWithLocation());15 }16});17const { test, expect } = require('@playwright/test');18test('should fail', async ({ page }) => {19 try {20 await page.click('non-existing');21 } catch (error) {22 console.log(error.errorWithLocation());23 }24});25The errorWithLocation() method returns a string with the location
Using AI Code Generation
1const { errorWithLocation } = require('playwright/lib/utils/stackTrace');2const error = new Error('test error');3errorWithLocation(error, 'test.js');4console.log(error.stack);5const { errorWithLocation } = require('playwright/lib/utils/stackTrace');6const error = new Error('test error');7errorWithLocation(error, 'test.js');8console.log(error.stack);9 at Object.<anonymous> (/Users/username/path/to/test.js:5:1)10 at Module._compile (internal/modules/cjs/loader.js:1063:30)11 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)12 at Module.load (internal/modules/cjs/loader.js:928:32)13 at Function.Module._load (internal/modules/cjs/loader.js:769:14)14 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Using AI Code Generation
1const { errorWithLocation } = require('@playwright/test');2const error = new Error('Test Error');3error.stack = errorWithLocation(error.stack, 'test.js', 2, 5);4throw error;5const { test, expect } = require('@playwright/test');6test('My test', async ({ page }) => {7 const title = page.locator('text=Get started');8 expect(title).toBeVisible();9});10 at Object.<anonymous> (test.js:4:9)11 at Object.<anonymous> (test.spec.js:4:1)12 at Object.<anonymous> (test.spec.js:6:1)13 at Object.<anonymous> (test.js:4:9)14 at Object.<anonymous> (test.spec.js:4:1)15 at Object.<anonymous> (test.spec.js:6:1)16 expect(received).toBeVisible()17 › Object.<anonymous> (test.spec.js:6:1)18 › Object.<anonymous> (test.spec.js:8:1)19 at Object.<anonymous> (test.js:4:9)20 at Object.<anonymous> (test.spec.js:4:1)21 at Object.<anonymous> (test.spec.js:6:1)
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!!