Best JavaScript code snippet using playwright-internal
Client.js
Source: Client.js
...30 else {31 const errorMessage = this.hasFinishedOutput() ?32 'connection ended without disconnect receipt' :33 'connection ended unexpectedly';34 this.destroy(this.createProtocolError(errorMessage));35 }36 }37 _beforeSendResponse() {38 // No interception of outgoing frame39 }40 _onDestroyed(exception) {41 if (!exception) {42 return;43 }44 for (let key in this._subscriptions) {45 this._subscriptions[key].processMessageFrame(exception);46 }47 }48 /*49 * Create frame to send to the server. This method returns a Writable stream50 * object for sending the frame body content.51 */52 sendFrame(command, headers, options) {53 if (options) {54 let onReceipt = options.onReceipt;55 if (typeof options.onError === 'function') {56 const originalOnReceipt = onReceipt || function(){};57 const onError = options.onError;58 this.on('error', onError);59 onReceipt = () => {60 this.removeListener('error', onError);61 originalOnReceipt();62 };63 }64 if (typeof onReceipt === 'function') {65 const id = this._nextReceiptId++;66 this._receipts[id] = onReceipt;67 headers.receipt = id;68 }69 }70 return Socket.prototype.sendFrame.apply(this, arguments);71 }72 /*73 * Send CONNECT frame to the server.74 */75 connect(headers, callback) {76 if (typeof headers === 'string') {77 headers = {'host': headers};78 }79 headers = Object.assign({80 'accept-version': '1.0,1.1,1.2'81 }, headers);82 let heartbeat = this.getHeartbeat();83 if (typeof headers['heart-beat'] === "string") {84 const match = headers['heart-beat'].match(/^(\d+) *, *(\d+)$/);85 if (match) {86 heartbeat = [parseInt(match[1], 10), parseInt(match[2], 10)];87 this.setHeartbeat(heartbeat);88 }89 }90 headers['heart-beat'] = heartbeat[0] + "," + heartbeat[1];91 this.setCommandHandlers({92 'CONNECTED': onConnected,93 'ERROR': onError94 });95 if (typeof callback === 'function') {96 const self = this;97 (function() {98 const onConnected = function(client) {99 cleanup();100 callback(null, client);101 };102 const onError = function(error) {103 cleanup();104 callback(error);105 };106 const cleanup = function() {107 self.removeListener('error', onError);108 self.removeListener('connect', onConnected);109 };110 self.on('error', onError);111 self.on('connect', onConnected);112 })();113 }114 const frame = this.sendFrame('CONNECT', headers);115 frame.end();116 }117 /*118 * Send a message to the server. This method returns a Writable stream object 119 * for sending the frame body content.120 */121 send(headers, options) {122 if (typeof headers === 'string') {123 headers = {destination: headers};124 }125 return this.sendFrame('SEND', headers, options);126 }127 /*128 * Send a message with the specified body to the server.129 */130 sendString(headers, body, options, callback) {131 const frame = this.send(headers, options);132 frame.write(body);133 frame.end(callback);134 }135 begin(headers) {136 if (typeof headers !== 'object') {137 if (typeof headers !== 'undefined') {138 headers = {transaction: headers};139 }140 else {141 headers = {};142 }143 }144 if (!('transaction' in headers)) {145 headers.transaction = this._nextTransactionId++;146 }147 const transaction = new Transaction(headers.transaction, this);148 this.sendFrame('BEGIN', headers).end();149 return transaction;150 }151 subscribe(headers, messageListener) {152 if (typeof headers === 'string') {153 headers = {destination: headers};154 }155 let id = headers.id !== undefined ? 156 headers.id : this._nextSubcriptionId++;157 while (this._subscriptions[id] !== undefined) {158 id = this._nextSubcriptionId++;159 }160 headers.id = id;161 const ack = headers.ack || 'auto';162 ensureValidAckMode(ack);163 const subscription = new Subscription(id, ack, messageListener, this);164 this._subscriptions[id] = subscription;165 this.sendFrame('SUBSCRIBE', headers).end();166 return subscription;167 }168 _getAckHeaders(message, userHeaders) {169 return Object.assign({}, userHeaders, {170 'subscription': message.headers.subscription,171 'message-id': message.headers['message-id'],172 'id': message.headers.ack173 });174 }175 ack(message, headers, sendOptions, callback) {176 const frame = this.sendFrame('ACK',177 this._getAckHeaders(message, headers), sendOptions);178 frameHandler(frame, callback);179 }180 nack (message, headers, sendOptions, callback) {181 const frame = this.sendFrame('NACK',182 this._getAckHeaders(message, headers), sendOptions);183 frameHandler(frame, callback);184 }185 getSubscription(id) {186 return this._subscriptions[id];187 }188 setImplicitSubscription(id, ack, messageListener) {189 if (this._subscriptions.hasOwnProperty(id)) {190 throw new Error('subscription id \'' + id + '\' already in use');191 }192 if (ack === void 0 || ack === null){193 ack = 'auto';194 }195 ensureValidAckMode(ack);196 const subscription = new Subscription(id, ack, messageListener, this);197 this._subscriptions[id] = subscription;198 return subscription;199 }200 /*201 * Perform graceful disconnect from server. This operation does not complete202 * until all messages are acknowledged.203 */204 disconnect(callback) {205 if (typeof callback === 'function') {206 const self = this;207 (function() {208 const onEnd = function(client) {209 cleanup();210 callback(null, client);211 };212 const onError = function(error) {213 cleanup();214 callback(error);215 };216 const cleanup = function() {217 self.removeListener('end', onEnd);218 self.removeListener('error', onError);219 };220 self.on('end', onEnd);221 self.on('error', onError);222 })();223 }224 this.sendFrame('DISCONNECT', {}, {225 onReceipt: () => {226 this._hasDisconnectReceipt = true;227 const transport = this.getTransportSocket();228 if (this._resetDisconnect) {229 this.destroy();230 }231 else{232 transport.end();233 }234 }235 }).end(this._finishOutput.bind(this));236 // Keep the transport output open until the receipt is processed just in 237 // case the transport is not configured to handle half-open connections.238 this._disconnecting = true;239 }240 readEmptyBody(frame, callback) {241 frame.readEmptyBody((isEmpty) => {242 if (isEmpty) {243 if (typeof callback === 'function') {244 callback.call(this);245 }246 }247 else {248 this.destroy(this.createProtocolError('expected empty body frame'));249 }250 });251 }252 /*253 * Get the connection options that the client was initialized with.254 */255 getOptions() {256 return this._options;257 }258}259function ensureValidAckMode(mode) {260 const validAckModes = [261 'auto', 'client', 'client-individual'262 ];263 if (validAckModes.indexOf(mode) === -1) {264 throw new Error('invalid ack mode: \'' + mode + '\'');265 }266}267function frameHandler(frame, callback) {268 const cb = function (err) {269 if (typeof callback === 'function') {270 callback(err || new Error('The frame failed but no error was provided'));271 }272 };273 frame.on('error', cb);274 frame.end(function (err) {275 frame.removeListener('error', cb);276 if (typeof callback === 'function') {277 callback(err);278 }279 });280}281function onConnected(frame, beforeSendResponse) {282 // If no version header is present then assume the server is running stomp 1.0283 // protocol284 this.setVersion(frame.headers.version || '1.0');285 this.setCommandHandlers({286 'MESSAGE': onMessage,287 'RECEIPT': onReceipt,288 'ERROR': onError289 });290 this.readEmptyBody(frame, () => {291 if (frame.headers['heart-beat'] !== undefined) {292 const heartbeat = frame.headers['heart-beat']293 .split(',').map(function(x) {294 return parseInt(x, 10);295 });296 if ( heartbeat.length > 1 &&297 !isNaN(heartbeat[0]) &&298 !isNaN(heartbeat[1]) ) {299 this._runHeartbeat(heartbeat[0], heartbeat[1]);300 }301 }302 this.headers = frame.headers;303 this.emit('connect', this);304 beforeSendResponse();305 });306}307function onError(frame) {308 const message = frame.headers.message ? frame.headers.message :309 'server sent ERROR frame';310 const error = this.createApplicationError(message);311 if ( frame.headers['content-type'] === 'text/plain' &&312 frame.headers['content-length'] <= ERROR_MAX_CONTENT_LENGTH) {313 const content = new BufferWritable(Buffer.alloc(ERROR_MAX_CONTENT_LENGTH));314 frame.on('end', function() {315 error.longMessage = content.getWrittenSlice().toString();316 this.destroy(error);317 });318 frame.pipe(content);319 }320 else {321 this.destroy(error);322 }323}324function onMessage(frame, beforeSendResponse) {325 const subId = frame.headers.subscription;326 const subscription = this._subscriptions[subId];327 if (subscription === void 0) {328 this.destroy(this.createProtocolError('invalid subscription id ' + subId));329 return;330 }331 subscription.processMessageFrame(null, frame);332 beforeSendResponse();333}334function onReceipt(frame, beforeSendResponse) {335 const id = frame.headers['receipt-id'];336 if (id === undefined || this._receipts[id] === undefined) {337 this.destroy(this.createProtocolError('invalid receipt'));338 return;339 }340 this.readEmptyBody(frame, function() {341 this._receipts[id].call(this);342 delete this._receipts[id];343 beforeSendResponse();344 });345}346function onUnknownCommand(frame) {347 this.destroy(this.createProtocolError(348 'unknown command \'' + frame.command + '\''349 ));350}...
Connection.js
Source: Connection.js
...121 // Callbacks could be all rejected if someone has called `.dispose()`.122 if (callback) {123 this._callbacks.delete(object.id);124 if (object.error)125 callback.reject(createProtocolError(callback.error, callback.method, object));126 else127 callback.resolve(object.result);128 }129 } else {130 this.emit(object.method, object.params);131 }132 }133 _onClose() {134 if (this._closed)135 return;136 this._closed = true;137 this._transport.onmessage = null;138 this._transport.onclose = null;139 for (const callback of this._callbacks.values())140 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));141 this._callbacks.clear();142 for (const session of this._sessions.values())143 session._onClosed();144 this._sessions.clear();145 this.emit(Events.Connection.Disconnected);146 }147 dispose() {148 this._onClose();149 this._transport.close();150 }151 /**152 * @param {Protocol.Target.TargetInfo} targetInfo153 * @return {!Promise<!CDPSession>}154 */155 async createSession(targetInfo) {156 const {157 sessionId158 } = await this.send('Target.attachToTarget', {159 targetId: targetInfo.targetId,160 flatten: true161 });162 return this._sessions.get(sessionId);163 }164}165class CDPSession extends EventEmitter {166 /**167 * @param {!Connection} connection168 * @param {string} targetType169 * @param {string} sessionId170 */171 constructor(connection, targetType, sessionId) {172 super();173 /** @type {!Map<number, {resolve: function, reject: function, error: !Error, method: string}>}*/174 this._callbacks = new Map();175 this._connection = connection;176 this._targetType = targetType;177 this._sessionId = sessionId;178 }179 /**180 * @param {string} method181 * @param {!Object=} params182 * @return {!Promise<?Object>}183 */184 send(method, params = {}) {185 if (!this._connection)186 return Promise.reject(new Error(`Protocol error (${method}): Session closed. Most likely the ${this._targetType} has been closed.`));187 const id = this._connection._rawSend({188 sessionId: this._sessionId,189 method,190 params191 });192 return new Promise((resolve, reject) => {193 this._callbacks.set(id, {194 resolve,195 reject,196 error: new Error(),197 method198 });199 });200 }201 /**202 * @param {{id?: number, method: string, params: Object, error: {message: string, data: any}, result?: *}} object203 */204 _onMessage(object) {205 if (object.id && this._callbacks.has(object.id)) {206 const callback = this._callbacks.get(object.id);207 this._callbacks.delete(object.id);208 if (object.error)209 callback.reject(createProtocolError(callback.error, callback.method, object));210 else211 callback.resolve(object.result);212 } else {213 assert(!object.id);214 this.emit(object.method, object.params);215 }216 }217 async detach() {218 if (!this._connection)219 throw new Error(`Session already detached. Most likely the ${this._targetType} has been closed.`);220 await this._connection.send('Target.detachFromTarget', {221 sessionId: this._sessionId222 });223 }224 _onClosed() {225 for (const callback of this._callbacks.values())226 callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));227 this._callbacks.clear();228 this._connection = null;229 this.emit(Events.CDPSession.Disconnected);230 }231}232/**233 * @param {!Error} error234 * @param {string} method235 * @param {{error: {message: string, data: any}}} object236 * @return {!Error}237 */238function createProtocolError(error, method, object) {239 let message = `Protocol error (${method}): ${object.error.message}`;240 if ('data' in object.error)241 message += ` ${object.error.data}`;242 return rewriteError(error, message);243}244/**245 * @param {!Error} error246 * @param {string} message247 * @return {!Error}248 */249function rewriteError(error, message) {250 error.message = message;251 return error;252}...
wkConnection.js
Source: wkConnection.js
...158 dispatchMessage(object) {159 if (object.id && this._callbacks.has(object.id)) {160 const callback = this._callbacks.get(object.id);161 this._callbacks.delete(object.id);162 if (object.error) callback.reject(createProtocolError(callback.error, callback.method, object.error));else callback.resolve(object.result);163 } else if (object.id && !object.error) {164 // Response might come after session has been disposed and rejected all callbacks.165 (0, _utils.assert)(this.isDisposed());166 } else {167 Promise.resolve().then(() => this.emit(object.method, object.params));168 }169 }170}171exports.WKSession = WKSession;172function createProtocolError(error, method, protocolError) {173 let message = `Protocol error (${method}): ${protocolError.message}`;174 if ('data' in protocolError) message += ` ${JSON.stringify(protocolError.data)}`;175 return (0, _stackTrace.rewriteErrorMessage)(error, message);...
Using AI Code Generation
1const { createProtocolError } = require('playwright-core/lib/server/protocol/protocol');2const { assert } = require('console');3const assert = require('assert');4const { chromium } = require('playwright-core');5(async () => {6 const browser = await chromium.launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();12 at CDPSession.send (C:\Users\user\Documents\test\node_modules\playwright-core\lib\server\cdpSession.js:159:19)13 at CDPSession.send (C:\Users\user\Documents\test\node_modules\playwright-core\lib\server\cdp.js:42:37)14 at ExecutionContext.evaluateHandle (C:\Users\user\Documents\test\node_modules\playwright-core\lib\server\chromium\chromiumExecutionContext.js:105:37)15 at ExecutionContext.evaluate (C:\Users\user\Documents\test\node_modules\playwright-core\lib\server\chromium\chromiumExecutionContext.js:55:21)16 at Page.evaluate (C:\Users\user\Documents\test\node_modules\playwright-core\lib\server\chromium\chromiumPage.js:108:32)17 at Page.evaluate (C:\Users\user\Documents\test\node_modules\playwright-core\lib\server\page.js:88:29)18 at Page.screenshot (C:\Users\user\Documents\test\node_modules\playwright-core\lib\server\chromium\chromiumPage.js:113:33)19 at Page.screenshot (C:\Users\user\Documents\test\node_modules\playwright-core\lib\server\page.js:93:29)20 at Object.<anonymous> (C:\Users\user\Documents\test\test.js:17:13)21 at Module._compile (internal/modules/cjs/loader.js:1138:30)
Using AI Code Generation
1const { InternalError } = require('playwright');2const error = InternalError.createProtocolError('error message', 'error code');3console.log(error.message);4console.log(error.stack);5console.log(error.code);6const { InternalError } = require('playwright');7const error = InternalError.createCustomError('error message', 'error code');8console.log(error.message);9console.log(error.stack);10console.log(error.code);11const { InternalError } = require('playwright');12const error = InternalError.createTimeoutError('error message', 'error code');13console.log(error.message);14console.log(error.stack);15console.log(error.code);16const { InternalError } = require('playwright');17const error = InternalError.createEvaluationError('error message', 'error code');18console.log(error.message);19console.log(error.stack);20console.log(error.code);21const { InternalError } = require('playwright');22const error = InternalError.createError('error message', 'error code');23console.log(error.message);24console.log(error.stack);25console.log(error.code);26const { InternalError } = require('playwright');27const error = InternalError.createAssertionError('error message', 'error code');28console.log(error.message);29console.log(error.stack);30console.log(error.code);31const { TimeoutError } = require('playwright');32const error = TimeoutError.createError('error message', 'error code');33console.log(error.message);34console.log(error.stack);35console.log(error.code);36const { EvaluationError } = require('playwright');37const error = EvaluationError.createError('error message', 'error code');38console.log(error.message);39console.log(error.stack);40console.log(error.code);
Using AI Code Generation
1const { createProtocolError } = require('playwright-core/lib/server/instrumentation');2const error = createProtocolError('my error', { statusCode: 500, statusMessage: 'Internal Server Error' });3console.log(error);4const { createProtocolError } = require('playwright-core/lib/server/instrumentation');5const error = createProtocolError('my error', { statusCode: 500, statusMessage: 'Internal Server Error' });6console.log(error);7const { createProtocolError } = require('playwright-core/lib/server/instrumentation');8const error = createProtocolError('my error', { statusCode: 500, statusMessage: 'Internal Server Error' });9console.log(error);10const { createProtocolError } = require('playwright-core/lib/server/instrumentation');11const error = createProtocolError('my error', { statusCode: 500, statusMessage: 'Internal Server Error' });12console.log(error);13const { createProtocolError } = require('playwright-core/lib/server/instrumentation');14const error = createProtocolError('my error', { statusCode: 500, statusMessage: 'Internal Server Error' });15console.log(error);16const { createProtocolError } = require('playwright-core/lib/server/instrumentation');17const error = createProtocolError('my error', { statusCode: 500, statusMessage: 'Internal Server Error' });18console.log(error);19const { createProtocolError } = require('playwright-core/lib/server/instrumentation');20const error = createProtocolError('my error', { statusCode: 500, statusMessage: 'Internal Server Error' });21console.log(error);
Using AI Code Generation
1const { createProtocolError } = require('playwright/lib/server/supplements/utils/stackTrace');2const error = createProtocolError('my error', 'my error message');3console.log(error);4{5}6const { createProtocolError } = require('playwright/lib/server/supplements/utils/stackTrace');7const error = createProtocolError('my error', 'my error message');8console.log(error);9{10}11const { createProtocolError } = require('playwright/lib/server/supplements/utils/stackTrace');12const error = createProtocolError('my error', 'my error message');13console.log(error);14{15}16const { createProtocolError } = require('playwright/lib/server/supplements/utils/stackTrace');17const error = createProtocolError('my error', 'my error message');18console.log(error);19{20}21const { createProtocolError } = require('playwright/lib/server/supplements/utils/stackTrace');
Using AI Code Generation
1const { createProtocolError } = require('playwright/lib/server/protocol');2const error = createProtocolError('my error', 'custom error');3console.log(error);4{5 "error": {6 }7}
Using AI Code Generation
1const { Playwright } = require('playwright');2const { createProtocolError } = Playwright.InternalError;3const error = createProtocolError('Protocol error', 'error');4console.log(error);5const playwright = require('playwright');6const { createProtocolError } = require('playwright-internal-error');7const error = createProtocolError('Protocol error', 'error');8console.log(error);9[MIT](LICENSE)
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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!!