Best JavaScript code snippet using playwright-internal
wkAccessibility.js
Source: wkAccessibility.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.getAccessibilityTree = getAccessibilityTree;6/**7 * Copyright (c) Microsoft Corporation.8 *9 * Licensed under the Apache License, Version 2.0 (the "License");10 * you may not use this file except in compliance with the License.11 * You may obtain a copy of the License at12 *13 * http://www.apache.org/licenses/LICENSE-2.014 *15 * Unless required by applicable law or agreed to in writing, software16 * distributed under the License is distributed on an "AS IS" BASIS,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 */21async function getAccessibilityTree(session, needle) {22 const objectId = needle ? needle._objectId : undefined;23 const {24 axNode25 } = await session.send('Page.accessibilitySnapshot', {26 objectId27 });28 const tree = new WKAXNode(axNode);29 return {30 tree,31 needle: needle ? tree._findNeedle() : null32 };33}34const WKRoleToARIARole = new Map(Object.entries({35 'TextField': 'textbox'36})); // WebKit localizes role descriptions on mac, but the english versions only add noise.37const WKUnhelpfulRoleDescriptions = new Map(Object.entries({38 'WebArea': 'HTML content',39 'Summary': 'summary',40 'DescriptionList': 'description list',41 'ImageMap': 'image map',42 'ListMarker': 'list marker',43 'Video': 'video playback',44 'Mark': 'highlighted',45 'contentinfo': 'content information',46 'Details': 'details',47 'DescriptionListDetail': 'description',48 'DescriptionListTerm': 'term',49 'alertdialog': 'web alert dialog',50 'dialog': 'web dialog',51 'status': 'application status',52 'tabpanel': 'tab panel',53 'application': 'web application'54}));55class WKAXNode {56 constructor(payload) {57 this._payload = void 0;58 this._children = void 0;59 this._payload = payload;60 this._children = [];61 for (const payload of this._payload.children || []) this._children.push(new WKAXNode(payload));62 }63 children() {64 return this._children;65 }66 _findNeedle() {67 if (this._payload.found) return this;68 for (const child of this._children) {69 const found = child._findNeedle();70 if (found) return found;71 }72 return null;73 }74 isControl() {75 switch (this._payload.role) {76 case 'button':77 case 'checkbox':78 case 'ColorWell':79 case 'combobox':80 case 'DisclosureTriangle':81 case 'listbox':82 case 'menu':83 case 'menubar':84 case 'menuitem':85 case 'menuitemcheckbox':86 case 'menuitemradio':87 case 'radio':88 case 'scrollbar':89 case 'searchbox':90 case 'slider':91 case 'spinbutton':92 case 'switch':93 case 'tab':94 case 'textbox':95 case 'TextField':96 case 'tree':97 return true;98 default:99 return false;100 }101 }102 _isTextControl() {103 switch (this._payload.role) {104 case 'combobox':105 case 'searchfield':106 case 'textbox':107 case 'TextField':108 return true;109 }110 return false;111 }112 _name() {113 if (this._payload.role === 'text') return this._payload.value || '';114 return this._payload.name || '';115 }116 isInteresting(insideControl) {117 const {118 role,119 focusable120 } = this._payload;121 const name = this._name();122 if (role === 'ScrollArea') return false;123 if (role === 'WebArea') return true;124 if (focusable || role === 'MenuListOption') return true; // If it's not focusable but has a control role, then it's interesting.125 if (this.isControl()) return true; // A non focusable child of a control is not interesting126 if (insideControl) return false;127 return this.isLeafNode() && !!name;128 }129 _hasRendundantTextChild() {130 if (this._children.length !== 1) return false;131 const child = this._children[0];132 return child._payload.role === 'text' && this._payload.name === child._payload.value;133 }134 isLeafNode() {135 if (!this._children.length) return true; // WebKit on Linux ignores everything inside text controls, normalize this behavior136 if (this._isTextControl()) return true; // WebKit for mac has text nodes inside heading, li, menuitem, a, and p nodes137 if (this._hasRendundantTextChild()) return true;138 return false;139 }140 serialize() {141 const node = {142 role: WKRoleToARIARole.get(this._payload.role) || this._payload.role,143 name: this._name()144 };145 if ('description' in this._payload && this._payload.description !== node.name) node.description = this._payload.description;146 if ('roledescription' in this._payload) {147 const roledescription = this._payload.roledescription;148 if (roledescription !== this._payload.role && WKUnhelpfulRoleDescriptions.get(this._payload.role) !== roledescription) node.roledescription = roledescription;149 }150 if ('value' in this._payload && this._payload.role !== 'text') {151 if (typeof this._payload.value === 'string') node.valueString = this._payload.value;else if (typeof this._payload.value === 'number') node.valueNumber = this._payload.value;152 }153 if ('checked' in this._payload) node.checked = this._payload.checked === 'true' ? 'checked' : this._payload.checked === 'false' ? 'unchecked' : 'mixed';154 if ('pressed' in this._payload) node.pressed = this._payload.pressed === 'true' ? 'pressed' : this._payload.pressed === 'false' ? 'released' : 'mixed';155 const userStringProperties = ['keyshortcuts', 'valuetext'];156 for (const userStringProperty of userStringProperties) {157 if (!(userStringProperty in this._payload)) continue;158 node[userStringProperty] = this._payload[userStringProperty];159 }160 const booleanProperties = ['disabled', 'expanded', 'focused', 'modal', 'multiline', 'multiselectable', 'readonly', 'required', 'selected'];161 for (const booleanProperty of booleanProperties) {162 // WebArea and ScorllArea treat focus differently than other nodes. They report whether their frame has focus,163 // not whether focus is specifically on the root node.164 if (booleanProperty === 'focused' && (this._payload.role === 'WebArea' || this._payload.role === 'ScrollArea')) continue;165 const value = this._payload[booleanProperty];166 if (!value) continue;167 node[booleanProperty] = value;168 }169 const numericalProperties = ['level', 'valuemax', 'valuemin'];170 for (const numericalProperty of numericalProperties) {171 if (!(numericalProperty in this._payload)) continue;172 node[numericalProperty] = this._payload[numericalProperty];173 }174 const tokenProperties = ['autocomplete', 'haspopup', 'invalid'];175 for (const tokenProperty of tokenProperties) {176 const value = this._payload[tokenProperty];177 if (!value || value === 'false') continue;178 node[tokenProperty] = value;179 }180 const orientationIsApplicable = new Set(['ScrollArea', 'scrollbar', 'listbox', 'combobox', 'menu', 'tree', 'separator', 'slider', 'tablist', 'toolbar']);181 if (this._payload.orientation && orientationIsApplicable.has(this._payload.role)) node.orientation = this._payload.orientation;182 return node;183 }...
accessibility.js
Source: accessibility.js
...52 this._channel = channel53 }54 async snapshot(options = {}) {55 const root = options.root ? options.root._elementChannel : undefined56 const result = await this._channel.accessibilitySnapshot({57 interestingOnly: options.interestingOnly,58 root59 })60 return result.rootAXNode ? axNodeFromProtocol(result.rootAXNode) : null61 }62}...
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const snapshot = await page.accessibility.snapshot();7 console.log(snapshot);8 await browser.close();9})();10{11 {12 {13 },14 {15 },16 {17 {18 }19 }20 }21}
Using AI Code Generation
1const { accessibilitySnapshot } = require('@playwright/test');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const snapshot = await accessibilitySnapshot(page);8 console.log(snapshot);9 await browser.close();10})();11const { test, expect } = require('@playwright/test');12test('snapshot', async ({ page }) => {
Using AI Code Generation
1const { accessibilitySnapshot } = require('@playwright/test');2const fs = require('fs');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const snapshot = await accessibilitySnapshot(page);8 fs.writeFileSync('snapshot.json', JSON.stringify(snapshot));9 await browser.close();10})();
Using AI Code Generation
1const { accessibilitySnapshot } = require('@playwright/test/lib/server/chromium/crBrowser');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const snapshot = await accessibilitySnapshot(page);8 console.log(snapshot);9 await browser.close();10})();11{12 {13 },14 {
Using AI Code Generation
1const { accessibilitySnapshot } = require('@playwright/test');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4 const snapshot = await accessibilitySnapshot(page);5 expect(snapshot).toMatchSnapshot('playwright-homepage.snapshot');6});7{8 {9 {10 }11 },12 {13 {14 }15 },16 {17 },18 {19 },20 {21 },22 {23 },24 {25 },26 {27 },28 {29 },
Using AI Code Generation
1const { accessibilitySnapshot } = require('playwright/lib/server/chromium/crBrowser');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const snapshot = await accessibilitySnapshot(page);8 console.log(snapshot);9 await browser.close();10})();11{12 {13 {
Using AI Code Generation
1const { accessibilitySnapshot } = require('@playwright/test/lib/server/trace/recorder/snapshotter');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4 const snapshot = await accessibilitySnapshot(page);5 expect(snapshot).toMatchSnapshot('accessibility.snapshot');6});7const { test, expect } = require('@playwright/test');8test('test', async ({ page }) => {9 const snapshot = await page.accessibility.snapshot();10 expect(snapshot).toMatchSnapshot('accessibility.snapshot');11});
Using AI Code Generation
1const { accessibilitySnapshot } = require('@playwright/test');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4 const snapshot = await accessibilitySnapshot(page);5 expect(snapshot).toMatchSnapshot('accessibility.snapshot');6});7Object {8 Object {9 Object {10 },11 },12}13`;14AccessibilitySnapshot {
Using AI Code Generation
1const playwright = require('playwright');2const fs = require('fs');3(async () => {4 const browser = await playwright.chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const snapshot = await page.accessibility.snapshot();8 fs.writeFileSync('snapshot.json', JSON.stringify(snapshot, null, 2));9 await browser.close();10})();11const playwright = require('playwright');12const fs = require('fs');13(async () => {14 const browser = await playwright.chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 const snapshot = await page.accessibility.snapshot();18 fs.writeFileSync('snapshot.json', JSON.stringify(snapshot, null, 2));19 await browser.close();20})();21const playwright = require('playwright');22const fs = require('fs');23(async () => {24 const browser = await playwright.chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 const snapshot = await page.accessibility.snapshot();28 fs.writeFileSync('snapshot.json', JSON.stringify(snapshot, null, 2));29 await browser.close();30})();31const playwright = require('playwright');32const fs = require('fs');33(async () => {34 const browser = await playwright.chromium.launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 const snapshot = await page.accessibility.snapshot();38 fs.writeFileSync('snapshot.json', JSON.stringify(snapshot, null, 2));39 await browser.close();40})();
Using AI Code Generation
1const { accessibilitySnapshot } = require('@playwright/test/lib/server/trace/recorder/snapshotter');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4 const snapshot = await accessibilitySnapshot(page);5 expect(snapshot).toMatchSnapshot('accessibility.snapshot');6});7const { test, expect } = require('@playwright/test');8test('test', async ({ page }) => {9 const snapshot = await page.accessibility.snapshot();10 expect(snapshot).toMatchSnapshot('accessibility.snapshot');11});
Using AI Code Generation
1const { accessibilitySnapshot } = require('@playwright/test');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4 const snapshot = await accessibilitySnapshot(page);5 expect(snapshot).toMatchSnapshot('accessibility.snapshot');6});7Object {8 Object {9 Object {10 },11 },12}13`;14AccessibilitySnapshot {
Using AI Code Generation
1const { accessibilitySnapshot } = require('@playwright/test/lib/server/trace/recorder/snapshotter');2const { getTestState } = require('@playwright/test/lib/server/trace/recorder/recorderProcess');3const { Accessibility } = require('@playwright/test/lib/server/trace/recorder/accessibility');4const { Page } = require('@playwright/test/lib/server/page');5const { Snapshotter } = require('@playwright/test/lib/server/snapshot/snapshotter');6const { SnapshotStorage } = require('@playwright/test/lib/server/snapshot/snapshotStorage');7const { SnapshotServer } = require('@playwright/test/lib/server/snapshot/snapshotServer');8(async () => {9 const page = await browser.newPage();10 const snapshotter = new Snapshotter(page, new SnapshotStorage(), new SnapshotServer());11 const accessibility = new Accessibility(page);12 const testState = getTestState();13 const context = page.context();14 const browser = context.browser();15 const browserContext = browser._browserContext;16 const snapshotServer = browserContext._snapshotter._snapshotServer;17 const snapshotStorage = browserContext._snapshotter._snapshotStorage;
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!!