Best JavaScript code snippet using playwright-internal
ve.track.js
Source: ve.track.js
...12 'mwtiming.behavior.lastTransactionTillSaveDialogOpen': function ( data ) {13 return {14 action: actions.OPEN,15 label: 'dialog-save',16 value: normalizeDuration( data.duration )17 };18 },19 'mwtiming.behavior.saveDialogClose': function ( data ) {20 return {21 action: actions.CLOSE,22 label: 'dialog-save',23 value: normalizeDuration( data.duration )24 };25 },26 'command.execute': function ( data ) {27 return {28 action: actions.KEYPRESS,29 label: 'tool-' + nameToLabel( data.name )30 };31 },32 'error.createdocumentfromhtml': function ( data ) {33 return {34 action: actions.ERROR,35 label: 'createdocumentfromhtml-' + data.message36 };37 },38 'mwtiming.performance.system.activation': function ( data ) {39 return {40 action: actions.IMPRESSION,41 label: 'edit-page-ready',42 value: normalizeDuration( data.duration )43 };44 },45 'mwtiming.performance.user.reviewComplete': function ( data ) {46 return {47 action: actions.SUCCESS,48 label: 'dialog-save-review-changes',49 value: normalizeDuration( data.duration )50 };51 },52 'mwtiming.performance.user.reviewError': function ( data ) {53 return {54 action: actions.ERROR,55 label: 'dialog-save-review-changes',56 value: normalizeDuration( data.duration )57 };58 },59 'mwtiming.performance.user.saveComplete': function ( data ) {60 return {61 action: actions.SUCCESS,62 label: 'publish',63 value: normalizeDuration( data.duration )64 };65 },66 'mwtiming.performance.user.saveError': function ( data, topics ) {67 if ( !data.type ) {68 data.type = topics[ topics.length - 1 ];69 }70 return {71 action: actions.ERROR,72 label: 'publish-' + data.type,73 retries: data.retries,74 value: normalizeDuration( data.duration )75 };76 },77 tool: function ( data ) {78 return {79 action: actions.CLICK,80 label: 'tool-' + nameToLabel( data.name ),81 value: data.toolbar === 'surface' ? 1 : 082 };83 }84 },85 // @see {@link nameToLabel} for more information86 nameToLabelMap = {87 meta: 'page-settings',88 mwSave: 'save',89 transclusion: 'template',90 wikiaMediaInsert: 'media-insert',91 wikiaSourceMode: 'source'92 },93 // A lot of the events sent in the 'wikia' topic are tracked generically (for example,94 // all dialog 'open' and 'close' events). Sometimes this isn't desired because we want95 // to track them manually and provide custom data. Adding those events to this array96 // will allow this. Events should be listed alphabetically in the format: "label/action"97 wikiaTopicBlacklist = [98 'dialog-save/close',99 'dialog-save/open'100 ],101 rUppercase = /[A-Z]/g;102 /**103 * Convert symbolic names to tracking labels, falling back to the symbolic name if there is104 * nothing else to map it to.105 *106 * @example107 * "meta" -> "page-settings"108 *109 * @method110 * @param {string} name The symbolic name111 * @returns {string} The converted label112 */113 function nameToLabel( name ) {114 return nameToLabelMap[name] || name;115 }116 /**117 * Normalize time durations, for example rounding up or down or limiting118 * the number of decimal spaces to keep.119 *120 * @method121 * @param {number} duration Time in milliseconds122 * @returns {number} Normalized time in milliseconds123 */124 function normalizeDuration( duration ) {125 return Math.round( duration );126 }127 /**128 * Editor tracking function.129 *130 * @method131 * @param {string} topic Event sub-category (like "tool", "button", etc.); this will be joined132 * with data.label to form the whole label for the event.133 * @param {Object} data The data to send to our internal tracking function.134 */135 function track( topic, data ) {136 var i, mwEvent, topics,137 params = {138 category: 'editor-ve',139 trackingMethod: 'analytics'140 };141 // MW events142 if ( topic !== 'wikia' ) {143 // MW events are categorized in dot notation (like "performance.system.activation")144 // This allows us to follow an entire topic ("performance") without having to track145 // all the sub-topics separately.146 topics = topic.split( '.' );147 for ( i = 0; i < topics.length; i++ ) {148 topic = ( i === 0 ? '' : topic + '.' ) + topics[i];149 mwEvent = mwTopics[topic];150 if ( mwEvent ) {151 // We have found a match; exit the loop152 break;153 }154 }155 // Only track things we care about156 if ( !mwEvent ) {157 return;158 }159 data = $.isFunction( mwEvent ) ? mwEvent( data, topics ) : mwEvent;160 }161 // Normalize tracking labels162 data.label = data.label.replace( rUppercase, upperToHyphenLower );163 // Don't track blacklisted Wikia tracking calls.164 if (165 topic === 'wikia' &&166 $.inArray( [ data.label, data.action ].join( '/' ), wikiaTopicBlacklist ) > -1167 ) {168 return;169 }170 // Funnel tracking171 handleFunnel( data );172 // Send off to Wikia.Tracker173 tracker.track( ve.extendObject( params, data ) );174 }175 /**176 * Track fake pageviews in GA for certain events177 * @method178 * @param {Object} data The tracking data179 */180 function handleFunnel( data ) {181 var funnelEvents = [182 'edit-page-ready/impression',183 'edit-page-ready-toolbartest/impression',184 'button-publish/enable',185 'button-cancel/click',186 'button-publish/click',187 'dialog-save-publish/click',188 'publish/success'189 ],190 funnelEvent = data.label + '/' + data.action;191 if ( funnelEvents.indexOf( funnelEvent ) !== -1 ) {192 window.guaTrackPageview( '/fake-visual-editor/' + funnelEvent, 've' );193 }194 }195 /**196 * Convert a string from lazyCamelCase to lowercase-hyphen style.197 *198 * @method199 * @param {string} match The matched string to convert.200 * @returns {string} The converted string.201 */202 function upperToHyphenLower( match ) {203 return '-' + match.toLowerCase();204 }205 // Track time to init when accessing directly from the URI via ?veaction=edit206 if ( mw.libs.ve.activateOnPageLoad ) {207 mw.hook( 've.activationComplete' ).add( function () {208 ve.track( 'wikia', {209 action: actions.IMPRESSION,210 label: 'edit-page-ready-from-page-load',211 value: normalizeDuration( ve.now() - window.wgNow )212 } );213 } );214 }215 // Exports216 ve.track.actions = actions;217 ve.track.nameToLabel = nameToLabel;218 ve.track.normalizeDuration = normalizeDuration;219 ve.trackSubscribeAll( track );220 /* jshint +W003 */...
duration.js
Source: duration.js
...12 constructor(key, value) {13 let duration = {},14 data = this._data = {},15 milliseconds = 0,16 normalizedUnit = normalizeDuration(key, value),17 unit = normalizedUnit.unit;18 duration[unit] = normalizedUnit.value;19 milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0;20 let years = duration.years || duration.year || duration.y || 0,21 months = duration.months || duration.month || duration.M || 0,22 weeks = duration.weeks || duration.w || duration.week || 0,23 days = duration.days || duration.d || duration.day || 0,24 hours = duration.hours || duration.hour || duration.h || 0,25 minutes = duration.minutes || duration.minute || duration.m || 0,26 seconds = duration.seconds || duration.second || duration.s || 0;27 // representation for dateAddRemove28 this._milliseconds = milliseconds + seconds * (1e3) + minutes * (6e4) + hours * (36e5);29 // Because of dateAddRemove treats 24 hours as different from a30 // day when working around DST, we need to store them separately...
SessionsTable.js
Source: SessionsTable.js
...6import LoadingCircle from "../common/LoadingCircle";7const SessionsTable = (props) => {8 let totalMillis = 0, sessionTotalCount = 0;9 const displayCountTime = (count, time) => {10 return `${count} / ${normalizeDuration(time)}`;11 };12 const isSessionData = props.sessionData.length > 0;13 const tableStyles = isSessionData ? 'table-striped' : undefined;14 return (15 <div className='position-relative'>16 <LoadingCircle marginTop='mt-5' height='h-75' loading={props.loading}/>17 <table className={`table text-center ${tableStyles} mt-4`}>18 <thead>19 <tr>20 <th scope="col">Session</th>21 <th scope="col">Count / Duration</th>22 </tr>23 </thead>24 <tbody>...
ve.init.wikia.TargetEvents.js
Source: ve.init.wikia.TargetEvents.js
...41 this.timings.beforeUnload = ve.now();42 ve.track( 'wikia', {43 action: ve.track.actions.CLOSE,44 label: 'window',45 value: ve.track.normalizeDuration( this.timings.beforeUnload - this.timings.surfaceReady )46 } );47 }48};49/**50 * Track when document save is complete51 */52ve.init.wikia.TargetEvents.prototype.onSaveComplete = function () {53 ve.init.wikia.TargetEvents.super.prototype.onSaveComplete.call( this );54 ve.track( 'wikia', {55 action: ve.track.actions.CLICK,56 label: 'dialog-save-publish',57 value: ve.track.normalizeDuration( ve.now() - this.timings.saveInitiated )58 } );59};60/*61 * Track when user deactivates VE by clicking back button62 */63ve.init.wikia.TargetEvents.prototype.onPopStateDeactivated = function () {64 ve.track( 'wikia', {65 action: ve.track.actions.CLICK,66 label: 'back',67 value: ve.track.normalizeDuration( ve.now() - this.timings.surfaceReady )68 } );...
EditTable.js
Source: EditTable.js
...25 id={id}26 key={index}27 firstCol={sessionName}28 secCol={type === 'day' ? createdAt : count}29 thirdCol={normalizeDuration(duration)}/>30 )31 ) : (32 <tr>33 <td colSpan={5} className='no-sessions text-center'>34 No sessions for this date35 </td>36 </tr>37 )}38 </tbody>39 </table>40 </div>41 );42};43export default EditTable;
dates.js
Source: dates.js
...8 return Interval.fromDateTimes(start, afterEnd).splitBy({ days: 1 }).map(i => i.start)9}10// The toFormat() function for a duration is pretty limited so doing my own.11export function formatDuration(duration) {12 const units = normalizeDuration(duration).toObject()13 return Object14 .keys(units)15 .map(unit => {16 if( units[unit] > 0 && unit != 'seconds' )17 return `${units[unit]}${unit.charAt(0)}`18 })19 .filter(segment => segment)20 .join(' ')21}22export function roundToLargestDuration(duration) {23 const units = normalizeDuration(duration).toObject()24 const largestUnit = Object25 .keys(units)26 .find(unit => units[unit] > 0)27 if( !largestUnit ) return 028 return `${units[largestUnit]} ${largestUnit}`29}30function normalizeDuration(duration) {31 return duration32 .shiftTo('years', 'months', 'days', 'hours', 'minutes', 'seconds')33 .normalize()...
normalizeDuration.js
Source: normalizeDuration.js
1const normalizeDuration = (duration) => {2// if under 1 hour don't show 0 hour3 const hours = new Date(duration).getUTCHours();4 const min = new Date(duration).getUTCMinutes();5 if (duration < 3600000) {6 return `${min} min`;7 } else if ((duration % 3600000) === 0) {8 // if exactly whole hours don't show 0 min9 return `${hours} h`;10 }11 // show hour and min12 return `${hours} h ${min} min`;13};...
normalizeDuration.test.js
Source: normalizeDuration.test.js
1import normalizeDuration from './../normalizeDuration';2describe('normalizeDuration', () => {3 it('shows minutes if under 1 hour duration', () => {4 expect(normalizeDuration(3500000)).toBe('58 min');5 });6 it('shows hours if over 1 hour duration', () => {7 expect(normalizeDuration(3600000)).toBe('1 h');8 });9 it('shows hours if over 1 hour duration', () => {10 expect(normalizeDuration(3800000)).toBe('1 h 3 min');11 });...
Using AI Code Generation
1const { chromium } = require('playwright');2const { normalizeDuration } = require('playwright/lib/utils/utils');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 console.log(normalizeDuration('1s'));7 console.log(normalizeDuration('1.5s'));8 console.log(normalizeDuration('100ms'));9 console.log(normalizeDuration('1.5s', '2s'));10 console.log(normalizeDuration('1.5s', '1s'));11 console.log(normalizeDuration('1.5s', '1.5s'));12 console.log(normalizeDuration('1.5s', '2s', '3s'));13 await browser.close();14})();15### `normalizeDuration(value, minimum, maximum)`
Using AI Code Generation
1const { chromium } = require('playwright');2const { normalizeDuration } = require('playwright/lib/utils/utils');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 console.log(normalizeDuration('1s'));7 console.log(normalizeDuration('1.5s'));8 console.log(normalizeDuration('100ms'));9 console.log(normalizeDuration('1.5s', '2s'));10 console.log(normalizeDuration('1.5s', '1s'));11 console.log(normalizeDuration('1.5s', '1.5s'));12 console.log(normalizeDuration('1.5s', '2s', '3s'));13 await browser.close();14})();
Using AI Code Generation
1const { normalizeDuration } = require('playwright/lib/helper');2const { normalizeDuration } = require('playwright/lib/helper');3const { normalizeDuration } = require('playwright/lib/helper');4const { normalizeDuration } = require('playwright/lib/helper');5const { normalizeDuration } = require('playwright/lib/helper');6const { normalizeDuration } = require('playwright/lib/helper');7const { normalizeDuration } = require('playwright/lib/helper');8const { normalizeDuration } = require('playwright/lib/helper');9const { normalizeDuration } = require('playwright/lib/helper');10const { normalizeDuration } = require('playwright/lib/helper');
Using AI Code Generation
1const { normalizeDuration } = require('@playwright/test/lib/utils/timeoutSettings');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 console.log(normalizeDuration(0));8 console.log(normalizeDuration(1));9 console.log(normalizeDuration(1000));10 console.log(normalizeDuration(1000000));11 await browser.close();12})();
Using AI Code Generation
1const { normalizeDuration } = requirer'playwright/lib/utils/utils');2const duration = normalizeDuration('10s');3const { toHaveText, toBeChecked } = require('expect-playwright');4expect.extend({ toHaveText, toBeChecked });5const { toHaveText } = require('expect-playwright');6expect.extend({ toHaveText });7await expect(page.locator('#text')).toHaveText('Hello World');8await expect(page.locator('#text')).toHaveText(/Hello/);9const { toBeChecked } = require('expect-playwright');10expect.extend({ toBeChecked });11await expect(page.locator('#checkbox')).toBeChecked();12const { toHaveValue } = require('expect-playwright');13expect.extend({ toHaveValue });14await expect(page.locator('#input')).toHaveValue('Hello World');15await expect(page.locator('#input')).toHaveValue(/Hello/);16const { toHaveSelector } = require('expect-playwright');17expect.extend({ toHaveSelector });18await expect(page.locator('#parent')).toHaveSelector('#child');19await expect(page.locator('#parent')).toHaveSelector(page.locator('#child'));20const { toHaveURL } = require('expect-playwright');21expect.extend({ toHaveURL });22await expect(page).toHaveURL(/playwright/);23This matcher accepts a `string` or `RegExp` and checks ifation(1.5);24console.log(`Normalized Duration: ${normalizedDuration}`);25[Apache 2.0](./LICENSE)
Using AI Code Generation
1const { normalizeDuration } = require('playwright/lib/utils/utils');2const duration = normalizeDuration('10s');3const { toHaveText, toBeChecked } = require('expect-playwright');4expect.extend({ toHaveText, toBeChecked });5const { toHaveText } = require('expect-playwright');6expect.extend({ toHaveText });7await expect(page.locator('#text')).toHaveText('Hello World');8await expect(page.locator('#text')).toHaveText(/Hello/);9const { toBeChecked } = require('expect-playwright');10expect.extend({ toBeChecked });11await expect(page.locator('#checkbox')).toBeChecked();12const { toHaveValue } = require('expect-playwright');13expect.extend({ toHaveValue });14await expect(page.locator('#input')).toHaveValue('Hello World');15await expect(page.locator('#input')).toHaveValue(/Hello/);16const { toHaveSelector } = require('expect-playwright');17expect.extend({ toHaveSelector });18await expect(page.locator('#parent')).toHaveSelector('#child');19await expect(page.locator('#parent')).toHaveSelector(page.locator('#child'));20const { toHaveURL } = require('expect-playwright');21expect.extend({ toHaveURL });22await expect(page).toHaveURL(/playwright/);
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!!