Best JavaScript code snippet using playwright-internal
index.js
Source:index.js
1/* eslint-disable func-names */2import _ from 'lodash';3import co from 'co';4import cmds from './commands';5function extractor() {6 // MySQL does a weird thing on certain queries, where it wraps the result into a second array, this is7 // a workaround until I figure out why and when the driver does this8 // - The 1st array is a RowDataPacket9 // - The 2nd array is a FieldPacket10 const getRows = function (result) {11 if (Array.isArray(result) && result.length > 0) {12 if (Array.isArray(result[0])) {13 return result[0];14 }15 }16 return result;17 };18 return {19 extract: function extract(knex) {20 return co(function*() {21 const db = {22 driver: 'mysql',23 variant: {},24 catalog: getRows(yield cmds.getCatalog(knex))[0].name,25 dataTypes: _.keyBy(_.map(getRows(yield cmds.getDataTypes(knex)), function (row) {26 return {27 typeName: row.typeName,28 isUserDefined: row.isUserDefined === 1,29 isAssemblyType: row.isAssemblyType === 1,30 hasMaxLength: row.hasMaxLength === 1,31 hasPrecision: row.hasPrecision === 1,32 hasScale: row.hasScale === 133 };34 }), 'typeName'),35 schemas: {},36 };37 _.forEach(getRows(yield cmds.getVersionInfo(knex)), function (row) {38 if (row.Variable_name === 'version') {39 db.variant.productVersion = row.Value;40 } else if (row.Variable_name === 'version_comment') {41 db.variant.edition = row.Value;42 } else if (row.Variable_name === 'protocol_version') {43 db.variant.productLevel = row.Value;44 }45 });46 if (db.variant.productVersion && db.variant.productVersion.length > 0) {47 db.variant.majorVersion = `MySQL ${db.variant.productVersion.split('.')[0]}`;48 }49 // get database users50 // db.users = _.map(getRows(yield cmds.getUsers(knex)), 'name');51 // in MySQL, a schema is a database, so always default the schema to the current database52 // we also want to pre-populate all the tables on each schema before we iterate53 // through and populate table details54 // the following would retrieve a list of all databases the current user has access to,55 // this is not what we want in our case, so default instead to the current database56 // const schemaNames = _.map(getRows(yield cmds.getSchemas(knex)), 'name');57 const schemaNames = [db.catalog];58 for (let i = 0; i < schemaNames.length; i++) {59 const schemaName = schemaNames[i];60 // get schema tables61 const tables = getRows(yield cmds.getTables(knex, schemaName));62 if (tables.length === 0) continue;63 const schema = {64 name: schemaName,65 tables: _.keyBy(_.map(tables, function (t) {66 return {67 name: t.name,68 description: t.description,69 };70 }), 'name'),71 };72 db.schemas[schemaName] = schema;73 // get schema table columns74 const schemaTableColumns = _.map(getRows(yield cmds.getTableColumns(knex, schema.name)), function (row) {75 return {76 table: row.table,77 name: row.name,78 description: '', // gets populated later79 ordinal: row.ordinal,80 dataType: row.dataType,81 maxLength: row.maxLength,82 precision: row.precision,83 scale: row.scale,84 dateTimePrecision: row.dateTimePrecision,85 characterSet: row.characterSet,86 collation: row.collation,87 isNullable: row.isNullable === 1,88 default: row.default ? { expression: row.default, constraintName: null } : null, // gets populated later89 isIdentity: false, // gets populated later90 isPartOfPrimaryKey: false, // gets populated later91 isPrimaryKey: false, // gets populated later92 isComputed: false, // gets populated later93 isPartOfUniqueKey: false, // gets populated later94 isUnique: false, // gets populated later95 isForeignKey: false // gets populated later96 };97 });98 _.forEach(schema.tables, function (table) {99 table.columns = _.keyBy(_.filter(schemaTableColumns, { table: table.name }), 'name');100 // remove the table property101 _.forEach(table.columns, function (col) {102 _.unset(col, 'schema');103 _.unset(col, 'table');104 });105 });106 // get schema views107 const views = getRows(yield cmds.getViews(knex, schemaName));108 if (views.length > 0) {109 schema.views = _.keyBy(_.map(views, function (v) {110 return {111 name: v.name,112 description: v.description,113 sql: v.sql114 };115 }), 'name');116 }117 // get schema view columns118 const schemaViewColumns = _.map(getRows(yield cmds.getViewColumns(knex, schema.name)), function (row) {119 return {120 view: row.view,121 name: row.name,122 ordinal: row.ordinal,123 dataType: row.dataType,124 maxLength: row.maxLength,125 precision: row.precision,126 scale: row.scale,127 dateTimePrecision: row.dateTimePrecision,128 characterSet: row.characterSet,129 collation: row.collation,130 isNullable: row.isNullable === 1131 };132 });133 _.forEach(schema.views, function (view) {134 view.columns = _.keyBy(_.filter(schemaViewColumns, { view: view.name }), 'name');135 // remove the view property136 _.forEach(view.columns, function (col) {137 _.unset(col, 'schema');138 _.unset(col, 'view');139 });140 });141 }142 // now that all tables are populated on all schemas with their columns143 // let's get the rest of the info144 for (let i = 0; i < schemaNames.length; i++) {145 const schemaName = schemaNames[i];146 const schema = db.schemas[schemaName];147 if (!schema) continue;148 const schemaColumnDefaultConstraint = getRows(yield cmds.getDefaultConstraints(knex, schema.name));149 const schemaColumnIdentityDefinitions = getRows(yield cmds.getIdentityDefinitions(knex, schema.name));150 const schemaComputedColumnDefinitions = getRows(yield cmds.getComputedColumnDefinitions(knex, schema.name));151 _.forEach(schemaComputedColumnDefinitions, function (scdd) {152 if (scdd.definition && scdd.definition.length > 0) {153 schema.tables[scdd.table].columns[scdd.name].isComputed = true;154 schema.tables[scdd.table].columns[scdd.name].computedDefinition = scdd.definition;155 }156 });157 _.forEach(schemaColumnDefaultConstraint, function (scdc) {158 if (scdc.expression && scdc.expression.length > 0) {159 const dcc = schema.tables[scdc.table].columns[scdc.column];160 let cExpression = scdc.expression;161 if (scdc.extra && scdc.extra.length > 0) {162 cExpression += ` ${scdc.extra}`;163 }164 const cName = scdc.name && scdc.name.length > 0 ? scdc.name : null;165 dcc.default = { expression: cExpression, constraintName: cName };166 }167 });168 _.forEach(schemaColumnIdentityDefinitions, function (idcd) {169 const idc = schema.tables[idcd.table].columns[idcd.column];170 idc.isIdentity = true;171 idc.identity = {172 seed: idcd.seed,173 increment: idcd.increment,174 };175 });176 // get check constraints (NOT SUPPORTED IN MYSQL)177 // const checkConstraints = getRows(yield cmds.getCheckConstraints(knex, schema.name));178 // const checkConstraintDescriptions = getRows(yield cmds.getCheckConstraintDescriptions(knex, schema.name));179 // if (checkConstraints.length > 0) {180 // _.forEach(schema.tables, function (table) {181 // const tableCheckConstraints = _.filter(checkConstraints, { table: table.name });182 // if (tableCheckConstraints.length > 0) {183 // table.checkConstraints = _.keyBy(tableCheckConstraints, 'name');184 // _.forEach(table.checkConstraints, function (ck) {185 // _.unset(ck, 'schema');186 // _.unset(ck, 'table');187 // });188 // }189 // });190 // _.forEach(checkConstraintDescriptions, function (ccd) {191 // if (ccd.description && ccd.description.length > 0) {192 // schema.tables[ccd.table].checkConstraints[ccd.name].description = ccd.description;193 // }194 // });195 // }196 // get indexes197 const indexes = getRows(yield cmds.getIndexes(knex, schema.name));198 const primaryKeys = {};199 if (indexes.length > 0) {200 _.forEach(_.groupBy(indexes, 'long_name'), function (idxArr, idxName) {201 const idx = idxArr[0];202 const table = schema.tables[idx.table];203 const isPrimaryKey = idx.isPrimary === 1;204 if (!isPrimaryKey) {205 const idxc = {206 name: idxName,207 columnCount: idxArr.length,208 columns: _.map(idxArr, 'column'),209 type: idx.type,210 isUnique: idx.isUnique === 1,211 };212 table.indexes = table.indexes || {};213 table.indexes[idxName] = idxc;214 _.forEach(idxc.columns, function (idxcc) {215 table.columns[idxcc].isPartOfIndex = true;216 if (idxc.isUnique && idxArr.length > 1) {217 table.columns[idxcc].isUnique = true;218 }219 });220 } else {221 primaryKeys[table.name] = idx.name;222 }223 });224 }225 // get primary key (in MySQL, primary key names are always 'PRIMARY' so we need to group by table name instead)226 const primaryKeyConstraints = getRows(yield cmds.getPrimaryKeyConstraints(knex, schema.name));227 if (primaryKeyConstraints.length > 0) {228 _.forEach(_.groupBy(primaryKeyConstraints, 'table'), function (pk, pkName) {229 const table = schema.tables[pkName];230 table.primaryKey = { name: primaryKeys[table.name], columnCount: pk.length, columns: _.map(pk, 'column') };231 _.forEach(pk, function (pkc) {232 table.columns[pkc.column].isPartOfPrimaryKey = true;233 if (pk.length === 1) {234 table.columns[pkc.column].isPrimaryKey = true;235 }236 });237 });238 }239 // get unique keys240 const uniqueKeyConstraints = getRows(yield cmds.getUniqueKeyConstraints(knex, schema.name));241 if (uniqueKeyConstraints.length > 0) {242 _.forEach(_.groupBy(uniqueKeyConstraints, 'name'), function (uk, ukName) {243 const table = schema.tables[uk[0].table];244 const ukk = { name: ukName, columnCount: uk.length, columns: _.map(uk, 'column') };245 table.uniqueKeys = table.uniqueKeys || {};246 table.uniqueKeys[ukName] = ukk;247 _.forEach(ukk.columns, function (ukc) {248 table.columns[ukc].isPartOfUniqueKey = true;249 table.columns[ukc].uniqueKeyName = ukName;250 });251 });252 }253 // get foreign keys254 const foreignKeyConstraints = getRows(yield cmds.getForeignKeyConstraints(knex, schema.name));255 if (foreignKeyConstraints.length > 0) {256 schema.foreignKeys = _.keyBy(_.map(foreignKeyConstraints, function (fkc) {257 return {258 name: fkc.name,259 fkSchemaName: fkc.schema,260 fkTableName: fkc.table,261 fkColumnName: fkc.column,262 pkSchemaName: fkc.ucSchema,263 pkTableName: fkc.ucTable,264 pkName: fkc.ucName,265 deleteRule: fkc.deleteRule,266 updateRule: fkc.updateRule,267 };268 }), 'name');269 _.forEach(schema.foreignKeys, function (fk) {270 const fkc = schema.tables[fk.fkTableName].columns[fk.fkColumnName];271 fkc.isForeignKey = true;272 fkc.foreignKeyName = fk.name;273 const pkt = db.schemas[fk.pkSchemaName].tables[fk.pkTableName];274 pkt.reverseForeignKeys = pkt.reverseForeignKeys || {};275 pkt.reverseForeignKeys[fk.name] = {276 name: fk.name,277 schemaName: fk.fkSchemaName,278 tableName: fk.fkTableName,279 columnName: fk.fkColumnName,280 };281 });282 }283 // get schema functions284 const functions = _.map(getRows(yield cmds.getFunctions(knex, schemaName)), function (row) {285 return {286 name: row.name,287 description: row.description,288 sql: row.sql,289 language: row.language, // typically always 'SQL'290 result: !row.dataType ? null : {291 name: '',292 ordinal: 0,293 isIn: false,294 isOut: false,295 isResult: true,296 asLocator: false,297 dataType: row.dataType,298 maxLength: row.maxLength,299 precision: row.precision,300 scale: row.scale,301 dateTimePrecision: row.dateTimePrecision,302 characterSet: row.characterSetName,303 collation: row.collation304 }305 };306 });307 if (functions.length > 0) {308 schema.functions = _.keyBy(functions, 'name');309 }310 // get schema procedures311 const procedures = _.map(getRows(yield cmds.getStoredProcedures(knex, schemaName)), function (row) {312 return {313 name: row.name,314 description: row.description,315 sql: row.sql,316 language: row.language, // typically always 'SQL'317 result: !row.dataType ? null : {318 name: '',319 ordinal: 0,320 isIn: false,321 isOut: false,322 isResult: true,323 asLocator: false,324 dataType: row.dataType,325 maxLength: row.maxLength,326 precision: row.precision,327 scale: row.scale,328 dateTimePrecision: row.dateTimePrecision,329 characterSet: row.characterSetName,330 collation: row.collation331 }332 };333 });334 if (procedures.length > 0) {335 schema.procedures = _.keyBy(procedures, 'name');336 }337 // get procedure arguments338 const procedureArguments = getRows(yield cmds.getProcedureArguments(knex, schemaName));339 if (procedureArguments.length > 0) {340 _.forEach(_.groupBy(procedureArguments, 'procedureName'), function (groupedArguments, procedureName) {341 const pargs = _.map(groupedArguments, function (parg) {342 return {343 name: parg.parameterName,344 ordinal: parg.ordinal,345 isIn: parg.parameterMode && parg.parameterMode.indexOf('IN') >= 0, // can be INOUT346 isOut: parg.parameterMode && parg.parameterMode.indexOf('OUT') >= 0, // can be INOUT347 isResult: false,348 asLocator: false,349 dataType: parg.dataType,350 maxLength: parg.maxLength,351 precision: parg.precision,352 scale: parg.scale,353 dateTimePrecision: parg.dateTimePrecision,354 characterSet: parg.characterSetName,355 collation: parg.collation,356 };357 });358 const presult = _.find(pargs, parg => parg.isResult);359 const parguments = _.keyBy(_.filter(pargs, parg => !parg.isResult), 'name');360 if (schema.functions && schema.functions[procedureName]) {361 if (presult) {362 schema.functions[procedureName].result = presult;363 }364 schema.functions[procedureName].arguments = parguments;365 } else if (schema.procedures && schema.procedures[procedureName]) {366 if (presult) {367 schema.procedures[procedureName].result = presult;368 }369 schema.procedures[procedureName].arguments = parguments;370 }371 });372 }373 }374 return db;375 });376 },377 };378}379const mssqlExtractor = extractor();...
javascript.js
Source:javascript.js
...49 let subject;50 if (actionInContext.frame.isMainFrame) {51 subject = pageAlias;52 } else if (actionInContext.frame.selectorsChain && action.name !== 'navigate') {53 const locators = actionInContext.frame.selectorsChain.map(selector => '.' + asLocator(selector, 'frameLocator'));54 subject = `${pageAlias}${locators.join('')}`;55 } else if (actionInContext.frame.name) {56 subject = `${pageAlias}.frame(${formatObject({57 name: actionInContext.frame.name58 })})`;59 } else {60 subject = `${pageAlias}.frame(${formatObject({61 url: actionInContext.frame.url62 })})`;63 }64 const signals = (0, _language.toSignalMap)(action);65 if (signals.dialog) {66 formatter.add(` ${pageAlias}.once('dialog', dialog => {67 console.log(\`Dialog message: $\{dialog.message()}\`);68 dialog.dismiss().catch(() => {});69 });`);70 }71 const emitPromiseAll = signals.waitForNavigation || signals.popup || signals.download;72 if (emitPromiseAll) {73 // Generate either await Promise.all([]) or74 // const [popup1] = await Promise.all([]).75 let leftHandSide = '';76 if (signals.popup) leftHandSide = `const [${signals.popup.popupAlias}] = `;else if (signals.download) leftHandSide = `const [download] = `;77 formatter.add(`${leftHandSide}await Promise.all([`);78 } // Popup signals.79 if (signals.popup) formatter.add(`${pageAlias}.waitForEvent('popup'),`); // Navigation signal.80 if (signals.waitForNavigation) formatter.add(`${pageAlias}.waitForNavigation(/*{ url: ${quote(signals.waitForNavigation.url)} }*/),`); // Download signals.81 if (signals.download) formatter.add(`${pageAlias}.waitForEvent('download'),`);82 const prefix = signals.popup || signals.waitForNavigation || signals.download ? '' : 'await ';83 const actionCall = this._generateActionCall(action);84 const suffix = signals.waitForNavigation || emitPromiseAll ? '' : ';';85 formatter.add(`${prefix}${subject}.${actionCall}${suffix}`);86 if (emitPromiseAll) {87 formatter.add(`]);`);88 } else if (signals.assertNavigation) {89 if (this._isTest) formatter.add(` await expect(${pageAlias}).toHaveURL(${quote(signals.assertNavigation.url)});`);else formatter.add(` // assert.equal(${pageAlias}.url(), ${quote(signals.assertNavigation.url)});`);90 }91 return formatter.format();92 }93 _generateActionCall(action) {94 switch (action.name) {95 case 'openPage':96 throw Error('Not reached');97 case 'closePage':98 return 'close()';99 case 'click':100 {101 let method = 'click';102 if (action.clickCount === 2) method = 'dblclick';103 const modifiers = (0, _utils.toModifiers)(action.modifiers);104 const options = {};105 if (action.button !== 'left') options.button = action.button;106 if (modifiers.length) options.modifiers = modifiers;107 if (action.clickCount > 2) options.clickCount = action.clickCount;108 if (action.position) options.position = action.position;109 const optionsString = formatOptions(options, false);110 return asLocator(action.selector) + `.${method}(${optionsString})`;111 }112 case 'check':113 return asLocator(action.selector) + `.check()`;114 case 'uncheck':115 return asLocator(action.selector) + `.uncheck()`;116 case 'fill':117 return asLocator(action.selector) + `.fill(${quote(action.text)})`;118 case 'setInputFiles':119 return asLocator(action.selector) + `.setInputFiles(${formatObject(action.files.length === 1 ? action.files[0] : action.files)})`;120 case 'press':121 {122 const modifiers = (0, _utils.toModifiers)(action.modifiers);123 const shortcut = [...modifiers, action.key].join('+');124 return asLocator(action.selector) + `.press(${quote(shortcut)})`;125 }126 case 'navigate':127 return `goto(${quote(action.url)})`;128 case 'select':129 return asLocator(action.selector) + `.selectOption(${formatObject(action.options.length > 1 ? action.options : action.options[0])})`;130 }131 }132 generateHeader(options) {133 if (this._isTest) return this.generateTestHeader(options);134 return this.generateStandaloneHeader(options);135 }136 generateFooter(saveStorage) {137 if (this._isTest) return this.generateTestFooter(saveStorage);138 return this.generateStandaloneFooter(saveStorage);139 }140 generateTestHeader(options) {141 const formatter = new JavaScriptFormatter();142 const useText = formatContextOptions(options.contextOptions, options.deviceName);143 formatter.add(`144 import { test, expect${options.deviceName ? ', devices' : ''} } from '@playwright/test';145${useText ? '\ntest.use(' + useText + ');\n' : ''}146 test('test', async ({ page }) => {`);147 return formatter.format();148 }149 generateTestFooter(saveStorage) {150 return `\n});`;151 }152 generateStandaloneHeader(options) {153 const formatter = new JavaScriptFormatter();154 formatter.add(`155 const { ${options.browserName}${options.deviceName ? ', devices' : ''} } = require('playwright');156 (async () => {157 const browser = await ${options.browserName}.launch(${formatObjectOrVoid(options.launchOptions)});158 const context = await browser.newContext(${formatContextOptions(options.contextOptions, options.deviceName)});`);159 return formatter.format();160 }161 generateStandaloneFooter(saveStorage) {162 const storageStateLine = saveStorage ? `\n await context.storageState({ path: ${quote(saveStorage)} });` : '';163 return `\n // ---------------------${storageStateLine}164 await context.close();165 await browser.close();166})();`;167 }168}169exports.JavaScriptLanguageGenerator = JavaScriptLanguageGenerator;170function asLocator(selector, locatorFn = 'locator') {171 const match = selector.match(/(.*)\s+>>\s+nth=(\d+)$/);172 if (!match) return `${locatorFn}(${quote(selector)})`;173 if (+match[2] === 0) return `${locatorFn}(${quote(match[1])}).first()`;174 return `${locatorFn}(${quote(match[1])}).nth(${match[2]})`;175}176function formatOptions(value, hasArguments) {177 const keys = Object.keys(value);178 if (!keys.length) return '';179 return (hasArguments ? ', ' : '') + formatObject(value);180}181function formatObject(value, indent = ' ') {182 if (typeof value === 'string') return quote(value);183 if (Array.isArray(value)) return `[${value.map(o => formatObject(o)).join(', ')}]`;184 if (typeof value === 'object') {...
csharp.js
Source:csharp.js
...44 let subject;45 if (actionInContext.frame.isMainFrame) {46 subject = pageAlias;47 } else if (actionInContext.frame.selectorsChain && action.name !== 'navigate') {48 const locators = actionInContext.frame.selectorsChain.map(selector => '.' + asLocator(selector, 'FrameLocator'));49 subject = `${pageAlias}${locators.join('')}`;50 } else if (actionInContext.frame.name) {51 subject = `${pageAlias}.Frame(${quote(actionInContext.frame.name)})`;52 } else {53 subject = `${pageAlias}.FrameByUrl(${quote(actionInContext.frame.url)})`;54 }55 const signals = (0, _language.toSignalMap)(action);56 if (signals.dialog) {57 formatter.add(` void ${pageAlias}_Dialog${signals.dialog.dialogAlias}_EventHandler(object sender, IDialog dialog)58 {59 Console.WriteLine($"Dialog message: {dialog.Message}");60 dialog.DismissAsync();61 ${pageAlias}.Dialog -= ${pageAlias}_Dialog${signals.dialog.dialogAlias}_EventHandler;62 }63 ${pageAlias}.Dialog += ${pageAlias}_Dialog${signals.dialog.dialogAlias}_EventHandler;`);64 }65 const lines = [];66 const actionCall = this._generateActionCall(action, actionInContext.frame.isMainFrame);67 if (signals.waitForNavigation) {68 lines.push(`await ${pageAlias}.RunAndWaitForNavigationAsync(async () =>`);69 lines.push(`{`);70 lines.push(` await ${subject}.${actionCall};`);71 lines.push(`}/*, new ${actionInContext.frame.isMainFrame ? 'Page' : 'Frame'}WaitForNavigationOptions`);72 lines.push(`{`);73 lines.push(` UrlString = ${quote(signals.waitForNavigation.url)}`);74 lines.push(`}*/);`);75 } else {76 lines.push(`await ${subject}.${actionCall};`);77 }78 if (signals.download) {79 lines.unshift(`var download${signals.download.downloadAlias} = await ${pageAlias}.RunAndWaitForDownloadAsync(async () =>\n{`);80 lines.push(`});`);81 }82 if (signals.popup) {83 lines.unshift(`var ${signals.popup.popupAlias} = await ${pageAlias}.RunAndWaitForPopupAsync(async () =>\n{`);84 lines.push(`});`);85 }86 for (const line of lines) formatter.add(line);87 if (signals.assertNavigation) formatter.add(` // Assert.AreEqual(${quote(signals.assertNavigation.url)}, ${pageAlias}.Url);`);88 return formatter.format();89 }90 _generateActionCall(action, isPage) {91 switch (action.name) {92 case 'openPage':93 throw Error('Not reached');94 case 'closePage':95 return 'CloseAsync()';96 case 'click':97 {98 let method = 'Click';99 if (action.clickCount === 2) method = 'DblClick';100 const modifiers = (0, _utils.toModifiers)(action.modifiers);101 const options = {};102 if (action.button !== 'left') options.button = action.button;103 if (modifiers.length) options.modifiers = modifiers;104 if (action.clickCount > 2) options.clickCount = action.clickCount;105 if (action.position) options.position = action.position;106 if (!Object.entries(options).length) return asLocator(action.selector) + `.${method}Async()`;107 const optionsString = formatObject(options, ' ', 'Locator' + method + 'Options');108 return asLocator(action.selector) + `.${method}Async(${optionsString})`;109 }110 case 'check':111 return asLocator(action.selector) + `.CheckAsync()`;112 case 'uncheck':113 return asLocator(action.selector) + `.UncheckAsync()`;114 case 'fill':115 return asLocator(action.selector) + `.FillAsync(${quote(action.text)})`;116 case 'setInputFiles':117 return asLocator(action.selector) + `.SetInputFilesAsync(${formatObject(action.files)})`;118 case 'press':119 {120 const modifiers = (0, _utils.toModifiers)(action.modifiers);121 const shortcut = [...modifiers, action.key].join('+');122 return asLocator(action.selector) + `.PressAsync(${quote(shortcut)})`;123 }124 case 'navigate':125 return `GotoAsync(${quote(action.url)})`;126 case 'select':127 return asLocator(action.selector) + `.SelectOptionAsync(${formatObject(action.options)})`;128 }129 }130 generateHeader(options) {131 const formatter = new CSharpFormatter(0);132 formatter.add(`133 using Microsoft.Playwright;134 using System;135 using System.Threading.Tasks;136 class Program137 {138 public static async Task Main()139 {140 using var playwright = await Playwright.CreateAsync();141 await using var browser = await playwright.${toPascal(options.browserName)}.LaunchAsync(${formatObject(options.launchOptions, ' ', 'BrowserTypeLaunchOptions')});142 var context = await browser.NewContextAsync(${formatContextOptions(options.contextOptions, options.deviceName)});`);143 return formatter.format();144 }145 generateFooter(saveStorage) {146 const storageStateLine = saveStorage ? `\n await context.StorageStateAsync(new BrowserContextStorageStateOptions\n {\n Path = ${quote(saveStorage)}\n });\n` : '';147 return `${storageStateLine} }148}\n`;149 }150}151exports.CSharpLanguageGenerator = CSharpLanguageGenerator;152function formatObject(value, indent = ' ', name = '') {153 if (typeof value === 'string') {154 if (['permissions', 'colorScheme', 'modifiers', 'button'].includes(name)) return `${getClassName(name)}.${toPascal(value)}`;155 return quote(value);156 }157 if (Array.isArray(value)) return `new[] { ${value.map(o => formatObject(o, indent, name)).join(', ')} }`;158 if (typeof value === 'object') {159 const keys = Object.keys(value);160 if (!keys.length) return name ? `new ${getClassName(name)}` : '';161 const tokens = [];162 for (const key of keys) {163 const property = getPropertyName(key);164 tokens.push(`${property} = ${formatObject(value[key], indent, key)},`);165 }166 if (name) return `new ${getClassName(name)}\n{\n${indent}${tokens.join(`\n${indent}`)}\n${indent}}`;167 return `{\n${indent}${tokens.join(`\n${indent}`)}\n${indent}}`;168 }169 if (name === 'latitude' || name === 'longitude') return String(value) + 'm';170 return String(value);171}172function getClassName(value) {173 switch (value) {174 case 'viewport':175 return 'ViewportSize';176 case 'proxy':177 return 'ProxySettings';178 case 'permissions':179 return 'ContextPermission';180 case 'modifiers':181 return 'KeyboardModifier';182 case 'button':183 return 'MouseButton';184 default:185 return toPascal(value);186 }187}188function getPropertyName(key) {189 switch (key) {190 case 'storageState':191 return 'StorageStatePath';192 case 'viewport':193 return 'ViewportSize';194 default:195 return toPascal(key);196 }197}198function toPascal(value) {199 return value[0].toUpperCase() + value.slice(1);200}201function formatContextOptions(options, deviceName) {202 const device = deviceName && _deviceDescriptors.default[deviceName];203 if (!device) {204 if (!Object.entries(options).length) return '';205 return formatObject(options, ' ', 'BrowserNewContextOptions');206 }207 options = (0, _language.sanitizeDeviceOptions)(device, options);208 if (!Object.entries(options).length) return `playwright.Devices[${quote(deviceName)}]`;209 return formatObject(options, ' ', `BrowserNewContextOptions(playwright.Devices[${quote(deviceName)}])`);210}211class CSharpFormatter {212 constructor(offset = 0) {213 this._baseIndent = void 0;214 this._baseOffset = void 0;215 this._lines = [];216 this._baseIndent = ' '.repeat(4);217 this._baseOffset = ' '.repeat(offset);218 }219 prepend(text) {220 this._lines = text.trim().split('\n').map(line => line.trim()).concat(this._lines);221 }222 add(text) {223 this._lines.push(...text.trim().split('\n').map(line => line.trim()));224 }225 newLine() {226 this._lines.push('');227 }228 format() {229 let spaces = '';230 let previousLine = '';231 return this._lines.map(line => {232 if (line === '') return line;233 if (line.startsWith('}') || line.startsWith(']') || line.includes('});') || line === ');') spaces = spaces.substring(this._baseIndent.length);234 const extraSpaces = /^(for|while|if).*\(.*\)$/.test(previousLine) ? this._baseIndent : '';235 previousLine = line;236 line = spaces + extraSpaces + line;237 if (line.endsWith('{') || line.endsWith('[') || line.endsWith('(')) spaces += this._baseIndent;238 if (line.endsWith('));')) spaces = spaces.substring(this._baseIndent.length);239 return this._baseOffset + line;240 }).join('\n');241 }242}243function quote(text) {244 return (0, _stringUtils.escapeWithQuotes)(text, '\"');245}246function asLocator(selector, locatorFn = 'Locator') {247 const match = selector.match(/(.*)\s+>>\s+nth=(\d+)$/);248 if (!match) return `${locatorFn}(${quote(selector)})`;249 if (+match[2] === 0) return `${locatorFn}(${quote(match[1])}).First`;250 return `${locatorFn}(${quote(match[1])}).Nth(${match[2]})`;...
python.js
Source:python.js
...52 let subject;53 if (actionInContext.frame.isMainFrame) {54 subject = pageAlias;55 } else if (actionInContext.frame.selectorsChain && action.name !== 'navigate') {56 const locators = actionInContext.frame.selectorsChain.map(selector => '.' + asLocator(selector, 'frame_locator'));57 subject = `${pageAlias}${locators.join('')}`;58 } else if (actionInContext.frame.name) {59 subject = `${pageAlias}.frame(${formatOptions({60 name: actionInContext.frame.name61 }, false)})`;62 } else {63 subject = `${pageAlias}.frame(${formatOptions({64 url: actionInContext.frame.url65 }, false)})`;66 }67 const signals = (0, _language.toSignalMap)(action);68 if (signals.dialog) formatter.add(` ${pageAlias}.once("dialog", lambda dialog: dialog.dismiss())`);69 const actionCall = this._generateActionCall(action);70 let code = `${this._awaitPrefix}${subject}.${actionCall}`;71 if (signals.popup) {72 code = `${this._asyncPrefix}with ${pageAlias}.expect_popup() as popup_info {73 ${code}74 }75 ${signals.popup.popupAlias} = ${this._awaitPrefix}popup_info.value`;76 }77 if (signals.download) {78 code = `${this._asyncPrefix}with ${pageAlias}.expect_download() as download_info {79 ${code}80 }81 download = ${this._awaitPrefix}download_info.value`;82 }83 if (signals.waitForNavigation) {84 code = `85 # ${this._asyncPrefix}with ${pageAlias}.expect_navigation(url=${quote(signals.waitForNavigation.url)}):86 ${this._asyncPrefix}with ${pageAlias}.expect_navigation() {87 ${code}88 }`;89 }90 formatter.add(code);91 if (signals.assertNavigation) formatter.add(` # ${this._awaitPrefix}expect(${pageAlias}).to_have_url(${quote(signals.assertNavigation.url)})`);92 return formatter.format();93 }94 _generateActionCall(action) {95 switch (action.name) {96 case 'openPage':97 throw Error('Not reached');98 case 'closePage':99 return 'close()';100 case 'click':101 {102 let method = 'click';103 if (action.clickCount === 2) method = 'dblclick';104 const modifiers = (0, _utils.toModifiers)(action.modifiers);105 const options = {};106 if (action.button !== 'left') options.button = action.button;107 if (modifiers.length) options.modifiers = modifiers;108 if (action.clickCount > 2) options.clickCount = action.clickCount;109 if (action.position) options.position = action.position;110 const optionsString = formatOptions(options, false);111 return asLocator(action.selector) + `.${method}(${optionsString})`;112 }113 case 'check':114 return asLocator(action.selector) + `.check()`;115 case 'uncheck':116 return asLocator(action.selector) + `.uncheck()`;117 case 'fill':118 return asLocator(action.selector) + `.fill(${quote(action.text)})`;119 case 'setInputFiles':120 return asLocator(action.selector) + `.set_input_files(${formatValue(action.files.length === 1 ? action.files[0] : action.files)})`;121 case 'press':122 {123 const modifiers = (0, _utils.toModifiers)(action.modifiers);124 const shortcut = [...modifiers, action.key].join('+');125 return asLocator(action.selector) + `.press(${quote(shortcut)})`;126 }127 case 'navigate':128 return `goto(${quote(action.url)})`;129 case 'select':130 return asLocator(action.selector) + `.select_option(${formatValue(action.options.length === 1 ? action.options[0] : action.options)})`;131 }132 }133 generateHeader(options) {134 const formatter = new PythonFormatter();135 if (this._isAsync) {136 formatter.add(`137import asyncio138from playwright.async_api import Playwright, async_playwright, expect139async def run(playwright: Playwright) -> None {140 browser = await playwright.${options.browserName}.launch(${formatOptions(options.launchOptions, false)})141 context = await browser.new_context(${formatContextOptions(options.contextOptions, options.deviceName)})`);142 } else {143 formatter.add(`144from playwright.sync_api import Playwright, sync_playwright, expect145def run(playwright: Playwright) -> None {146 browser = playwright.${options.browserName}.launch(${formatOptions(options.launchOptions, false)})147 context = browser.new_context(${formatContextOptions(options.contextOptions, options.deviceName)})`);148 }149 return formatter.format();150 }151 generateFooter(saveStorage) {152 if (this._isAsync) {153 const storageStateLine = saveStorage ? `\n await context.storage_state(path=${quote(saveStorage)})` : '';154 return `\n # ---------------------${storageStateLine}155 await context.close()156 await browser.close()157async def main() -> None:158 async with async_playwright() as playwright:159 await run(playwright)160asyncio.run(main())161`;162 } else {163 const storageStateLine = saveStorage ? `\n context.storage_state(path=${quote(saveStorage)})` : '';164 return `\n # ---------------------${storageStateLine}165 context.close()166 browser.close()167with sync_playwright() as playwright:168 run(playwright)169`;170 }171 }172}173exports.PythonLanguageGenerator = PythonLanguageGenerator;174function formatValue(value) {175 if (value === false) return 'False';176 if (value === true) return 'True';177 if (value === undefined) return 'None';178 if (Array.isArray(value)) return `[${value.map(formatValue).join(', ')}]`;179 if (typeof value === 'string') return quote(value);180 if (typeof value === 'object') return JSON.stringify(value);181 return String(value);182}183function toSnakeCase(name) {184 const toSnakeCaseRegex = /((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))/g;185 return name.replace(toSnakeCaseRegex, `_$1`).toLowerCase();186}187function formatOptions(value, hasArguments) {188 const keys = Object.keys(value);189 if (!keys.length) return '';190 return (hasArguments ? ', ' : '') + keys.map(key => `${toSnakeCase(key)}=${formatValue(value[key])}`).join(', ');191}192function formatContextOptions(options, deviceName) {193 const device = deviceName && _deviceDescriptors.default[deviceName];194 if (!device) return formatOptions(options, false);195 return `**playwright.devices[${quote(deviceName)}]` + formatOptions((0, _language.sanitizeDeviceOptions)(device, options), true);196}197class PythonFormatter {198 constructor(offset = 0) {199 this._baseIndent = void 0;200 this._baseOffset = void 0;201 this._lines = [];202 this._baseIndent = ' '.repeat(4);203 this._baseOffset = ' '.repeat(offset);204 }205 prepend(text) {206 this._lines = text.trim().split('\n').map(line => line.trim()).concat(this._lines);207 }208 add(text) {209 this._lines.push(...text.trim().split('\n').map(line => line.trim()));210 }211 newLine() {212 this._lines.push('');213 }214 format() {215 let spaces = '';216 const lines = [];217 this._lines.forEach(line => {218 if (line === '') return lines.push(line);219 if (line === '}') {220 spaces = spaces.substring(this._baseIndent.length);221 return;222 }223 line = spaces + line;224 if (line.endsWith('{')) {225 spaces += this._baseIndent;226 line = line.substring(0, line.length - 1).trimEnd() + ':';227 }228 return lines.push(this._baseOffset + line);229 });230 return lines.join('\n');231 }232}233function quote(text) {234 return (0, _stringUtils.escapeWithQuotes)(text, '\"');235}236function asLocator(selector, locatorFn = 'locator') {237 const match = selector.match(/(.*)\s+>>\s+nth=(\d+)$/);238 if (!match) return `${locatorFn}(${quote(selector)})`;239 if (+match[2] === 0) return `${locatorFn}(${quote(match[1])}).first`;240 return `${locatorFn}(${quote(match[1])}).nth(${match[2]})`;...
java.js
Source:java.js
...45 let subject;46 if (actionInContext.frame.isMainFrame) {47 subject = pageAlias;48 } else if (actionInContext.frame.selectorsChain && action.name !== 'navigate') {49 const locators = actionInContext.frame.selectorsChain.map(selector => '.' + asLocator(selector, 'frameLocator'));50 subject = `${pageAlias}${locators.join('')}`;51 } else if (actionInContext.frame.name) {52 subject = `${pageAlias}.frame(${quote(actionInContext.frame.name)})`;53 } else {54 subject = `${pageAlias}.frameByUrl(${quote(actionInContext.frame.url)})`;55 }56 const signals = (0, _language.toSignalMap)(action);57 if (signals.dialog) {58 formatter.add(` ${pageAlias}.onceDialog(dialog -> {59 System.out.println(String.format("Dialog message: %s", dialog.message()));60 dialog.dismiss();61 });`);62 }63 const actionCall = this._generateActionCall(action);64 let code = `${subject}.${actionCall};`;65 if (signals.popup) {66 code = `Page ${signals.popup.popupAlias} = ${pageAlias}.waitForPopup(() -> {67 ${code}68 });`;69 }70 if (signals.download) {71 code = `Download download = ${pageAlias}.waitForDownload(() -> {72 ${code}73 });`;74 }75 if (signals.waitForNavigation) {76 code = `77 // ${pageAlias}.waitForNavigation(new Page.WaitForNavigationOptions().setUrl(${quote(signals.waitForNavigation.url)}), () ->78 ${pageAlias}.waitForNavigation(() -> {79 ${code}80 });`;81 }82 formatter.add(code);83 if (signals.assertNavigation) formatter.add(`// assertThat(${pageAlias}).hasURL(${quote(signals.assertNavigation.url)});`);84 return formatter.format();85 }86 _generateActionCall(action) {87 switch (action.name) {88 case 'openPage':89 throw Error('Not reached');90 case 'closePage':91 return 'close()';92 case 'click':93 {94 let method = 'click';95 if (action.clickCount === 2) method = 'dblclick';96 const modifiers = (0, _utils.toModifiers)(action.modifiers);97 const options = {};98 if (action.button !== 'left') options.button = action.button;99 if (modifiers.length) options.modifiers = modifiers;100 if (action.clickCount > 2) options.clickCount = action.clickCount;101 if (action.position) options.position = action.position;102 const optionsText = formatClickOptions(options);103 return asLocator(action.selector) + `.${method}(${optionsText})`;104 }105 case 'check':106 return asLocator(action.selector) + `.check()`;107 case 'uncheck':108 return asLocator(action.selector) + `.uncheck()`;109 case 'fill':110 return asLocator(action.selector) + `.fill(${quote(action.text)})`;111 case 'setInputFiles':112 return asLocator(action.selector) + `.setInputFiles(${formatPath(action.files.length === 1 ? action.files[0] : action.files)})`;113 case 'press':114 {115 const modifiers = (0, _utils.toModifiers)(action.modifiers);116 const shortcut = [...modifiers, action.key].join('+');117 return asLocator(action.selector) + `.press(${quote(shortcut)})`;118 }119 case 'navigate':120 return `navigate(${quote(action.url)})`;121 case 'select':122 return asLocator(action.selector) + `.selectOption(${formatSelectOption(action.options.length > 1 ? action.options : action.options[0])})`;123 }124 }125 generateHeader(options) {126 const formatter = new _javascript.JavaScriptFormatter();127 formatter.add(`128 import com.microsoft.playwright.*;129 import com.microsoft.playwright.options.*;130 import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;131 import java.util.*;132 public class Example {133 public static void main(String[] args) {134 try (Playwright playwright = Playwright.create()) {135 Browser browser = playwright.${options.browserName}().launch(${formatLaunchOptions(options.launchOptions)});136 BrowserContext context = browser.newContext(${formatContextOptions(options.contextOptions, options.deviceName)});`);137 return formatter.format();138 }139 generateFooter(saveStorage) {140 const storageStateLine = saveStorage ? `\n context.storageState(new BrowserContext.StorageStateOptions().setPath(${quote(saveStorage)}));\n` : '';141 return `${storageStateLine} }142 }143}`;144 }145}146exports.JavaLanguageGenerator = JavaLanguageGenerator;147function formatPath(files) {148 if (Array.isArray(files)) {149 if (files.length === 0) return 'new Path[0]';150 return `new Path[] {${files.map(s => 'Paths.get(' + quote(s) + ')').join(', ')}}`;151 }152 return `Paths.get(${quote(files)})`;153}154function formatSelectOption(options) {155 if (Array.isArray(options)) {156 if (options.length === 0) return 'new String[0]';157 return `new String[] {${options.map(s => quote(s)).join(', ')}}`;158 }159 return quote(options);160}161function formatLaunchOptions(options) {162 const lines = [];163 if (!Object.keys(options).length) return '';164 lines.push('new BrowserType.LaunchOptions()');165 if (typeof options.headless === 'boolean') lines.push(` .setHeadless(false)`);166 if (options.channel) lines.push(` .setChannel(${quote(options.channel)})`);167 return lines.join('\n');168}169function formatContextOptions(contextOptions, deviceName) {170 const lines = [];171 if (!Object.keys(contextOptions).length && !deviceName) return '';172 const device = deviceName ? _deviceDescriptors.default[deviceName] : {};173 const options = { ...device,174 ...contextOptions175 };176 lines.push('new Browser.NewContextOptions()');177 if (options.acceptDownloads) lines.push(` .setAcceptDownloads(true)`);178 if (options.bypassCSP) lines.push(` .setBypassCSP(true)`);179 if (options.colorScheme) lines.push(` .setColorScheme(ColorScheme.${options.colorScheme.toUpperCase()})`);180 if (options.deviceScaleFactor) lines.push(` .setDeviceScaleFactor(${options.deviceScaleFactor})`);181 if (options.geolocation) lines.push(` .setGeolocation(${options.geolocation.latitude}, ${options.geolocation.longitude})`);182 if (options.hasTouch) lines.push(` .setHasTouch(${options.hasTouch})`);183 if (options.isMobile) lines.push(` .setIsMobile(${options.isMobile})`);184 if (options.locale) lines.push(` .setLocale(${quote(options.locale)})`);185 if (options.proxy) lines.push(` .setProxy(new Proxy(${quote(options.proxy.server)}))`);186 if (options.storageState) lines.push(` .setStorageStatePath(Paths.get(${quote(options.storageState)}))`);187 if (options.timezoneId) lines.push(` .setTimezoneId(${quote(options.timezoneId)})`);188 if (options.userAgent) lines.push(` .setUserAgent(${quote(options.userAgent)})`);189 if (options.viewport) lines.push(` .setViewportSize(${options.viewport.width}, ${options.viewport.height})`);190 return lines.join('\n');191}192function formatClickOptions(options) {193 const lines = [];194 if (options.button) lines.push(` .setButton(MouseButton.${options.button.toUpperCase()})`);195 if (options.modifiers) lines.push(` .setModifiers(Arrays.asList(${options.modifiers.map(m => `KeyboardModifier.${m.toUpperCase()}`).join(', ')}))`);196 if (options.clickCount) lines.push(` .setClickCount(${options.clickCount})`);197 if (options.position) lines.push(` .setPosition(${options.position.x}, ${options.position.y})`);198 if (!lines.length) return '';199 lines.unshift(`new Locator.ClickOptions()`);200 return lines.join('\n');201}202function quote(text) {203 return (0, _stringUtils.escapeWithQuotes)(text, '\"');204}205function asLocator(selector, locatorFn = 'locator') {206 const match = selector.match(/(.*)\s+>>\s+nth=(\d+)$/);207 if (!match) return `${locatorFn}(${quote(selector)})`;208 if (+match[2] === 0) return `${locatorFn}(${quote(match[1])}).first()`;209 return `${locatorFn}(${quote(match[1])}).nth(${match[2]})`;...
Using AI Code Generation
1const {chromium} = require('playwright');2const {asLocator} = require('playwright/internal/locator');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const locator = asLocator(page, 'input[name="q"]');8 await locator.fill('Hello World');9 await browser.close();10})();11const {chromium} = require('playwright');12const {asLocator} = require('playwright/internal/locator');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 const locator = asLocator(page, 'input[name="q"]');18 await locator.fill('Hello World');19 await browser.close();20})();21const {chromium} = require('playwright');22const {asLocator} = require('playwright/internal/locator');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 const locator = asLocator(page, 'input[name="q"]');28 await locator.fill('Hello World');29 await browser.close();30})();31const {chromium} = require('playwright');32const {asLocator} = require('playwright/internal/locator');33(async () => {34 const browser = await chromium.launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 const locator = asLocator(page, 'input[name="q"]');38 await locator.fill('Hello World');39 await browser.close();40})();41const {chromium} = require('playwright');42const {asLocator} = require('playwright/internal/locator');43(async () => {44 const browser = await chromium.launch();
Using AI Code Generation
1const { Locator } = require('@playwright/test');2const { LocatorImpl } = require('@playwright/test/lib/server/locator');3const { Page } = require('@playwright/test/lib/server/page');4const { ElementHandle } = require('@playwright/test/lib/server/dom');5const { JSHandle } = require('@playwright/test/lib/server/jsHandle');6const { asLocator } = LocatorImpl.prototype;7const { evaluateHandle } = Page.prototype;8const { asElement } = JSHandle.prototype;9const { _scrollIntoViewIfNeeded } = ElementHandle.prototype;10const elementHandle = await evaluateHandle.call(page, (locator, root) => {11 return locator.asElement(root);12}, locator, page);13const element = asElement.call(elementHandle);14_scrollIntoViewIfNeeded.call(element);
Using AI Code Generation
1const { Locator } = require('@playwright/test');2const { LocatorChannel } = require('@playwright/test/lib/channels');3const { Page } = require('@playwright/test/lib/server/page');4const { selectors } = require('@playwright/test/lib/server/selectors');5const { ElementHandle } = require('@playwright/test/lib/server/chromium/crElementHandle');6const { JSHandle } = require('@playwright/test/lib/server/jsHandle');7const { Frame } = require('@playwright/test/lib/server/frame');8const { Worker } = require('@playwright/test/lib/server/worker');9const { PageChannel } = require('@playwright/test/lib/channels');10const { FrameChannel } = require('@playwright/test/lib/channels');11const { WorkerChannel } = require('@playwright/test/lib/channels');12const { ElementHandleChannel } = require('@playwright/test/lib/channels');13const { JSHandleChannel } = require('@playwright/test/lib/channels');14const { selectors } = require('@playwright/test/lib/server/selectors');15const { Page } = require('@playwright/test/lib/server/page');16const { Frame } = require('@playwright/test/lib/server/frame');17const { Worker } = require('@playwright/test/lib/server/worker');18const { PageChannel } = require('@playwright/test/lib/channels');19const { FrameChannel } = require('@playwright/test/lib/channels');20const { WorkerChannel } = require('@playwright/test/lib/channels');21const { ElementHandleChannel } = require('@playwright/test/lib/channels');22const { JSHandleChannel } = require('@playwright/test/lib/channels');23const { selectors } = require('@playwright/test/lib/server/selectors');24const { Page } = require('@playwright/test/lib/server/page');25const { Frame } = require('@playwright/test/lib/server/frame');26const { Worker } = require('@playwright/test/lib/server/worker');27const { PageChannel } = require('@playwright/test/lib/channels');28const { FrameChannel } = require('@playwright/test/lib/channels');29const { WorkerChannel } = require('@playwright/test/lib/channels');30const { ElementHandleChannel } = require('@playwright/test/lib/channels');31const { JSHandleChannel } = require('@playwright/test/lib/channels');32const { selectors } = require('@playwright/test/lib/server/selectors');33const { Page } = require('@playwright/test/lib/server/page');
Using AI Code Generation
1const { asLocator } = require('@playwright/test');2const { Locator } = require('@playwright/test');3const { test } = require('@playwright/test');4test('asLocator', async ({ page }) => {5 const locator = await asLocator(page, 'css=div');6 expect(locator).toBeInstanceOf(Locator);7 const element = await locator.first();8 expect(await element.getAttribute('class')).toBe('header');9});10const { test } = require('@playwright/test');11test.describe('asLocator', () => {12 test('asLocator', async ({ page }) => {13 const locator = await page.asLocator('css=div');14 const element = await locator.first();15 expect(await element.getAttribute('class')).toBe('header');16 });17});18import { test } from '@playwright/test';19test.describe('asLocator', () => {20 test('asLocator', async ({ page }) => {21 const locator = await page.asLocator('css=div');22 const element = await locator.first();23 expect(await element.getAttribute('class')).toBe('header');24 });25});26const { test } = require('@playwright/test');27test.describe('asLocator', () => {28 test('asLocator', async ({ page }) => {29 const locator = await page.asLocator('css=div');30 const element = await locator.first();31 expect(await element.getAttribute('class')).toBe('header');32 });33});34import { test } from '@playwright/test';35test.describe('asLocator', () => {36 test('asLocator', async ({ page }) => {37 const locator = await page.asLocator('css=div');38 const element = await locator.first();39 expect(await element.getAttribute('class')).toBe('header');40 });41});42const { test } = require('@playwright/test');43test.describe('asLocator', () => {44 test('asLocator', async ({ page }) => {
Using AI Code Generation
1const { test, expect } = require("@playwright/test");2test("test", async ({ page }) => {3 const searchBox = await page.$("#searchform input");4 const locator = await searchBox.asLocator();5 console.log(locator);6});
Using AI Code Generation
1const { Locator } = require('playwright');2const { BrowserContext } = require('playwright');3const { Page } = require('playwright');4const { LocatorImpl } = require('playwright/lib/server/locator.js');5const { ElementHandle } = require('playwright/lib/server/dom.js');6const { Frame } = require('playwright/lib/server/frame.js');7const { JSHandle } = require('playwright/lib/server/jsHandle.js');8async function test() {9 const browser = await chromium.launch();10 const context = await browser.newContext();11 const page = await context.newPage();12 const locator = await page.asLocator('input[type="text"]');13 const elementHandle = await locator.elementHandle();14 const element = await elementHandle.asElement();15 console.log('Element: ', element);16 await browser.close();17}18test();
Using AI Code Generation
1const { Locator } = require('@playwright/test');2const { asLocator } = Locator;3const locator = asLocator('text=Hello');4console.log(locator.toString());5const { Locator } = require('@playwright/test');6const { asLocator } = Locator;7const locator = asLocator('text=Hello');8console.log(locator.toString());9const { Locator } = require('@playwright/test');10const { asLocator } = Locator;11const locator = asLocator('text=Hello');12console.log(locator.toString());13const { Locator } = require('@playwright/test');14const { asLocator } = Locator;15const locator = asLocator('text=Hello');16console.log(locator.toString());17const { Locator } = require('@playwright/test');18const { asLocator } = Locator;19const locator = asLocator('text=Hello');20console.log(locator.toString());21const { Locator } = require('@playwright/test');22const { asLocator } = Locator;23const locator = asLocator('text=Hello');24console.log(locator.toString());25const { Locator } = require('@playwright/test');26const { asLocator } = Locator;27const locator = asLocator('text=Hello');28console.log(locator.toString());29const { Locator } = require('@playwright/test');30const { asLocator } = Locator;31const locator = asLocator('text=Hello');32console.log(locator.toString());33const { Locator } = require('@playwright/test');34const { asLocator } = Locator;35const locator = asLocator('text=Hello');36console.log(locator.toString());37const { Locator } = require('@playwright/test');38const { asLocator } = Locator;39const locator = asLocator('text=Hello');40console.log(locator.toString());41const { Locator } = require('@playwright/test');42const { asLocator } =
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!!