Best JavaScript code snippet using playwright-internal
Connection.js
Source:Connection.js
...96 if (object.id && this._callbacks.has(object.id)) {97 const callback = this._callbacks.get(object.id);98 this._callbacks.delete(object.id);99 if (object.error)100 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): ${object.error.message} ${object.error.data}`));101 else102 callback.resolve(object.result);103 } else {104 console.assert(!object.id);105 if (object.method === 'Target.receivedMessageFromTarget') {106 const session = this._sessions.get(object.params.sessionId);107 if (session)108 session._onMessage(object.params.message);109 } else if (object.method === 'Target.detachedFromTarget') {110 const session = this._sessions.get(object.params.sessionId);111 if (session)112 session._onClosed();113 this._sessions.delete(object.params.sessionId);114 } else {115 this.emit(object.method, object.params);116 }117 }118 }119 _onClose() {120 if (this._closeCallback) {121 this._closeCallback();122 this._closeCallback = null;123 }124 this._transport.removeAllListeners();125 // If transport throws any error at this point of time, we don't care and should swallow it.126 this._transport.on('error', () => {});127 for (const callback of this._callbacks.values())128 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));129 this._callbacks.clear();130 for (const session of this._sessions.values())131 session._onClosed();132 this._sessions.clear();133 }134 dispose() {135 this._onClose();136 this._transport.close();137 }138 /**139 * @param {string} targetId140 * @return {!Promise<!CDPSession>}141 */142 async createSession(targetId) {143 const {sessionId} = await this.send('Target.attachToTarget', {targetId});144 const session = new CDPSession(this, targetId, sessionId);145 this._sessions.set(sessionId, session);146 return session;147 }148}149class CDPSession extends EventEmitter {150 /**151 * @param {!Connection} connection152 * @param {string} targetId153 * @param {string} sessionId154 */155 constructor(connection, targetId, sessionId) {156 super();157 this._lastId = 0;158 /** @type {!Map<number, {resolve: function, reject: function, error: !Error, method: string}>}*/159 this._callbacks = new Map();160 this._connection = connection;161 this._targetId = targetId;162 this._sessionId = sessionId;163 }164 /**165 * @param {string} method166 * @param {!Object=} params167 * @return {!Promise<?Object>}168 */169 send(method, params = {}) {170 if (!this._connection)171 return Promise.reject(new Error(`Protocol error (${method}): Session closed. Most likely the page has been closed.`));172 const id = ++this._lastId;173 const message = JSON.stringify({id, method, params});174 debugSession('SEND ⺠' + message);175 this._connection.send('Target.sendMessageToTarget', {sessionId: this._sessionId, message}).catch(e => {176 // The response from target might have been already dispatched.177 if (!this._callbacks.has(id))178 return;179 const callback = this._callbacks.get(id);180 this._callbacks.delete(id);181 callback.reject(rewriteError(callback.error, e && e.message));182 });183 return new Promise((resolve, reject) => {184 this._callbacks.set(id, {resolve, reject, error: new Error(), method});185 });186 }187 /**188 * @param {string} message189 */190 _onMessage(message) {191 debugSession('â RECV ' + message);192 const object = JSON.parse(message);193 if (object.id && this._callbacks.has(object.id)) {194 const callback = this._callbacks.get(object.id);195 this._callbacks.delete(object.id);196 if (object.error)197 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): ${object.error.message} ${object.error.data}`));198 else199 callback.resolve(object.result);200 } else {201 console.assert(!object.id);202 this.emit(object.method, object.params);203 }204 }205 async detach() {206 await this._connection.send('Target.detachFromTarget', {sessionId: this._sessionId});207 }208 _onClosed() {209 for (const callback of this._callbacks.values())210 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));211 this._callbacks.clear();212 this._connection = null;213 }214}215helper.tracePublicAPI(CDPSession);216/**217 * @param {!Error} error218 * @param {string} message219 * @return {!Error}220 */221function rewriteError(error, message) {222 error.message = message;223 return error;224}...
crExecutionContext.js
Source:crExecutionContext.js
...109 await (0, _crProtocolHelper.releaseObject)(this._client, objectId);110 }111}112exports.CRExecutionContext = CRExecutionContext;113function rewriteError(error) {114 if (error.message.includes('Object reference chain is too long')) return {115 result: {116 type: 'undefined'117 }118 };119 if (error.message.includes('Object couldn\'t be returned by value')) return {120 result: {121 type: 'undefined'122 }123 };124 if (error instanceof TypeError && error.message.startsWith('Converting circular structure to JSON')) (0, _stackTrace.rewriteErrorMessage)(error, error.message + ' Are you passing a nested JSHandle?');125 if (!js.isJavaScriptErrorInEvaluate(error) && !(0, _protocolError.isSessionClosedError)(error)) throw new Error('Execution context was destroyed, most likely because of a navigation.');126 throw error;127}...
ffExecutionContext.js
Source:ffExecutionContext.js
...104function checkException(exceptionDetails) {105 if (!exceptionDetails) return;106 if (exceptionDetails.value) throw new js.JavaScriptErrorInEvaluate(JSON.stringify(exceptionDetails.value));else throw new js.JavaScriptErrorInEvaluate(exceptionDetails.text + (exceptionDetails.stack ? '\n' + exceptionDetails.stack : ''));107}108function rewriteError(error) {109 if (error.message.includes('cyclic object value') || error.message.includes('Object is not serializable')) return {110 result: {111 type: 'undefined',112 value: undefined113 }114 };115 if (error instanceof TypeError && error.message.startsWith('Converting circular structure to JSON')) (0, _stackTrace.rewriteErrorMessage)(error, error.message + ' Are you passing a nested JSHandle?');116 if (!js.isJavaScriptErrorInEvaluate(error) && !(0, _protocolError.isSessionClosedError)(error)) throw new Error('Execution context was destroyed, most likely because of a navigation.');117 throw error;118}119function potentiallyUnserializableValue(remoteObject) {120 const value = remoteObject.value;121 const unserializableValue = remoteObject.unserializableValue;122 return unserializableValue ? js.parseUnserializableValue(unserializableValue) : value;...
wkExecutionContext.js
Source:wkExecutionContext.js
...40 });41 if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description);42 return response.result.value;43 } catch (error) {44 throw rewriteError(error);45 }46 }47 async rawEvaluateHandle(expression) {48 try {49 const response = await this._session.send('Runtime.evaluate', {50 expression,51 contextId: this._contextId,52 returnByValue: false53 });54 if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description);55 return response.result.objectId;56 } catch (error) {57 throw rewriteError(error);58 }59 }60 rawCallFunctionNoReply(func, ...args) {61 this._session.send('Runtime.callFunctionOn', {62 functionDeclaration: func.toString(),63 objectId: args.find(a => a instanceof js.JSHandle)._objectId,64 arguments: args.map(a => a instanceof js.JSHandle ? {65 objectId: a._objectId66 } : {67 value: a68 }),69 returnByValue: true,70 emulateUserGesture: true71 }).catch(() => {});72 }73 async evaluateWithArguments(expression, returnByValue, utilityScript, values, objectIds) {74 try {75 const response = await this._session.send('Runtime.callFunctionOn', {76 functionDeclaration: expression,77 objectId: utilityScript._objectId,78 arguments: [{79 objectId: utilityScript._objectId80 }, ...values.map(value => ({81 value82 })), ...objectIds.map(objectId => ({83 objectId84 }))],85 returnByValue,86 emulateUserGesture: true,87 awaitPromise: true88 });89 if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description);90 if (returnByValue) return (0, _utilityScriptSerializers.parseEvaluationResultValue)(response.result.value);91 return utilityScript._context.createHandle(response.result);92 } catch (error) {93 throw rewriteError(error);94 }95 }96 async getProperties(context, objectId) {97 const response = await this._session.send('Runtime.getProperties', {98 objectId,99 ownProperties: true100 });101 const result = new Map();102 for (const property of response.properties) {103 if (!property.enumerable || !property.value) continue;104 result.set(property.name, context.createHandle(property.value));105 }106 return result;107 }108 createHandle(context, remoteObject) {109 const isPromise = remoteObject.className === 'Promise';110 return new js.JSHandle(context, isPromise ? 'promise' : remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));111 }112 async releaseHandle(objectId) {113 await this._session.send('Runtime.releaseObject', {114 objectId115 });116 }117}118exports.WKExecutionContext = WKExecutionContext;119function potentiallyUnserializableValue(remoteObject) {120 const value = remoteObject.value;121 const isUnserializable = remoteObject.type === 'number' && ['NaN', '-Infinity', 'Infinity', '-0'].includes(remoteObject.description);122 return isUnserializable ? js.parseUnserializableValue(remoteObject.description) : value;123}124function rewriteError(error) {125 if (!js.isJavaScriptErrorInEvaluate(error) && !(0, _protocolError.isSessionClosedError)(error)) return new Error('Execution context was destroyed, most likely because of a navigation.');126 return error;127}128function renderPreview(object) {129 if (object.type === 'undefined') return 'undefined';130 if ('value' in object) return String(object.value);131 if (object.description === 'Object' && object.preview) {132 const tokens = [];133 for (const {134 name,135 value136 } of object.preview.properties) tokens.push(`${name}: ${value}`);137 return `{${tokens.join(', ')}}`;138 }...
ExecutionContext.js
Source:ExecutionContext.js
...69 throw err;70 }71 const payload = await callFunctionPromise.catch(rewriteError);72 return createHandle(this, payload.result, payload.exceptionDetails);73 function rewriteError(error) {74 if (error.message.includes('Failed to find execution context with id'))75 throw new Error('Execution context was destroyed, most likely because of a navigation.');76 throw error;77 }78 }79 frame() {80 return this._frame;81 }82 async evaluate(pageFunction, ...args) {83 try {84 const handle = await this.evaluateHandle(pageFunction, ...args);85 const result = await handle.jsonValue();86 await handle.dispose();87 return result;...
logger.js
Source:logger.js
2import RavenWinston from 'raven-winston'3import { merge } from 'lodash'4import VError from 'verror'5import config from './config/environment'6function rewriteError(level, msg, meta) {7 const output = {}8 if (meta instanceof Error) {9 output.err = {10 stack: VError.fullStack(meta),11 message: meta.message,12 extra: meta.extra,13 }14 return output15 }16 Object.assign(output, meta)17 if (meta.err) {18 output.err = {19 stack: VError.fullStack(meta.err),20 message: meta.err.message,...
main.js
Source:main.js
...5import store from './store'6import {v4} from 'uuid';7Vue.prototype.$v4 = v4;8import rewriteError from './plugins/rewriteError'9rewriteError();10import 'iview/dist/styles/iview.css';11import {12 Button,13 ButtonGroup,14 Dropdown,15 DropdownItem,16 DropdownMenu,17 Input,18 Select,19 Option,20 Checkbox,21 CheckboxGroup,22 Page,23 Modal,...
httpError.js
Source:httpError.js
...11 status: res?.statusCode || err.statusCode,12 headers: res?.headers || err.headers,13 body: res?.text || err.text14 }15 const nerror = rewriteError({16 code: base.code,17 status: base.status,18 statusMessage: res?.statusMessage || err.statusMessage19 })20 nerror.requestError = true21 nerror.code = base.code22 nerror.status = base.status23 nerror.headers = base.headers24 nerror.body = base.body25 return nerror...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 try {7 } catch (e) {8 console.log(e.rewriteError('Rewriting error'));9 }10 await browser.close();11})();12 at runMicrotasks (<anonymous>)13 at processTicksAndRejections (internal/process/task_queues.js:93:5)14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 try {20 } catch (e) {21 console.log(e.rewriteError('Rewriting error'));22 }23 await browser.close();24})();25 at runMicrotasks (<anonymous>)26 at processTicksAndRejections (internal/process/task_queues.js:93:5)27const { chromium } = require('playwright');28(async () => {29 const browser = await chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();32 try {33 } catch (e) {34 console.log(e.rewriteError('Rewriting error'));35 }36 await browser.close();37})();38 at runMicrotasks (<anonymous>)39 at processTicksAndRejections (internal/process/task_queues.js:93:5
Using AI Code Generation
1const { Playwright } = require('@playwright/test');2const { rewriteError } = Playwright.InternalError;3const { expect } = require('@playwright/test');4const { test, expect } = require('@playwright/test');5test('test', async ({ page }) => {6 const error = new Error('Hello');7 ' at Script.runInThisContext (vm.js:133:18)\n' +8 ' at Object.runInThisContext (vm.js:310:38)\n' +9 ' at Object.<anonymous> (/Users/aslushnikov/Projects/playwright/test.js:1:1)\n' +10 ' at Module._compile (internal/modules/cjs/loader.js:1158:30)\n' +11 ' at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)\n' +12 ' at Module.load (internal/modules/cjs/loader.js:1002:32)\n' +13 ' at Function.Module._load (internal/modules/cjs/loader.js:901:14)\n' +14 ' at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)\n' +15 ' at internal/main/run_main_module.js:18:47';16 rewriteError(error);17 expect(error.stack).toContain('test.js');18});
Using AI Code Generation
1const { InternalError } = require('playwright/lib/utils/stackTrace');2InternalError.rewriteError = (error) => {3 }4 return error;5};6InternalError.rewriteError = (error) => {7 }8 return error;9};10InternalError.rewriteError = (error) => {11 }12 return error;13};14InternalError.rewriteError = (error) => {15 }16 return error;17};18InternalError.rewriteError = (error) => {
Using AI Code Generation
1const { rewriteError } = require('playwright/lib/utils/stackTrace');2const error = new Error('error message');3const rewrittenError = rewriteError(error, 'test.js');4console.log(rewrittenError.stack);5const { rewriteError } = require('playwright/lib/utils/stackTrace');6const error = new Error('error message');7const rewrittenError = rewriteError(error, 'test.js');8console.log(rewrittenError.stack);9### rewriteError(error, testFile)
Using AI Code Generation
1const { InternalError } = require('playwright/lib/internal/errors');2const { rewriteErrorMessage } = require('playwright/lib/internal/stackTrace');3const e = new InternalError('Error message');4console.log(rewriteErrorMessage(e, 'New error message'));5### `rewriteErrorMessage(error, message)`6### `rewriteErrorStack(error, message, stack)`
Using AI Code Generation
1const { rewriteError } = require('playwright/lib/utils/stackTrace');2const { rewriteError } = require('playwright/lib/utils/stackTrace');3const { test, expect } = require('@playwright/test');4test('test name', async ({ page }) => {5});6import { test, expect } from '@playwright/test';7test('test name', async ({ page }) => {8});
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!!