Best JavaScript code snippet using playwright-internal
dashboard_compressed_v1.js
Source: dashboard_compressed_v1.js
...16const {SimpleBlob, flattenSpecs} = require('./utils.js');17async function processDashboardCompressedV1(context, reports, commitSHA) {18 const timestamp = Date.now();19 const dashboardBlob = await SimpleBlob.create('dashboards', `compressed_v1/${commitSHA}.json`);20 await dashboardBlob.uploadGzipped(compressReports(reports));21 context.log(`22 ===== started dashboard compressed v1 =====23 SHA: ${commitSHA}24 ===== complete in ${Date.now() - timestamp}ms =====25 `);26}27module.exports = {processDashboardCompressedV1, compressReports};28function compressReports(reports) {29 const files = {};30 for (const report of reports) {31 for (const spec of flattenSpecs(report)) {32 let specs = files[spec.file];33 if (!specs) {34 specs = new Map();35 files[spec.file] = specs;36 }37 const specId = spec.file + '---' + spec.title + ' --- ' + spec.line;38 let specObject = specs.get(specId);39 if (!specObject) {40 specObject = {41 title: spec.title,42 line: spec.line,...
healthcheck.js
Source: healthcheck.js
...40 };41 }42 return merged;43}44function compressReports(reports) {45 const compressed = [];46 for (var i = 0; i < reports.length; i++) {47 let report = reports[i];48 let compressedReport = [];49 for (let name of services) {50 let serviceReport = report[name];51 if (!serviceReport) {52 compressedReport.push(null);53 continue;54 }55 compressedReport.push([56 serviceReport.ping,57 serviceReport.success,58 serviceReport.errors,59 ]);60 }61 compressed.push(compressedReport);62 }63 return compressed;64}65function parsePings(pings) {66 let report = {};67 // format with structure68 // {69 // "service": {70 // "success": 0,71 // "errors": 0,72 // "ping": average73 // }74 // }75 const workers = Object.keys(pings);76 for (let i = 0; i < workers.length; i++) {77 const [service, worker] = workers[i].split("@", 2);78 let ping = pings[ workers[i] ];79 if (!report[service]) {80 report[service] = {81 count: 1,82 ...ping,83 };84 } else {85 report[service].count += 1;86 report[service].ping += ping.ping;87 report[service].success += ping.success;88 report[service].errors += ping.errors;89 }90 }91 let unknownServices = [];92 const serviceKeys = Object.keys(report);93 for (let i = 0; i < serviceKeys.length; i++) {94 const service = serviceKeys[i];95 if (!services.includes(service)) {96 unknownServices.push(service);97 }98 report[service].ping = report[service].ping / report[service].count;99 delete report[service].count;100 }101 return [ report, unknownServices ];102}103// Triggered when this service sends a ping request and it gets completed104service.onPing((responsible, pings) => {105 const [ report, unknownServices ] = parsePings(pings);106 if (unknownServices.length > 0) {107 for (let i = 0; i < unknownServices.length; i++) {108 services.push(unknownServices[i]);109 }110 if (responsible) {111 service.redis.sadd("status:services", unknownServices, (err) => {112 if (!!err) {113 console.log(err);114 }115 });116 }117 }118 nextGroup.push(report);119 if (nextGroup.length >= reportsPerGroup) {120 if (responsible) {121 const group = mergeReports(nextGroup);122 service.redis.rpush(123 "status:reports",124 JSON.stringify(group),125 (err, items) => {126 if (!!err) {127 console.error(err);128 return;129 }130 if (items > historySize) {131 service.redis.lpop(132 "status:reports",133 items - historySize,134 (err) => {135 if (!!err) {136 console.error(err);137 return;138 }139 }140 );141 }142 }143 );144 }145 nextGroup = [];146 }147 toSend = {148 services,149 data: compressReports([report])[0],150 };151 let forWS = JSON.stringify(toSend);152 // Notify all the clients listening for this event153 for (let i = 0; i < statusListeners.length; i++) {154 statusListeners[i].send(forWS);155 }156});157// A new client wants to listen to service status158router.ws("/status", (ws, req) => {159 statusListeners.push(ws); // Register the client160 ws.on("close", () => {161 // The client disconnected. Remove from list.162 let index = statusListeners.indexOf(ws);163 statusListeners.splice(index, 1);164 });165});166router.get("/status/current", (req, res) => {167 res.send(toSend);168});169router.get("/status/past", (req, res) => {170 let { interval } = req.query;171 interval = parseInt(interval) || 2;172 if (interval > 12) {173 writeError(res, 400, "Requested interval is too big.");174 return;175 }176 service.redis.lrange("status:reports", 0, -1, (err, result) => {177 if (!!err) {178 console.error(err);179 writeError(res, 500);180 return;181 }182 let reports = [];183 let forInterval = [];184 if (interval > 1) {185 // Some intervals are skipped, so let's merge them186 for (let i = 0; i < result.length; i++) {187 forInterval.push(JSON.parse(result[i]));188 if (i > 0 && ((i + 1) % interval === 0)) {189 reports.push(mergeReports(forInterval));190 forInterval = [];191 }192 }193 forInterval = compressReports(forInterval);194 } else {195 for (let i = 0; i < result.length; i++) {196 reports.push(JSON.parse(result[i]));197 }198 }199 res.send({200 interval,201 services,202 forInterval,203 data: compressReports(reports)204 });205 });206});...
scan.js
Source: scan.js
...21 // }22 // console.log(`all scans complete`);23 // console.log(`compressing reports`);24 await combineJSON();25 // await compressReports();26 console.log(`reports compressed`);27}28async function fetchURLs() {29 const docURL = config.docURL;30 console.log(`requesting list of URLs to scan from ${docURL}`);31 const rsp = await fetch(docURL);32 const text = await rsp.text();33 return text.split(/\s+/);34}35// The shell version36async function lighthoose(37 url,38 date,39 config,40 opts = { chromeFlags: ["--headless", "--no-sandbox"] }41) {42 console.log(`scan starting on ${url}`);43 const happyUrl = url.replace(/[^A-z0-9]/g, "_");44 const outputDir = path.resolve(config.saveReportPath, happyUrl, date);45 const outputPath = path.resolve(outputDir, "lighthoose");46 // create reports dir47 await fs.ensureDir(outputDir);48 const onOpenshift = !!process.env.OPENSHIFT_BUILD_NAME;49 const openshiftCpuSlowdownMultiplier = 1;50 if (onOpenshift) {51 console.log(52 `detected openshift environment, setting CPU slowdown factor to ${1 /53 openshiftCpuSlowdownMultiplier}`54 );55 }56 const cmd = [57 `./node_modules/.bin/lighthouse`,58 `--chrome-flags="${opts.chromeFlags.join(" ")}"`,59 `--no-sandbox`,60 onOpenshift61 ? `--throttling.cpuSlowdownMultiplier=${openshiftCpuSlowdownMultiplier}`62 : "",63 `--output=json`,64 `--output=html`,65 `--output=csv`,66 `--output-path=${outputPath}`,67 `"${url}"`68 ].join(" ");69 try {70 const cmdOut = await shell(cmd);71 } catch (e) {72 console.log(`could not run lighthouse`);73 throw e;74 }75 console.log(`scan ${scanId} complete, report saved in ${outputDir}`);76}77async function combineJSON() {78 const reportPath = path.resolve(__dirname, config.saveReportPath);79 // properties of lighthouse JSON that we want to surface to the UI80 const INCLUDED_PROPS = [81 "audits.first-contentful-paint",82 "audits.first-meaningful-paint",83 "audits.speed-index"84 ];85 // properties of the lighthouse JSON that we don't want to surface to the86 // UI (essentially, sub-properties of INCLUDED_PROPS that we want to omit)87 const EXCLUDED_SUB_PROPS = _.flatten(88 ["displayValue", "id", "description", "scoreDisplayMode", "title"].map(sp =>89 INCLUDED_PROPS.map(ip => `${ip}.${sp}`)90 )91 );92 const jsonFiles = await globby(93 path.join(reportPath, "**", "lighthoose.report.json")94 );95 const combinedJSON = jsonFiles.map(require);96 // pick only the properties we care about for the UI97 const data = _(combinedJSON)98 .map(o =>99 _(o)100 .pick(INCLUDED_PROPS)101 .omit(EXCLUDED_SUB_PROPS)102 .value()103 )104 .value();105 // grab a copy of a few properties that were previously duplicated, for lookup in the UI106 const legend = _.pick(107 _.first(combinedJSON),108 _.flatten(INCLUDED_PROPS.map(ip => [`${ip}.description`, `${ip}.title`]))109 );110 await fs.writeJson(path.join(reportPath, "lighthoose.history.json"), {111 data,112 legend113 });114}115async function compressReports() {116 const reportPath = path.resolve(__dirname, config.saveReportPath);117 await zipdirp(reportPath, {118 saveTo: path.join(reportPath, "lighthoose-reports-all.zip"),119 filter: path => !/\.zip$/.test(path) // don't include existing zip files120 });121}122module.exports = scan;123if (require.main === module) {124 scan();...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 await context.tracing.start({ screenshots: true, snapshots: true });6 const page = await context.newPage();7 await context.tracing.stop({ path: 'trace.zip' });8 await browser.close();9})();10#### tracing.start(options)
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 await page.screenshot({ path: 'example.png' });7 await browser.close();8 await context._browserContext._options.recordVideo._recorder._video._compressReports();9})();
Using AI Code Generation
1const fs = require('fs');2const path = require('path');3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'example.png' });9 const reportsDirectory = path.join(__dirname, 'reports');10 const compressedReportsDirectory = path.join(__dirname, 'compressed-reports');11 await page.context().compressReports(reportsDirectory, compressedReportsDirectory);12 await browser.close();13})();14#### browserContext.compressReports(reportsDirectory, compressedReportsDirectory[, options])15const fs = require('fs');16const path = require('path');17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'example.png' });23 const reportsDirectory = path.join(__dirname, 'reports');24 const compressedReportsDirectory = path.join(__dirname, 'compressed-reports');25 await page.context().compressReports(reportsDirectory, compressedReportsDirectory);26 await browser.close();27})();28const fs = require('fs');29const path = require('path');30const { chromium } = require('playwright');31(async () => {32 const browser = await chromium.launch();
Using AI Code Generation
1const { compressReports } = require('@playwright/test');2(async () => {3 await compressReports({4 });5})();6### method: `compressReports(options)`7[Apache 2.0](LICENSE)
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!