Best JavaScript code snippet using playwright-internal
ideality.js
Source: ideality.js
...255i.nodeDisplay = (node, nested) => 256 (node == i.current.node ? '' : `<a 257 href="?${i.routingString(node)}" 258 onclick="259 i.gotoId(${i.escapeWithQuotes(node.id)}); 260 return false261 "262 >263 ${i.escape(node.body).replace(i.commentRegex, '<em style="color: #CCC">$1$2</em>') || "<em>[tba]</em>"}264 </a>`265 ) + (i.branched(node) ?266 `<span 267 style="color: lightgray; font-size:x-small; vertical-align: bottom;"268 >269 <a 270 href="#" 271 onclick="272 i.toggleExpand(${i.escapeWithQuotes(node.id)}); 273 return false274 "275 >276 ${node.expanded ? 'â' : 'â'}277 </a>278 </span>` : ( nested ?279 i.children(node).map(child => i.nodeDisplay(child, true)) : ''280 )281 ) + (node.expanded && i.branched(node) ?282 `<div style="color:gray; font-size:small;">283 <ul>284 ${i.children(node).filter(child => !i.current.thread.includes(child)).map( child => 285 `<li>286 ${i.nodeDisplay(child, true)}...
locator.js
Source: locator.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.Locator = exports.FrameLocator = void 0;6var util = _interopRequireWildcard(require("util"));7var _utils = require("../utils/utils");8var _elementHandle = require("./elementHandle");9var _jsHandle = require("./jsHandle");10var _stringUtils = require("../utils/stringUtils");11let _util$inspect$custom;12function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }13function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }14_util$inspect$custom = util.inspect.custom;15class Locator {16 constructor(frame, selector, options) {17 this._frame = void 0;18 this._selector = void 0;19 this._frame = frame;20 this._selector = selector;21 if (options !== null && options !== void 0 && options.hasText) {22 const text = options.hasText;23 if ((0, _utils.isRegExp)(text)) this._selector += ` >> :scope:text-matches(${(0, _stringUtils.escapeWithQuotes)(text.source, '"')}, "${text.flags}")`;else this._selector += ` >> :scope:has-text(${(0, _stringUtils.escapeWithQuotes)(text, '"')})`;24 }25 }26 async _withElement(task, timeout) {27 timeout = this._frame.page()._timeoutSettings.timeout({28 timeout29 });30 const deadline = timeout ? (0, _utils.monotonicTime)() + timeout : 0;31 return this._frame._wrapApiCall(async () => {32 const result = await this._frame._channel.waitForSelector({33 selector: this._selector,34 strict: true,35 state: 'attached',36 timeout37 });38 const handle = _elementHandle.ElementHandle.fromNullable(result.element);39 if (!handle) throw new Error(`Could not resolve ${this._selector} to DOM Element`);40 try {41 return await task(handle, deadline ? deadline - (0, _utils.monotonicTime)() : 0);42 } finally {43 await handle.dispose();44 }45 });46 }47 async boundingBox(options) {48 return this._withElement(h => h.boundingBox(), options === null || options === void 0 ? void 0 : options.timeout);49 }50 async check(options = {}) {51 return this._frame.check(this._selector, {52 strict: true,53 ...options54 });55 }56 async click(options = {}) {57 return this._frame.click(this._selector, {58 strict: true,59 ...options60 });61 }62 async dblclick(options = {}) {63 return this._frame.dblclick(this._selector, {64 strict: true,65 ...options66 });67 }68 async dispatchEvent(type, eventInit = {}, options) {69 return this._frame.dispatchEvent(this._selector, type, eventInit, {70 strict: true,71 ...options72 });73 }74 async dragTo(target, options = {}) {75 return this._frame.dragAndDrop(this._selector, target._selector, { ...options,76 strict: true77 });78 }79 async evaluate(pageFunction, arg, options) {80 return this._withElement(h => h.evaluate(pageFunction, arg), options === null || options === void 0 ? void 0 : options.timeout);81 }82 async evaluateAll(pageFunction, arg) {83 return this._frame.$$eval(this._selector, pageFunction, arg);84 }85 async evaluateHandle(pageFunction, arg, options) {86 return this._withElement(h => h.evaluateHandle(pageFunction, arg), options === null || options === void 0 ? void 0 : options.timeout);87 }88 async fill(value, options = {}) {89 return this._frame.fill(this._selector, value, {90 strict: true,91 ...options92 });93 }94 async _highlight() {95 return this._frame._highlight(this._selector);96 }97 locator(selector, options) {98 return new Locator(this._frame, this._selector + ' >> ' + selector, options);99 }100 frameLocator(selector) {101 return new FrameLocator(this._frame, this._selector + ' >> ' + selector);102 }103 async elementHandle(options) {104 return await this._frame.waitForSelector(this._selector, {105 strict: true,106 state: 'attached',107 ...options108 });109 }110 async elementHandles() {111 return this._frame.$$(this._selector);112 }113 first() {114 return new Locator(this._frame, this._selector + ' >> nth=0');115 }116 last() {117 return new Locator(this._frame, this._selector + ` >> nth=-1`);118 }119 nth(index) {120 return new Locator(this._frame, this._selector + ` >> nth=${index}`);121 }122 async focus(options) {123 return this._frame.focus(this._selector, {124 strict: true,125 ...options126 });127 }128 async count() {129 return this._frame._queryCount(this._selector);130 }131 async getAttribute(name, options) {132 return this._frame.getAttribute(this._selector, name, {133 strict: true,134 ...options135 });136 }137 async hover(options = {}) {138 return this._frame.hover(this._selector, {139 strict: true,140 ...options141 });142 }143 async innerHTML(options) {144 return this._frame.innerHTML(this._selector, {145 strict: true,146 ...options147 });148 }149 async innerText(options) {150 return this._frame.innerText(this._selector, {151 strict: true,152 ...options153 });154 }155 async inputValue(options) {156 return this._frame.inputValue(this._selector, {157 strict: true,158 ...options159 });160 }161 async isChecked(options) {162 return this._frame.isChecked(this._selector, {163 strict: true,164 ...options165 });166 }167 async isDisabled(options) {168 return this._frame.isDisabled(this._selector, {169 strict: true,170 ...options171 });172 }173 async isEditable(options) {174 return this._frame.isEditable(this._selector, {175 strict: true,176 ...options177 });178 }179 async isEnabled(options) {180 return this._frame.isEnabled(this._selector, {181 strict: true,182 ...options183 });184 }185 async isHidden(options) {186 return this._frame.isHidden(this._selector, {187 strict: true,188 ...options189 });190 }191 async isVisible(options) {192 return this._frame.isVisible(this._selector, {193 strict: true,194 ...options195 });196 }197 async press(key, options = {}) {198 return this._frame.press(this._selector, key, {199 strict: true,200 ...options201 });202 }203 async screenshot(options = {}) {204 return this._withElement((h, timeout) => h.screenshot({ ...options,205 timeout206 }), options.timeout);207 }208 async scrollIntoViewIfNeeded(options = {}) {209 return this._withElement((h, timeout) => h.scrollIntoViewIfNeeded({ ...options,210 timeout211 }), options.timeout);212 }213 async selectOption(values, options = {}) {214 return this._frame.selectOption(this._selector, values, {215 strict: true,216 ...options217 });218 }219 async selectText(options = {}) {220 return this._withElement((h, timeout) => h.selectText({ ...options,221 timeout222 }), options.timeout);223 }224 async setChecked(checked, options) {225 if (checked) await this.check(options);else await this.uncheck(options);226 }227 async setInputFiles(files, options = {}) {228 return this._frame.setInputFiles(this._selector, files, {229 strict: true,230 ...options231 });232 }233 async tap(options = {}) {234 return this._frame.tap(this._selector, {235 strict: true,236 ...options237 });238 }239 async textContent(options) {240 return this._frame.textContent(this._selector, {241 strict: true,242 ...options243 });244 }245 async type(text, options = {}) {246 return this._frame.type(this._selector, text, {247 strict: true,248 ...options249 });250 }251 async uncheck(options = {}) {252 return this._frame.uncheck(this._selector, {253 strict: true,254 ...options255 });256 }257 async allInnerTexts() {258 return this._frame.$$eval(this._selector, ee => ee.map(e => e.innerText));259 }260 async allTextContents() {261 return this._frame.$$eval(this._selector, ee => ee.map(e => e.textContent || ''));262 }263 async waitFor(options) {264 await this._frame._channel.waitForSelector({265 selector: this._selector,266 strict: true,267 omitReturnValue: true,268 ...options269 });270 }271 async _expect(expression, options) {272 const params = {273 selector: this._selector,274 expression,275 ...options,276 isNot: !!options.isNot277 };278 if (options.expectedValue) params.expectedValue = (0, _jsHandle.serializeArgument)(options.expectedValue);279 const result = await this._frame._channel.expect(params);280 if (result.received !== undefined) result.received = (0, _jsHandle.parseResult)(result.received);281 return result;282 }283 [_util$inspect$custom]() {284 return this.toString();285 }286 toString() {287 return `Locator@${this._selector}`;288 }289}290exports.Locator = Locator;291class FrameLocator {292 constructor(frame, selector) {293 this._frame = void 0;294 this._frameSelector = void 0;295 this._frame = frame;296 this._frameSelector = selector;297 }298 locator(selector, options) {299 return new Locator(this._frame, this._frameSelector + ' >> control=enter-frame >> ' + selector, options);300 }301 frameLocator(selector) {302 return new FrameLocator(this._frame, this._frameSelector + ' >> control=enter-frame >> ' + selector);303 }304 first() {305 return new FrameLocator(this._frame, this._frameSelector + ' >> nth=0');306 }307 last() {308 return new FrameLocator(this._frame, this._frameSelector + ` >> nth=-1`);309 }310 nth(index) {311 return new FrameLocator(this._frame, this._frameSelector + ` >> nth=${index}`);312 }313}...
python.js
Source: python.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.PythonLanguageGenerator = void 0;6var _language = require("./language");7var _recorderActions = require("./recorderActions");8var _utils = require("./utils");9var _stringUtils = require("../../../utils/stringUtils");10var _deviceDescriptors = _interopRequireDefault(require("../../deviceDescriptors"));11function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }12/**13 * Copyright (c) Microsoft Corporation.14 *15 * Licensed under the Apache License, Version 2.0 (the "License");16 * you may not use this file except in compliance with the License.17 * You may obtain a copy of the License at18 *19 * http://www.apache.org/licenses/LICENSE-2.020 *21 * Unless required by applicable law or agreed to in writing, software22 * distributed under the License is distributed on an "AS IS" BASIS,23 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.24 * See the License for the specific language governing permissions and25 * limitations under the License.26 */27class PythonLanguageGenerator {28 constructor(isAsync) {29 this.id = 'python';30 this.fileName = 'Python';31 this.highlighter = 'python';32 this._awaitPrefix = void 0;33 this._asyncPrefix = void 0;34 this._isAsync = void 0;35 this.id = isAsync ? 'python-async' : 'python';36 this.fileName = isAsync ? 'Python Async' : 'Python';37 this._isAsync = isAsync;38 this._awaitPrefix = isAsync ? 'await ' : '';39 this._asyncPrefix = isAsync ? 'async ' : '';40 }41 generateAction(actionInContext) {42 const action = actionInContext.action;43 const pageAlias = actionInContext.frame.pageAlias;44 const formatter = new PythonFormatter(4);45 formatter.newLine();46 formatter.add('# ' + (0, _recorderActions.actionTitle)(action));47 if (action.name === 'openPage') {48 formatter.add(`${pageAlias} = ${this._awaitPrefix}context.new_page()`);49 if (action.url && action.url !== 'about:blank' && action.url !== 'chrome://newtab/') formatter.add(`${this._awaitPrefix}${pageAlias}.goto(${quote(action.url)})`);50 return formatter.format();51 }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
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.JavaLanguageGenerator = void 0;6var _language = require("./language");7var _recorderActions = require("./recorderActions");8var _utils = require("./utils");9var _deviceDescriptors = _interopRequireDefault(require("../../deviceDescriptors"));10var _javascript = require("./javascript");11var _stringUtils = require("../../../utils/stringUtils");12function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }13/**14 * Copyright (c) Microsoft Corporation.15 *16 * Licensed under the Apache License, Version 2.0 (the "License");17 * you may not use this file except in compliance with the License.18 * You may obtain a copy of the License at19 *20 * http://www.apache.org/licenses/LICENSE-2.021 *22 * Unless required by applicable law or agreed to in writing, software23 * distributed under the License is distributed on an "AS IS" BASIS,24 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.25 * See the License for the specific language governing permissions and26 * limitations under the License.27 */28class JavaLanguageGenerator {29 constructor() {30 this.id = 'java';31 this.fileName = 'Java';32 this.highlighter = 'java';33 }34 generateAction(actionInContext) {35 const action = actionInContext.action;36 const pageAlias = actionInContext.frame.pageAlias;37 const formatter = new _javascript.JavaScriptFormatter(6);38 formatter.newLine();39 formatter.add('// ' + (0, _recorderActions.actionTitle)(action));40 if (action.name === 'openPage') {41 formatter.add(`Page ${pageAlias} = context.newPage();`);42 if (action.url && action.url !== 'about:blank' && action.url !== 'chrome://newtab/') formatter.add(`${pageAlias}.navigate(${quote(action.url)});`);43 return formatter.format();44 }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]})`;...
consoleApi.js
Source: consoleApi.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.default = exports.ConsoleAPI = void 0;6var _stringUtils = require("../../../utils/stringUtils");7var _selectorGenerator = require("../../injected/selectorGenerator");8/**9 * Copyright (c) Microsoft Corporation.10 *11 * Licensed under the Apache License, Version 2.0 (the "License");12 * you may not use this file except in compliance with the License.13 * You may obtain a copy of the License at14 *15 * http://www.apache.org/licenses/LICENSE-2.016 *17 * Unless required by applicable law or agreed to in writing, software18 * distributed under the License is distributed on an "AS IS" BASIS,19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.20 * See the License for the specific language governing permissions and21 * limitations under the License.22 */23function createLocator(injectedScript, initial, options) {24 class Locator {25 constructor(selector, options) {26 this.selector = void 0;27 this.element = void 0;28 this.elements = void 0;29 this.selector = selector;30 if (options !== null && options !== void 0 && options.hasText) {31 const text = options.hasText;32 if (text instanceof RegExp) this.selector += ` >> :scope:text-matches(${(0, _stringUtils.escapeWithQuotes)(text.source, '"')}, "${text.flags}")`;else this.selector += ` >> :scope:has-text(${(0, _stringUtils.escapeWithQuotes)(text)})`;33 }34 const parsed = injectedScript.parseSelector(this.selector);35 this.element = injectedScript.querySelector(parsed, document, false);36 this.elements = injectedScript.querySelectorAll(parsed, document);37 }38 locator(selector, options) {39 return new Locator(this.selector ? this.selector + ' >> ' + selector : selector, options);40 }41 }42 return new Locator(initial, options);43}44class ConsoleAPI {45 constructor(injectedScript) {46 this._injectedScript = void 0;47 this._injectedScript = injectedScript;48 if (window.playwright) return;49 window.playwright = {50 $: (selector, strict) => this._querySelector(selector, !!strict),51 $$: selector => this._querySelectorAll(selector),52 locator: (selector, options) => createLocator(this._injectedScript, selector, options),53 inspect: selector => this._inspect(selector),54 selector: element => this._selector(element),55 resume: () => this._resume()56 };57 }58 _querySelector(selector, strict) {59 if (typeof selector !== 'string') throw new Error(`Usage: playwright.query('Playwright >> selector').`);60 const parsed = this._injectedScript.parseSelector(selector);61 return this._injectedScript.querySelector(parsed, document, strict);62 }63 _querySelectorAll(selector) {64 if (typeof selector !== 'string') throw new Error(`Usage: playwright.$$('Playwright >> selector').`);65 const parsed = this._injectedScript.parseSelector(selector);66 return this._injectedScript.querySelectorAll(parsed, document);67 }68 _inspect(selector) {69 if (typeof selector !== 'string') throw new Error(`Usage: playwright.inspect('Playwright >> selector').`);70 window.inspect(this._querySelector(selector, false));71 }72 _selector(element) {73 if (!(element instanceof Element)) throw new Error(`Usage: playwright.selector(element).`);74 return (0, _selectorGenerator.generateSelector)(this._injectedScript, element).selector;75 }76 _resume() {77 window._playwrightResume().catch(() => {});78 }79}80exports.ConsoleAPI = ConsoleAPI;81var _default = ConsoleAPI;...
utils.js
Source: utils.js
...59 isMainFrame: false,60 frameUrl: frame.url()61 };62}63function escapeWithQuotes(text, char = '\'') {64 const stringified = JSON.stringify(text);65 const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\"/g, '"');66 if (char === '\'') return char + escapedText.replace(/[']/g, '\\\'') + char;67 if (char === '"') return char + escapedText.replace(/["]/g, '\\"') + char;68 if (char === '`') return char + escapedText.replace(/[`]/g, '`') + char;69 throw new Error('Invalid escape char');...
stringUtils.js
Source: stringUtils.js
...17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.18 * See the License for the specific language governing permissions and19 * limitations under the License.20 */21function escapeWithQuotes(text, char = '\'') {22 const stringified = JSON.stringify(text);23 const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\"/g, '"');24 if (char === '\'') return char + escapedText.replace(/[']/g, '\\\'') + char;25 if (char === '"') return char + escapedText.replace(/["]/g, '\\"') + char;26 if (char === '`') return char + escapedText.replace(/[`]/g, '`') + char;27 throw new Error('Invalid escape char');...
Using AI Code Generation
1const { escapeWithQuotes } = require('playwright/lib/utils/utils');2const escapedString = escapeWithQuotes('This is a test string');3const { escapeWithQuotes } = require('playwright/lib/utils/utils');4const escapedString = escapeWithQuotes('This is a test string');5const { escapeWithQuotes } = require('playwright/lib/utils/utils');6const escapedString = escapeWithQuotes('This is a test string');7const { escapeWithQuotes } = require('playwright/lib/utils/utils');8const escapedString = escapeWithQuotes('This is a test string');9const { escapeWithQuotes } = require('playwright/lib/utils/utils');10const escapedString = escapeWithQuotes('This is a test string');11const { escapeWithQuotes } = require('playwright/lib/utils/utils');12const escapedString = escapeWithQuotes('This is a test string');13const { escapeWithQuotes } = require('playwright/lib/utils/utils');14const escapedString = escapeWithQuotes('This is a test string');15const { escapeWithQuotes } = require('playwright/lib/utils/utils');16const escapedString = escapeWithQuotes('This is a test string');17const { escapeWithQuotes } = require('playwright/lib/utils/utils');18const escapedString = escapeWithQuotes('This is a test string');19const { escapeWithQuotes } = require('playwright/lib/utils/utils');20const escapedString = escapeWithQuotes('This is a test string');21const { escapeWithQuotes } = require('playwright/lib/utils/utils');22const escapedString = escapeWithQuotes('This is a test string');23const { escapeWithQuotes } = require('playwright/lib/utils/utils');24const escapedString = escapeWithQuotes('This
Using AI Code Generation
1const { escapeWithQuotes } = require('playwright/lib/utils/stackTrace');2const { test } = require('@playwright/test');3test('escapeWithQuotes', async ({ page }) => {4 const result = escapeWithQuotes("Hello 'world'");5 console.log(result);6});
Using AI Code Generation
1const { escapeWithQuotes } = require('playwright/lib/utils/utils');2const escapedString = escapeWithQuotes('string with "quote"');3console.log(escapedString);4const { escapeWithQuotes } = require('playwright');5const escapedString = escapeWithQuotes('string with "quote"');6console.log(escapedString);7const { escapeWithQuotes } = require('@playwright/test');8const escapedString = escapeWithQuotes('string with "quote"');9console.log(escapedString);10const { escapeWithQuotes } = require('@playwright/test');11const escapedString = escapeWithQuotes('string with "quote"');12console.log(escapedString);13const { escapeWithQuotes } = require('@playwright/test');14const escapedString = escapeWithQuotes('string with "quote"');15console.log(escapedString);16const { escapeWithQuotes } = require('@playwright/test');17const escapedString = escapeWithQuotes('string with "quote"');18console.log(escapedString);19const { escapeWithQuotes } = require('@playwright/test');20const escapedString = escapeWithQuotes('string with "quote"');21console.log(escapedString);
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!!