Best JavaScript code snippet using puppeteer
browser_emulateNetworkConditions.js
Source:browser_emulateNetworkConditions.js
...19add_networking_task(async function offlineWithoutArguments({ client }) {20 const { Network } = client;21 let errorThrown = "";22 try {23 await Network.emulateNetworkConditions();24 } catch (e) {25 errorThrown = e.message;26 }27 ok(28 errorThrown.match(/offline: boolean value expected/),29 "Fails without any arguments"30 );31});32add_networking_task(async function offlineWithEmptyArguments({ client }) {33 const { Network } = client;34 let errorThrown = "";35 try {36 await Network.emulateNetworkConditions({});37 } catch (e) {38 errorThrown = e.message;39 }40 ok(41 errorThrown.match(/offline: boolean value expected/),42 "Fails with only empty arguments"43 );44});45add_networking_task(async function offlineWithInvalidArguments({ client }) {46 const { Network } = client;47 const testTable = [null, undefined, 1, "foo", [], {}];48 for (const testCase of testTable) {49 let errorThrown = "";50 try {51 await Network.emulateNetworkConditions({ offline: testCase });52 } catch (e) {53 errorThrown = e.message;54 }55 const testType = typeof testCase;56 ok(57 errorThrown.match(/offline: boolean value expected/),58 `Fails with ${testType}-type argument for offline`59 );60 }61});62add_networking_task(async function offlineWithUnsupportedArguments({ client }) {63 const { Network } = client;64 // Random valid values for the Network.emulateNetworkConditions command, even though we don't support them yet65 const args = {66 offline: true,67 latency: 500,68 downloadThroughput: 500,69 uploadThroughput: 500,70 connectionType: "cellular2g",71 someFutureArg: false,72 };73 await Network.emulateNetworkConditions(args);74 ok(true, "No errors should be thrown due to non-implemented arguments");75});76add_networking_task(async function emulateOfflineWhileOnline({ client }) {77 const { Network } = client;78 // Assert we're online to begin with79 await assertOfflineStatus(false);80 // Assert for offline81 await Network.emulateNetworkConditions({ offline: true });82 await assertOfflineStatus(true);83 // Assert we really can't navigate after setting offline84 await assertOfflineNavigationFails();85});86add_networking_task(async function emulateOfflineWhileOffline({ client }) {87 const { Network } = client;88 // Assert we're online to begin with89 await assertOfflineStatus(false);90 // Assert for offline91 await Network.emulateNetworkConditions({ offline: true });92 await assertOfflineStatus(true);93 // Assert for no-offline event, because we're offline - and changing to offline - so nothing changes94 await Network.emulateNetworkConditions({ offline: true });95 await assertOfflineStatus(true);96 // Assert we still can't navigate after setting offline twice97 await assertOfflineNavigationFails();98});99add_networking_task(async function emulateOnlineWhileOnline({ client }) {100 const { Network } = client;101 // Assert we're online to begin with102 await assertOfflineStatus(false);103 // Assert for no-offline event, because we're online - and changing to online - so nothing changes104 await Network.emulateNetworkConditions({ offline: false });105 await assertOfflineStatus(false);106});107add_networking_task(async function emulateOnlineWhileOffline({ client }) {108 const { Network } = client;109 // Assert we're online to begin with110 await assertOfflineStatus(false);111 // Assert for offline event, because we're online - and changing to offline112 const offlineChanged = Promise.race([113 BrowserTestUtils.waitForContentEvent(114 gBrowser.selectedBrowser,115 "online",116 true117 ),118 BrowserTestUtils.waitForContentEvent(119 gBrowser.selectedBrowser,120 "offline",121 true122 ),123 ]);124 await Network.emulateNetworkConditions({ offline: true });125 info("Waiting for offline event on window");126 is(await offlineChanged, "offline", "Only the offline-event should fire");127 await assertOfflineStatus(true);128 // Assert for online event, because we're offline - and changing to online129 const offlineChangedBack = Promise.race([130 BrowserTestUtils.waitForContentEvent(131 gBrowser.selectedBrowser,132 "online",133 true134 ),135 BrowserTestUtils.waitForContentEvent(136 gBrowser.selectedBrowser,137 "offline",138 true139 ),140 ]);141 await Network.emulateNetworkConditions({ offline: false });142 info("Waiting for online event on window");143 is(await offlineChangedBack, "online", "Only the online-event should fire");144 await assertOfflineStatus(false);145});146/**147 * Navigates to a page, and asserting any status code to appear148 */149async function assertOfflineNavigationFails() {150 // Tests always connect to localhost, and per bug 87717, localhost is now151 // reachable in offline mode. To avoid this, disable any proxy.152 const proxyPrefValue = SpecialPowers.getIntPref("network.proxy.type");153 const diskPrefValue = SpecialPowers.getBoolPref("browser.cache.disk.enable");154 const memoryPrefValue = SpecialPowers.getBoolPref(155 "browser.cache.memory.enable"...
emulation.js
Source:emulation.js
1/**2 * @license3 * Copyright 2016 Google Inc. All Rights Reserved.4 *5 * Licensed under the Apache License, Version 2.0 (the "License");6 * you may not use this file except in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17'use strict';18/**19 * Nexus 5X metrics adapted from emulated_devices/module.json20 */21const NEXUS5X_EMULATION_METRICS = {22 mobile: true,23 screenWidth: 412,24 screenHeight: 732,25 width: 412,26 height: 732,27 positionX: 0,28 positionY: 0,29 scale: 1,30 deviceScaleFactor: 2.625,31 fitWindow: false,32 screenOrientation: {33 angle: 0,34 type: 'portraitPrimary'35 }36};37const NEXUS5X_USERAGENT = {38 userAgent: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5 Build/MRA58N) AppleWebKit/537.36' +39 '(KHTML, like Gecko) Chrome/52.0.2743.8 Mobile Safari/537.36'40};41const TYPICAL_MOBILE_THROTTLING_METRICS = {42 latency: 150, // 150ms43 downloadThroughput: Math.floor(1.6 * 1024 * 1024 / 8), // 1.6Mbps44 uploadThroughput: Math.floor(750 * 1024 / 8), // 750Kbps45 offline: false46};47const OFFLINE_METRICS = {48 offline: true,49 // values of 0 remove any active throttling. crbug.com/456324#c950 latency: 0,51 downloadThroughput: 0,52 uploadThroughput: 053};54const NO_THROTTLING_METRICS = {55 latency: 0,56 downloadThroughput: 0,57 uploadThroughput: 0,58 offline: false59};60const NO_CPU_THROTTLE_METRICS = {61 rate: 162};63const CPU_THROTTLE_METRICS = {64 rate: 565};66function enableNexus5X(driver) {67 /**68 * Finalizes touch emulation by enabling `"ontouchstart" in window` feature detect69 * to work. Messy hack, though copied verbatim from DevTools' emulation/TouchModel.js70 * where it's been working for years. addScriptToEvaluateOnLoad runs before any of the71 * page's JavaScript executes.72 */73 /* eslint-disable no-proto */ /* global window, document */ /* istanbul ignore next */74 const injectedTouchEventsFunction = function() {75 const touchEvents = ['ontouchstart', 'ontouchend', 'ontouchmove', 'ontouchcancel'];76 var recepients = [window.__proto__, document.__proto__];77 for (var i = 0; i < touchEvents.length; ++i) {78 for (var j = 0; j < recepients.length; ++j) {79 if (!(touchEvents[i] in recepients[j])) {80 Object.defineProperty(recepients[j], touchEvents[i], {81 value: null, writable: true, configurable: true, enumerable: true82 });83 }84 }85 }86 };87 /* eslint-enable */88 return Promise.all([89 driver.sendCommand('Emulation.setDeviceMetricsOverride', NEXUS5X_EMULATION_METRICS),90 // Network.enable must be called for UA overriding to work91 driver.sendCommand('Network.enable'),92 driver.sendCommand('Network.setUserAgentOverride', NEXUS5X_USERAGENT),93 driver.sendCommand('Emulation.setTouchEmulationEnabled', {94 enabled: true,95 configuration: 'mobile'96 }),97 driver.sendCommand('Page.addScriptToEvaluateOnLoad', {98 scriptSource: '(' + injectedTouchEventsFunction.toString() + ')()'99 })100 ]);101}102function enableNetworkThrottling(driver) {103 return driver.sendCommand('Network.emulateNetworkConditions', TYPICAL_MOBILE_THROTTLING_METRICS);104}105function disableNetworkThrottling(driver) {106 return driver.sendCommand('Network.emulateNetworkConditions', NO_THROTTLING_METRICS);107}108function goOffline(driver) {109 return driver.sendCommand('Network.emulateNetworkConditions', OFFLINE_METRICS);110}111function enableCPUThrottling(driver) {112 return driver.sendCommand('Emulation.setCPUThrottlingRate', CPU_THROTTLE_METRICS);113}114function disableCPUThrottling(driver) {115 return driver.sendCommand('Emulation.setCPUThrottlingRate', NO_CPU_THROTTLE_METRICS);116}117module.exports = {118 enableNexus5X,119 enableNetworkThrottling,120 disableNetworkThrottling,121 enableCPUThrottling,122 disableCPUThrottling,123 goOffline...
networkHandler.test.js
Source:networkHandler.test.js
1const chai = require('chai');2const rewire = require('rewire');3const expect = chai.expect;4const chaiAsPromissed = require('chai-as-promised');5chai.use(chaiAsPromissed);6const test_name = 'Network Handler';7describe(test_name, () => {8 let actualNetworkCondition, networkHandler;9 before(() => {10 networkHandler = rewire('../../../lib/handlers/networkHandler');11 delete process.env.TAIKO_EMULATE_NETWORK;12 let network = {13 requestWillBeSent: () => {},14 loadingFinished: () => {},15 loadingFailed: () => {},16 responseReceived: () => {},17 setCacheDisabled: () => {},18 setRequestInterception: () => {},19 requestIntercepted: () => {},20 emulateNetworkConditions: (networkCondition) => {21 actualNetworkCondition = networkCondition;22 return Promise.resolve();23 },24 };25 networkHandler.__set__('network', network);26 });27 after(() => {28 actualNetworkCondition = {};29 const createdSessionListener = networkHandler.__get__('createdSessionListener');30 networkHandler.__get__('eventHandler').removeListener('createdSession', createdSessionListener);31 networkHandler = rewire('../../../lib/handlers/networkHandler');32 networkHandler.__get__('eventHandler').removeListener('createdSession', createdSessionListener);33 process.env.TAIKO_EMULATE_NETWORK = '';34 });35 describe('setNetworkEmulation', () => {36 it('should invoke emulateNetworkConditions with a correct String option', async () => {37 const expectedNetworkCondition = {38 offline: false,39 downloadThroughput: 6400,40 uploadThroughput: 2560,41 latency: 500,42 };43 await networkHandler.setNetworkEmulation('GPRS');44 expect(actualNetworkCondition).to.deep.equal(expectedNetworkCondition);45 });46 it('should invoke emulateNetworkConditions with a correct Object option', async () => {47 const expectedNetworkCondition = {48 offline: false,49 downloadThroughput: 6400,50 uploadThroughput: 2560,51 latency: 500,52 };53 await networkHandler.setNetworkEmulation(expectedNetworkCondition);54 expect(actualNetworkCondition).to.deep.equal(expectedNetworkCondition);55 });56 it('should invoke emulateNetworkConditions with the set defaults if an incomplete Object option is provided', async () => {57 const defaultNetworkCondition = {58 offline: false,59 downloadThroughput: 0,60 uploadThroughput: 0,61 latency: 0,62 };63 const expectedNetworkCondition = {64 ...defaultNetworkCondition,65 uploadThroughput: 2500,66 };67 await networkHandler.setNetworkEmulation({ uploadThroughput: 2500 });68 expect(actualNetworkCondition).to.deep.equal(expectedNetworkCondition);69 });70 it('should throw error for invalid network type', async () => {71 return expect(72 networkHandler.setNetworkEmulation('invalid network'),73 ).to.eventually.rejectedWith(74 `Please set one of the given network types \n${[75 'GPRS',76 'Regular2G',77 'Good2G',78 'Regular3G',79 'Good3G',80 'Regular4G',81 'DSL',82 'WiFi',83 'Offline',84 ].join('\n')}`,85 );86 });87 it('should use networkType from config when not provided', async () => {88 process.env.TAIKO_EMULATE_NETWORK = 'GPRS';89 const expectedNetworkCondition = {90 offline: false,91 downloadThroughput: 6400,92 uploadThroughput: 2560,93 latency: 500,94 };95 await networkHandler.setNetworkEmulation();96 expect(actualNetworkCondition).to.deep.equal(expectedNetworkCondition);97 });98 });...
watcher.js
Source:watcher.js
1const puppeteer = require('puppeteer');2const fs = require('fs');3const { random, sample } = require('lodash');4const server = require('./server');5const { NETWORK_PRESETS, PORT } = require('./config')6const players = fs.readdirSync('./dist').filter((file) => file.match(/player-/));7const randomPlayer = sample(players);8console.log('Players found: ', players);9console.log('Random player chosen: ', randomPlayer);10(async () => {11 await server.start(PORT);12 const browser = await puppeteer.launch({executablePath: '/usr/bin/google-chrome', args: ['--no-sandbox', "--disable-dev-shm-usage"]});13 const page = await browser.newPage();14 const client = await page.target().createCDPSession()15 const randomStart = random(0, 100);16 if (randomStart < 15) {17 console.log('This bot got the short end of the stick...giving it a 3G connection.');18 await client.send('Network.emulateNetworkConditions', NETWORK_PRESETS['Regular3G']);19 } else if (randomStart > 75) {20 console.log('This bot wins! No throttling.');21 } else {22 const presetName = sample(Object.keys(NETWORK_PRESETS));23 console.log(`Assigning a random preset: ${presetName}`);24 await client.send('Network.emulateNetworkConditions', NETWORK_PRESETS[presetName]);25 }26 page.on('console', msg => {27 switch (msg._text) {28 case '--network_change--': {29 console.log('Network change triggered');30 client.send('Network.emulateNetworkConditions', sample(NETWORK_PRESETS));31 break;32 }33 case '--finished--': {34 console.log('Player example said farewell. Shutting things down.');35 browser.close();36 server.stop();37 break;38 }39 }40 });41 await page.goto(`http://localhost:${PORT}/${randomPlayer}`);...
offline.js
Source:offline.js
1// use window.navigator.onLine property to determine2// if the browser is offline or online3// https://caniuse.com/online-status4Cypress.assertOnline = () => {5 return cy.wrap(window).its('navigator.onLine').should('be.true')6}7Cypress.assertOffline = () => {8 return cy.wrap(window).its('navigator.onLine').should('be.false')9}10 11Cypress.goOffline = (fn) => {12 cy.log('**go offline**')13 .then(() => {14 Cypress.automation('remote:debugger:protocol',15 {16 command: 'Network.enable',17 })18 })19 .then(() => {20 Cypress.automation('remote:debugger:protocol',21 {22 command: 'Network.emulateNetworkConditions',23 params: {24 offline: true,25 latency: -1,26 downloadThroughput: -1,27 uploadThroughput: -1,28 },29 })30 }) 31 }32 33Cypress.goOnline = (fn) => {34 cy.log('**go online**')35 .then(() => {36 // Remove all service workers37 Cypress.removeSWs()38 39 // https://chromedevtools.github.io/devtools-protocol/1-3/Network/#method-emulateNetworkConditions40 Cypress.automation('remote:debugger:protocol',41 {42 command: 'Network.emulateNetworkConditions',43 params: {44 offline: false,45 latency: -1,46 downloadThroughput: -1,47 uploadThroughput: -1,48 },49 }).then(() => {50 return Cypress.automation('remote:debugger:protocol',51 {52 command: 'Network.enable',53 })54 })55 })56}57 Cypress.removeSWs = () => {58 navigator.serviceWorker.getRegistrations().then(function(registrations) {59 for(let registration of registrations) {60 registration.unregister()61 } })...
utils.js
Source:utils.js
1export const EXTENDED_TIMEOUT = { timeout: 15000 }2export const goOffline = () => {3 cy.log('**go offline**')4 .then(() => {5 return Cypress.automation('remote:debugger:protocol', {6 command: 'Network.enable',7 })8 })9 .then(() => {10 return Cypress.automation('remote:debugger:protocol', {11 command: 'Network.emulateNetworkConditions',12 params: {13 offline: true,14 latency: -1,15 downloadThroughput: -1,16 uploadThroughput: -1,17 },18 })19 })20}21export const goOnline = () => {22 // disable offline mode, otherwise we will break our tests :)23 cy.log('**go online**')24 .then(() => {25 return Cypress.automation('remote:debugger:protocol', {26 command: 'Network.emulateNetworkConditions',27 params: {28 offline: false,29 latency: -1,30 downloadThroughput: -1,31 uploadThroughput: -1,32 },33 })34 })35 .then(() => {36 return Cypress.automation('remote:debugger:protocol', {37 command: 'Network.disable',38 })39 })...
index.js
Source:index.js
...13 latency: 10,14 downloadThroughput: 100000,15 uploadThroughput: 10000016 };17 await cdp.Network.emulateNetworkConditions(networkConditions);18 setTimeout(() => {19 networkConditions.offline = false;20 cdp.Network.emulateNetworkConditions(networkConditions);21 }, 5000);22 const expectedClickCount = 10;23 for (let i = 0; i < expectedClickCount; i++)24 await t.click('button');25 const actualClickCount = await getClickCount();26 await t.expect(actualClickCount).eql(expectedClickCount);...
network.js
Source:network.js
1const goOffline = () => {2 cy.log( '**go offline**' )3 .then( () => {4 return Cypress.automation( 'remote:debugger:protocol',5 {6 command: 'Network.enable'7 } )8 } )9 .then( () => {10 return Cypress.automation( 'remote:debugger:protocol',11 {12 command: 'Network.emulateNetworkConditions',13 params: {14 offline: true,15 latency: -1,16 downloadThroughput: -1,17 uploadThroughput: -118 }19 } )20 } )21}22const goOnline = () => {23 // disable offline mode, otherwise we will break our tests :)24 cy.log( '**go online**' )25 .then( () => {26 // https://chromedevtools.github.io/devtools-protocol/1-3/Network/#method-emulateNetworkConditions27 return Cypress.automation( 'remote:debugger:protocol',28 {29 command: 'Network.emulateNetworkConditions',30 params: {31 offline: false,32 latency: -1,33 downloadThroughput: -1,34 uploadThroughput: -135 }36 } )37 } )38 .then( () => {39 return Cypress.automation( 'remote:debugger:protocol',40 {41 command: 'Network.disable'42 } )43 } )44}...
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({ headless: false });4 const page = await browser.newPage();5 await page.emulateNetworkConditions({6 });7 await browser.close();8})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.emulateNetworkConditions({6 });7 await page.screenshot({path: 'test.png'});8 await browser.close();9})();10const puppeteer = require('puppeteer');11(async () => {12 const browser = await puppeteer.launch({headless: false});13 const page = await browser.newPage();14 await page.emulate({15 viewport: {16 },17 });18 await page.screenshot({path: 'test.png'});19 await browser.close();20})();21const puppeteer = require('puppeteer');22(async () => {23 const browser = await puppeteer.launch({headless: false});24 const page = await browser.newPage();25 await page.emulate({26 viewport: {27 },28 });29 await page.screenshot({path: 'test.png'});30 await browser.close();31})();32const puppeteer = require('puppeteer');33(async () => {34 const browser = await puppeteer.launch({headless: false});35 const page = await browser.newPage();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.emulateNetworkConditions({6 });7 await browser.close();8})();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!