Best JavaScript code snippet using puppeteer
jshandle.spec.js
Source:jshandle.spec.js
...20 setupTestPageAndContextHooks();21 describe('Page.evaluateHandle', function() {22 it('should work', async() => {23 const {page} = getTestState();24 const windowHandle = await page.evaluateHandle(() => window);25 expect(windowHandle).toBeTruthy();26 });27 it('should accept object handle as an argument', async() => {28 const {page} = getTestState();29 const navigatorHandle = await page.evaluateHandle(() => navigator);30 const text = await page.evaluate(e => e.userAgent, navigatorHandle);31 expect(text).toContain('Mozilla');32 });33 it('should accept object handle to primitive types', async() => {34 const {page} = getTestState();35 const aHandle = await page.evaluateHandle(() => 5);36 const isFive = await page.evaluate(e => Object.is(e, 5), aHandle);37 expect(isFive).toBeTruthy();38 });39 it('should warn on nested object handles', async() => {40 const {page} = getTestState();41 const aHandle = await page.evaluateHandle(() => document.body);42 let error = null;43 await page.evaluateHandle(44 opts => opts.elem.querySelector('p'),45 {elem: aHandle}46 ).catch(error_ => error = error_);47 expect(error.message).toContain('Are you passing a nested JSHandle?');48 });49 it('should accept object handle to unserializable value', async() => {50 const {page} = getTestState();51 const aHandle = await page.evaluateHandle(() => Infinity);52 expect(await page.evaluate(e => Object.is(e, Infinity), aHandle)).toBe(true);53 });54 it('should use the same JS wrappers', async() => {55 const {page} = getTestState();56 const aHandle = await page.evaluateHandle(() => {57 window.FOO = 123;58 return window;59 });60 expect(await page.evaluate(e => e.FOO, aHandle)).toBe(123);61 });62 it('should work with primitives', async() => {63 const {page} = getTestState();64 const aHandle = await page.evaluateHandle(() => {65 window.FOO = 123;66 return window;67 });68 expect(await page.evaluate(e => e.FOO, aHandle)).toBe(123);69 });70 });71 describe('JSHandle.getProperty', function() {72 it('should work', async() => {73 const {page} = getTestState();74 const aHandle = await page.evaluateHandle(() => ({75 one: 1,76 two: 2,77 three: 378 }));79 const twoHandle = await aHandle.getProperty('two');80 expect(await twoHandle.jsonValue()).toEqual(2);81 });82 });83 describe('JSHandle.jsonValue', function() {84 it('should work', async() => {85 const {page} = getTestState();86 const aHandle = await page.evaluateHandle(() => ({foo: 'bar'}));87 const json = await aHandle.jsonValue();88 expect(json).toEqual({foo: 'bar'});89 });90 itFailsFirefox('should not work with dates', async() => {91 const {page} = getTestState();92 const dateHandle = await page.evaluateHandle(() => new Date('2017-09-26T00:00:00.000Z'));93 const json = await dateHandle.jsonValue();94 expect(json).toEqual({});95 });96 it('should throw for circular objects', async() => {97 const {page, isChrome} = getTestState();98 const windowHandle = await page.evaluateHandle('window');99 let error = null;100 await windowHandle.jsonValue().catch(error_ => error = error_);101 if (isChrome)102 expect(error.message).toContain('Object reference chain is too long');103 else104 expect(error.message).toContain('Object is not serializable');105 });106 });107 describe('JSHandle.getProperties', function() {108 it('should work', async() => {109 const {page} = getTestState();110 const aHandle = await page.evaluateHandle(() => ({111 foo: 'bar'112 }));113 const properties = await aHandle.getProperties();114 const foo = properties.get('foo');115 expect(foo).toBeTruthy();116 expect(await foo.jsonValue()).toBe('bar');117 });118 it('should return even non-own properties', async() => {119 const {page} = getTestState();120 const aHandle = await page.evaluateHandle(() => {121 class A {122 constructor() {123 this.a = '1';124 }125 }126 class B extends A {127 constructor() {128 super();129 this.b = '2';130 }131 }132 return new B();133 });134 const properties = await aHandle.getProperties();135 expect(await properties.get('a').jsonValue()).toBe('1');136 expect(await properties.get('b').jsonValue()).toBe('2');137 });138 });139 describe('JSHandle.asElement', function() {140 it('should work', async() => {141 const {page} = getTestState();142 const aHandle = await page.evaluateHandle(() => document.body);143 const element = aHandle.asElement();144 expect(element).toBeTruthy();145 });146 it('should return null for non-elements', async() => {147 const {page} = getTestState();148 const aHandle = await page.evaluateHandle(() => 2);149 const element = aHandle.asElement();150 expect(element).toBeFalsy();151 });152 itFailsFirefox('should return ElementHandle for TextNodes', async() => {153 const {page} = getTestState();154 await page.setContent('<div>ee!</div>');155 const aHandle = await page.evaluateHandle(() => document.querySelector('div').firstChild);156 const element = aHandle.asElement();157 expect(element).toBeTruthy();158 expect(await page.evaluate(e => e.nodeType === HTMLElement.TEXT_NODE, element));159 });160 itFailsFirefox('should work with nullified Node', async() => {161 const {page} = getTestState();162 await page.setContent('<section>test</section>');163 await page.evaluate(() => delete Node);164 const handle = await page.evaluateHandle(() => document.querySelector('section'));165 const element = handle.asElement();166 expect(element).not.toBe(null);167 });168 });169 describe('JSHandle.toString', function() {170 it('should work for primitives', async() => {171 const {page} = getTestState();172 const numberHandle = await page.evaluateHandle(() => 2);173 expect(numberHandle.toString()).toBe('JSHandle:2');174 const stringHandle = await page.evaluateHandle(() => 'a');175 expect(stringHandle.toString()).toBe('JSHandle:a');176 });177 it('should work for complicated objects', async() => {178 const {page} = getTestState();179 const aHandle = await page.evaluateHandle(() => window);180 expect(aHandle.toString()).toBe('JSHandle@object');181 });182 it('should work with different subtypes', async() => {183 const {page} = getTestState();184 expect((await page.evaluateHandle('(function(){})')).toString()).toBe('JSHandle@function');185 expect((await page.evaluateHandle('12')).toString()).toBe('JSHandle:12');186 expect((await page.evaluateHandle('true')).toString()).toBe('JSHandle:true');187 expect((await page.evaluateHandle('undefined')).toString()).toBe('JSHandle:undefined');188 expect((await page.evaluateHandle('"foo"')).toString()).toBe('JSHandle:foo');189 expect((await page.evaluateHandle('Symbol()')).toString()).toBe('JSHandle@symbol');190 expect((await page.evaluateHandle('new Map()')).toString()).toBe('JSHandle@map');191 expect((await page.evaluateHandle('new Set()')).toString()).toBe('JSHandle@set');192 expect((await page.evaluateHandle('[]')).toString()).toBe('JSHandle@array');193 expect((await page.evaluateHandle('null')).toString()).toBe('JSHandle:null');194 expect((await page.evaluateHandle('/foo/')).toString()).toBe('JSHandle@regexp');195 expect((await page.evaluateHandle('document.body')).toString()).toBe('JSHandle@node');196 expect((await page.evaluateHandle('new Date()')).toString()).toBe('JSHandle@date');197 expect((await page.evaluateHandle('new WeakMap()')).toString()).toBe('JSHandle@weakmap');198 expect((await page.evaluateHandle('new WeakSet()')).toString()).toBe('JSHandle@weakset');199 expect((await page.evaluateHandle('new Error()')).toString()).toBe('JSHandle@error');200 expect((await page.evaluateHandle('new Int32Array()')).toString()).toBe('JSHandle@typedarray');201 expect((await page.evaluateHandle('new Proxy({}, {})')).toString()).toBe('JSHandle@proxy');202 });203 });...
jshandle.js
Source:jshandle.js
...16 await helper.end()17})18test.serial('Page.evaluateHandle should work', async t => {19 const { page, server } = t.context20 const windowHandle = await page.evaluateHandle(() => window)21 t.truthy(windowHandle)22})23test.serial(24 'Page.evaluateHandle should accept object handle as an argument',25 async t => {26 const { page, server } = t.context27 const navigatorHandle = await page.evaluateHandle(() => navigator)28 const text = await page.evaluate(e => e.userAgent, navigatorHandle)29 t.true(text.includes('Mozilla'))30 }31)32test.serial(33 'Page.evaluateHandle should accept object handle to primitive types',34 async t => {35 const { page, server } = t.context36 const aHandle = await page.evaluateHandle(() => 5)37 const isFive = await page.evaluate(e => Object.is(e, 5), aHandle)38 t.truthy(isFive)39 }40)41test.serial(42 'Page.evaluateHandle should warn on nested object handles',43 async t => {44 const { page, server } = t.context45 const aHandle = await page.evaluateHandle(() => document.body)46 let error = null47 await page48 .evaluateHandle(opts => opts.elem.querySelector('p'), { elem: aHandle })49 .catch(e => (error = e))50 t.true(error.message.includes('Are you passing a nested JSHandle?'))51 }52)53test.serial(54 'Page.evaluateHandle should accept object handle to unserializable value',55 async t => {56 const { page, server } = t.context57 const aHandle = await page.evaluateHandle(() => Infinity)58 const testResult = await page.evaluate(e => Object.is(e, Infinity), aHandle)59 t.true(testResult)60 }61)62test.serial('Page.evaluateHandle should use the same JS wrappers', async t => {63 const { page, server } = t.context64 const aHandle = await page.evaluateHandle(() => {65 window.FOO = 12366 return window67 })68 const testResult = await page.evaluate(e => e.FOO, aHandle)69 t.is(testResult, 123)70})71test.serial('Page.evaluateHandle should work with primitives', async t => {72 const { page, server } = t.context73 const aHandle = await page.evaluateHandle(() => {74 window.FOO = 12375 return window76 })77 const testResult = await page.evaluate(e => e.FOO, aHandle)78 t.is(testResult, 123)79})80test.serial('JSHandle.getProperty should work', async t => {81 const { page, server } = t.context82 const aHandle = await page.evaluateHandle(() => ({83 one: 1,84 two: 2,85 three: 386 }))87 const twoHandle = await aHandle.getProperty('two')88 const testResult = await twoHandle.jsonValue()89 t.deepEqual(testResult, 2)90})91test.serial('JSHandle.jsonValue should work', async t => {92 const { page, server } = t.context93 const aHandle = await page.evaluateHandle(() => ({ foo: 'bar' }))94 const json = await aHandle.jsonValue()95 t.deepEqual(json, { foo: 'bar' })96})97test.serial('JSHandle.jsonValue should not work with dates', async t => {98 const { page, server } = t.context99 const dateHandle = await page.evaluateHandle(100 () => new Date('2017-09-26T00:00:00.000Z')101 )102 const json = await dateHandle.jsonValue()103 t.deepEqual(json, {})104})105test.serial('JSHandle.jsonValue should throw for circular objects', async t => {106 const { page, server } = t.context107 const windowHandle = await page.evaluateHandle('window')108 let error = null109 await windowHandle.jsonValue().catch(e => (error = e))110 t.true(error.message.includes('Object reference chain is too long'))111})112test.serial('JSHandle.getProperties should work', async t => {113 const { page, server } = t.context114 const aHandle = await page.evaluateHandle(() => ({115 foo: 'bar'116 }))117 const properties = await aHandle.getProperties()118 const foo = properties.get('foo')119 t.truthy(foo)120 const testResult = await foo.jsonValue()121 t.is(testResult, 'bar')122})123test.serial(124 'JSHandle.getProperties should return even non-own properties',125 async t => {126 const { page, server } = t.context127 const aHandle = await page.evaluateHandle(() => {128 class A {129 constructor () {130 this.a = '1'131 }132 }133 class B extends A {134 constructor () {135 super()136 this.b = '2'137 }138 }139 return new B()140 })141 const properties = await aHandle.getProperties()142 const testResult = await properties.get('a').jsonValue()143 t.is(testResult, '1')144 const testResult1 = await properties.get('b').jsonValue()145 t.is(testResult1, '2')146 }147)148test.serial('JSHandle.asElement should work', async t => {149 const { page, server } = t.context150 const aHandle = await page.evaluateHandle(() => document.body)151 const element = aHandle.asElement()152 t.truthy(element)153})154test.serial(155 'JSHandle.asElement should return null for non-elements',156 async t => {157 const { page, server } = t.context158 const aHandle = await page.evaluateHandle(() => 2)159 const element = aHandle.asElement()160 t.falsy(element)161 }162)163test.serial(164 'JSHandle.asElement should return ElementHandle for TextNodes',165 async t => {166 const { page, server } = t.context167 await page.setContent('<div>ee!</div>')168 const aHandle = await page.evaluateHandle(169 () => document.querySelector('div').firstChild170 )171 const element = aHandle.asElement()172 t.truthy(element)173 t.truthy(174 await page.evaluate(e => e.nodeType === HTMLElement.TEXT_NODE, element)175 )176 }177)178test.serial('JSHandle.asElement should work with nullified Node', async t => {179 const { page, server } = t.context180 await page.setContent('<section>test</section>')181 await page.evaluate('() => delete Node')182 const handle = await page.evaluateHandle(() =>183 document.querySelector('section')184 )185 const element = handle.asElement()186 t.truthy(element)187})188test.serial('JSHandle.toString should work for primitives', async t => {189 const { page, server } = t.context190 const numberHandle = await page.evaluateHandle(() => 2)191 t.is(numberHandle.toString(), 'JSHandle:2')192 const stringHandle = await page.evaluateHandle(() => 'a')193 t.is(stringHandle.toString(), 'JSHandle:a')194})195test.serial(196 'JSHandle.toString should work for complicated objects',197 async t => {198 const { page, server } = t.context199 const aHandle = await page.evaluateHandle(() => window)200 t.is(aHandle.toString(), 'JSHandle@Window')201 }202)203test.serial.only(204 'JSHandle.toString should work with different subtypes',205 async t => {206 const { page, server } = t.context207 t.is(208 (await page.evaluateHandle('(function(){})')).toString(),209 'JSHandle@function'210 )211 t.is((await page.evaluateHandle('12')).toString(), 'JSHandle:12')212 t.is((await page.evaluateHandle('true')).toString(), 'JSHandle:true')213 t.is(214 (await page.evaluateHandle('undefined')).toString(),215 'JSHandle:undefined'216 )217 t.is((await page.evaluateHandle('"foo"')).toString(), 'JSHandle:foo')218 t.is((await page.evaluateHandle('Symbol()')).toString(), 'JSHandle@Symbol')219 t.is((await page.evaluateHandle('new Map()')).toString(), 'JSHandle@Map')220 t.is((await page.evaluateHandle('new Set()')).toString(), 'JSHandle@Set')221 t.is((await page.evaluateHandle('[]')).toString(), 'JSHandle@Array')222 t.is((await page.evaluateHandle('null')).toString(), 'JSHandle:null')223 t.is((await page.evaluateHandle('/foo/')).toString(), 'JSHandle@RegExp')224 t.is(225 (await page.evaluateHandle('document.body')).toString(),226 'ElementHandle@HTMLBodyElement'227 )228 t.is((await page.evaluateHandle('new Date()')).toString(), 'JSHandle@Date')229 t.is(230 (await page.evaluateHandle('new WeakMap()')).toString(),231 'JSHandle@WeakMap'232 )233 t.is(234 (await page.evaluateHandle('new WeakSet()')).toString(),235 'JSHandle@WeakSet'236 )237 t.is(238 (await page.evaluateHandle('new Error()')).toString(),239 'JSHandle@Error'240 )241 t.is(242 (await page.evaluateHandle('new Int32Array()')).toString(),243 'JSHandle@Int32Array'244 )245 t.is(246 (await page.evaluateHandle('new Proxy({}, {})')).toString(),247 'JSHandle@Proxy'248 )249 }...
vacuna.js
Source:vacuna.js
...17async function startFill() {18 const page = await configureBrowser();19 await delay(1000);20 21 var enllac = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-error").shadowRoot.querySelector("div > div.subtitle > a")`)).asElement();22 while(enllac == null){23 enllac = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-error").shadowRoot.querySelector("div > div.subtitle > a")`)).asElement();24 }25 enllac.click();26 console.log("Click Enllaç");27 await delay(1000);28 var demanar = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-onboarding").shadowRoot.querySelector("#dismiss-btn").shadowRoot.querySelector("#button")`)).asElement();29 while(demanar == null){30 demanar = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-onboarding").shadowRoot.querySelector("#dismiss-btn").shadowRoot.querySelector("#button")`)).asElement();31 }32 demanar.click();33 console.log("Click Demanar");34 await delay(1000);35 var dniSelect = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#mdc-tab-2").shadowRoot.querySelector("button")`)).asElement();36 while(dniSelect == null){37 dniSelect = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#mdc-tab-2").shadowRoot.querySelector("button")`)).asElement();38 }39 dniSelect.click();40 console.log("Click DNI Select");41 await delay(1000);42 //DNI43 var dniButton = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#documentID").shadowRoot.querySelector("label > input")`)).asElement();44 while(dniButton == null){45 dniButton = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#documentID").shadowRoot.querySelector("label > input")`)).asElement();46 }47 dniButton.click();48 await delay(100);49 await page.keyboard.type(dni);50 51 //Mobil52 const mobilButton = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#phone").shadowRoot.querySelector("label > input")`)).asElement();53 mobilButton.click();54 await delay(100);55 await page.keyboard.type(mobil);56 //Nom57 const nomButton = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#name").shadowRoot.querySelector("label > input")`)).asElement();58 nomButton.click();59 await delay(100);60 await page.keyboard.type(nom);61 //Cognom62 const cognomButton = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#surname").shadowRoot.querySelector("label > input")`)).asElement();63 cognomButton.click();64 await delay(100);65 await page.keyboard.type(cognom1);66 //Cognom267 const cognom2Button = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#surname2").shadowRoot.querySelector("label > input")`)).asElement();68 cognom2Button.click();69 await delay(100);70 await page.keyboard.type(cognom2);71 //Email72 const emailButton = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#mail").shadowRoot.querySelector("label > input")`)).asElement();73 emailButton.click();74 await delay(100);75 await page.keyboard.type(email);76 await delay(500);77 //Acceptar78 const acceptaButton = await (await page.evaluateHandle(`document.querySelector("body > vaccinapp-app").shadowRoot.querySelector("#pages > vaccinapp-shell").shadowRoot.querySelector("#main-shell-content > appointment-shell").shadowRoot.querySelector("#appointment-shell-content > appointment-user-registration").shadowRoot.querySelector("#accept-btn").shadowRoot.querySelector("#button")`)).asElement();79 acceptaButton.click();80 81 await delay(1000000)82}83function delay(time) {84 return new Promise(function(resolve) { 85 setTimeout(resolve, time)86 });87 }...
puppeteer-helper.mjs
Source:puppeteer-helper.mjs
1import {CURRENCY_BLOCKPIT_NAME_MAP, SPECIAL_SEARCH_CURRENCIES} from "./consts.mjs";2export function inputForLabel(page, label) {3 return page.evaluateHandle((lbl) => {4 const dateInput = Array.from(5 document.querySelectorAll('label')6 )7 .find(8 (el) => {9 if (el.innerHTML?.includes(lbl)) {10 return true;11 }12 return el.querySelector('span')?.innerHTML?.includes(lbl);13 });14 if (dateInput) {15 return dateInput.parentElement.querySelector('input');16 }17 return null;18 }, label);19}20export async function clickNewTransactionButton(page) {21 try {22 const newTransactionButton = await page.evaluateHandle(() => {23 const span = Array.from(document.querySelectorAll('span')).find((el) => el.innerHTML?.includes('Neue Transaktion')); // TODO multilingual24 if (span) {25 return span;26 }27 return null;28 });29 if (newTransactionButton) {30 await newTransactionButton.click();31 return true;32 }33 } catch (err) {34 console.error(err);35 }36 await page.reload();37 await page.waitForTimeout(10000);38 return clickNewTransactionButton(page);39}40export async function clickTransactionTypeDropdown(page) {41 try {42 const transactionTypeSelect = await page.evaluateHandle(() => {43 const dateInput = Array.from(44 document.querySelectorAll('label')45 )46 .find(47 (el) => {48 if (el.innerHTML?.includes('Transaktionstyp')) { // TODO multilingual49 return true;50 }51 return el.querySelector('span')?.innerHTML?.includes('Transaktionstyp'); // TODO multilingual52 });53 if (dateInput) {54 return dateInput;55 }56 });57 if (transactionTypeSelect) {58 await transactionTypeSelect.click();59 return true;60 }61 } catch (err) {62 console.error(err);63 }64 await page.reload();65 await page.waitForTimeout(10000);66 return clickNewTransactionButton(page).then(() => clickTransactionTypeDropdown(page));67}68export async function getAndClearDateInput(page) {69 const datumInput = await inputForLabel(page, 'Datum'); // TODO multilingual70 await datumInput.click({clickCount: 3});71 await datumInput.press('Backspace');72 await datumInput.press('Backspace');73 await datumInput.press('Backspace');74 await datumInput.press('Backspace');75 await datumInput.press('Backspace');76 await datumInput.press('Backspace');77 await datumInput.press('Backspace');78 await datumInput.press('Backspace');79 await datumInput.press('Backspace');80 await datumInput.press('Backspace');81 return datumInput;82}83async function importAmountAndCurrency(page, amount, currency) {84 await (await inputForLabel(page, 'Menge')).type(amount); // TODO multilingual85 await (await inputForLabel(page, 'Währung')).type(SPECIAL_SEARCH_CURRENCIES[currency]); // TODO multilingual86}87export async function importStacking(page, preparedTransaction) {88 await importAmountAndCurrency(page, preparedTransaction.toAmount, preparedTransaction.toCurrency);89 const currencySelection = await page.evaluateHandle(90 (currency) => Array.from(91 document.querySelectorAll('span.mat-option-text')92 ).find((el) => el.innerHTML.includes(currency)),93 CURRENCY_BLOCKPIT_NAME_MAP[preparedTransaction.toCurrency]94 );95 if (currencySelection) {96 await currencySelection.click();97 } else {98 console.error('COULD NOT CLICK BUTTON');99 }100}101export async function importExchange(page, preparedTransaction) {102 await (await inputForLabel(page, 'Ausgehende Menge')).type(preparedTransaction.fromAmount); // TODO multilingual103 await (await inputForLabel(page, 'Ausgehende Währung')).type(SPECIAL_SEARCH_CURRENCIES[preparedTransaction.fromCurrency]); // TODO multilingual104 const currencySelection = await page.evaluateHandle(105 (currency) => Array.from(106 document.querySelectorAll('span.mat-option-text')107 ).find((el) => el.innerHTML.includes(currency)),108 CURRENCY_BLOCKPIT_NAME_MAP[preparedTransaction.fromCurrency]109 );110 if (currencySelection) {111 await currencySelection.click();112 } else {113 console.error('COULD NOT CLICK BUTTON');114 }115 await page.waitForTimeout(500);116 await (await inputForLabel(page, 'Eingehende Menge')).type(preparedTransaction.toAmount); // TODO multilingual117 await (await inputForLabel(page, 'Eingehende Währung')).type(SPECIAL_SEARCH_CURRENCIES[preparedTransaction.toCurrency]); // TODO multilingual118 const currencySelection2 = await page.evaluateHandle(119 (currency) => Array.from(120 document.querySelectorAll('span.mat-option-text')121 ).find((el) => el.innerHTML.includes(currency)),122 CURRENCY_BLOCKPIT_NAME_MAP[preparedTransaction.toCurrency]123 );124 if (currencySelection2) {125 await currencySelection2.click();126 } else {127 console.error('COULD NOT CLICK BUTTON');128 }129}130export async function importGift(page, preparedTransaction) {131 await importAmountAndCurrency(page, preparedTransaction.toAmount, preparedTransaction.toCurrency);132 const currencySelection = await page.evaluateHandle(133 (currency) => Array.from(134 document.querySelectorAll('span.mat-option-text')135 ).find((el) => el.innerHTML.includes(currency)),136 CURRENCY_BLOCKPIT_NAME_MAP[preparedTransaction.toCurrency]137 );138 if (currencySelection) {139 await currencySelection.click();140 } else {141 console.error('COULD NOT CLICK BUTTON');142 }143}144export async function importDeposit(page, preparedTransaction) {145 await importAmountAndCurrency(page, preparedTransaction.toAmount, preparedTransaction.toCurrency);146 const currencySelection = await page.evaluateHandle(147 (currency) => Array.from(148 document.querySelectorAll('span.mat-option-text')149 ).find((el) => el.innerHTML.includes(currency)),150 CURRENCY_BLOCKPIT_NAME_MAP[preparedTransaction.toCurrency]151 );152 if (currencySelection) {153 await currencySelection.click();154 } else {155 console.error('COULD NOT CLICK BUTTON');156 }157}158export async function importWithdraw(page, preparedTransaction) {159 await (await inputForLabel(page, 'Menge')).type(preparedTransaction.fromAmount); // TODO multilingual160 await (await inputForLabel(page, 'Währung')).type(SPECIAL_SEARCH_CURRENCIES[preparedTransaction.fromCurrency]); // TODO multilingual161 const currencySelection = await page.evaluateHandle(162 (currency) => Array.from(163 document.querySelectorAll('span.mat-option-text')164 ).find((el) => el.innerHTML.includes(currency)),165 CURRENCY_BLOCKPIT_NAME_MAP[preparedTransaction.fromCurrency]166 );167 if (currencySelection) {168 await currencySelection.click();169 } else {170 console.error('COULD NOT CLICK BUTTON');171 }...
exercise11.unit.test.js
Source:exercise11.unit.test.js
...20 headless: true21 });22 const page = await browser.newPage();23 await page.goto('http://localhost:5500/coreJavaScript/exercise11/exercise11.html');24 const parentsHandle = await page.evaluateHandle(() => {25 const elements = querySelectorAll('div.note < input.is-complete[checked]');26 return elements;27 });28 const parents = await page.evaluate(els => {29 return els.map(e => e.innerHTML)30 }, parentsHandle);31 expect(parents).toEqual(["<input type=\"checkbox\" class=\"is-complete\" checked=\"\"> ",32 "<input type=\"checkbox\" class=\"is-complete\" checked=\"\">",33 "<input type=\"checkbox\" class=\"is-complete\" checked=\"\">"]);34 await browser.close();35})36test('Basic selectors', async () => {37 const browser = await puppeteer.launch({38 headless: true39 });40 const page = await browser.newPage();41 await page.goto('http://localhost:5500/coreJavaScript/exercise11/exercise11.html');42 const divsHandle = await page.evaluateHandle(() => {43 const elements = querySelectorAll('div');44 return elements;45 });46 const divs = await page.evaluate(els => {47 return els.map(e => e.innerHTML.trim())48 }, divsHandle);49 expect(divs).toEqual(["<input type=\"checkbox\" class=\"is-complete\" checked=\"\">",50 "",51 "<input type=\"checkbox\" class=\"is-complete\" checked=\"\">",52 "",53 "<input type=\"checkbox\" class=\"is-complete\" checked=\"\">",54 "<input type=\"checkbox\" class=\"is-complete\">",55 "",56 "",57 "<p><span class=\"B\">selected</span></p>"])58 const originalSectionHandle = await page.evaluateHandle(() => {59 const elements = document.querySelectorAll('section');60 return [...elements];61 });62 const originalSection = await page.evaluate(els => {63 return els.map(e => e.innerHTML.trim())64 }, originalSectionHandle);65 const sectionHandle = await page.evaluateHandle(() => {66 const elements = querySelectorAll('section');67 return elements;68 });69 const section = await page.evaluate(els => {70 return els.map(e => e.innerHTML.trim())71 }, sectionHandle);72 expect(section).toEqual(originalSection)73 const emptyHandle = await page.evaluate(els => {74 const elements = querySelectorAll('');75 return elements;76 })77 const empty = await page.evaluate(els => {78 return els.map(e => e.innerHTML.trim())79 }, emptyHandle);80 expect(empty).toEqual([]);81 const originalOtherHandle = await page.evaluate(els => {82 const elements = querySelectorAll('div.anotherclass');83 return elements;84 })85 const originalOther = await page.evaluate(els => {86 return els.map(e => e.innerHTML)87 }, originalOtherHandle);88 const otherHandle = await page.evaluate(els => {89 const elements = querySelectorAll('div.anotherclass');90 return elements;91 })92 const other = await page.evaluate(els => {93 return els.map(e => e.innerHTML)94 }, otherHandle);95 expect(other).toEqual(originalOther);96 const originalFatherHandle = await page.evaluate(els => {97 const elements = document.querySelectorAll('#A');98 return [...elements];99 })100 const originalFather = await page.evaluate(els => {101 return els.map(e => e.innerHTML)102 }, originalFatherHandle);103 const fatherHandle = await page.evaluate(els => {104 const elements = querySelectorAll('#A < p .B');105 return elements;106 })107 const father = await page.evaluate(els => {108 return els.map(e => e.innerHTML)109 }, fatherHandle);110 expect(father).toEqual(originalFather);111 await browser.close();112})113test('Just direct parents', async () => {114 const browser = await puppeteer.launch({115 headless: true116 });117 const page = await browser.newPage();118 await page.goto('http://localhost:5500/coreJavaScript/exercise11/exercise11.html');119 const parentsHandle = await page.evaluateHandle(() => {120 const elements = querySelectorAll('#A < .B');121 return elements;122 });123 const parents = await page.evaluate(els => {124 return els.map(e => e.innerHTML)125 }, parentsHandle);126 expect(parents).toEqual([]);127 await browser.close();128})129test('No checked', async () => {130 const browser = await puppeteer.launch({131 headless: true132 });133 const page = await browser.newPage();134 await page.goto('http://localhost:5500/coreJavaScript/exercise11/exercise11.html');135 const divsHandle = await page.evaluateHandle(() => {136 const elements = querySelectorAll('div');137 return [...elements];138 });139 const divs = await page.evaluate(els => {140 return els.map(e => e.innerHTML)141 }, divsHandle);142 const parentsHandle = await page.evaluateHandle(() => {143 const elements = querySelectorAll('div.note < input.is-complete');144 return [...elements];145 });146 const parents = await page.evaluate(els => {147 return els.map(e => e.innerHTML)148 }, parentsHandle);149 expect(parents).toEqual([divs[0], divs[2], divs[4], divs[5]]);150 await browser.close();151})152test('No match', async () => {153 const browser = await puppeteer.launch({154 headless: true155 });156 const page = await browser.newPage();157 await page.goto('http://localhost:5500/coreJavaScript/exercise11/exercise11.html');158 const parentsHandle = await page.evaluateHandle(() => {159 const elements = querySelectorAll('div.note < input.anotherclass');160 return elements;161 });162 const parents = await page.evaluate(els => {163 return els.map(e => e.innerHTML)164 }, parentsHandle);165 expect(parents).toEqual([]);166 await browser.close();...
index.js
Source:index.js
...11{12 await checkJq(this);13 return await this.evaluate_old(pageFunction, ...args);14}15async function evaluateHandle(pageFunction, ...args)16{17 await checkJq(this);18 return await this.evaluateHandle_old(pageFunction, ...args);19}20async function waitForFunction(pageFunction, options = {}, ...args)21{22 await checkJq(this);23 return await this.waitForFunction_old(pageFunction, options, ...args);24}25async function getHandle(page, code)26{27 handle = await page.evaluateHandle(code);28 const array = [];29 const properties = await handle.getProperties();30 const context = properties.get('context');31 for (const property of properties.values())32 {33 if (property === context)34 continue;35 const elementHandle = property.asElement();36 if (elementHandle)37 array.push(elementHandle);38 }39 await handle.dispose();40 return array;41}42async function waitForjQuery(selector, options)43{44 const code = `$('${selector.replace(/'/g, "\\\'")}')`;45 let list;46 list = await getHandle(this, code);47 if (list.length)48 return list;49 await this.waitForFunction(code + `.toArray().length > 0`, options, code);50 list = await getHandle(this, code);51 return list;52}53function isString(obj)54{55 return typeof obj === 'string' || obj instanceof String;56}57const handlerRoot = {58 get(target, p, receiver)59 {60 if (typeof p == 'symbol')61 return target[p];62 let key = p.toString();63 switch (key)64 {65 case 'toString':66 case 'valueOf':67 case 'code':68 case 'selector':69 case 'page':70 return target[p];71 case 'then':72 return (...args) => {73 const lastExec = target.exec(true);74 return lastExec.then(...args);75 };76 case 'exec':77 return (...args) => {78 return target.exec(true);79 };80 case 'length':81 target.code += '.length';82 return target.exec(false);83 }84 return (...args) =>85 {86 args = args.map((arg) =>87 {88 if (isString(arg))89 return JSON.stringify(arg);90 if (typeof arg === 'function')91 return arg.toString();92 return JSON.stringify(arg);93 });94 let newCode = `${target.code}.${key}(${args.join(',')})`;95 if (args.length === 0)96 {97 switch (key)98 {99 case 'text':100 case 'html':101 case 'val':102 case 'css':103 const tmp = new JqApi(target.page, target.selector, newCode);104 return tmp.exec(false);105 }106 }107 let child = new JqApi(target.page, target.selector, newCode);108 return new Proxy(child, handlerRoot);109 }110 }111}112class JqApi113{114 constructor(page, selector, code)115 {116 this.page = page;117 this.selector = selector;118 this.code = code;119 }120 async exec(is_selector)121 {122 const code = `$('${this.selector.replace(/'/g, "\\\'")}')` + this.code;123 if (is_selector)124 {125 const handle = await this.page.evaluateHandle(code);126 const json = await handle.jsonValue();127 const is_handle = (json.context !== undefined);128 if (is_handle)129 return getHandle(this.page, code);130 else131 return await this.page.evaluate(code);132 }133 else134 return await this.page.evaluate(code);135 }136}137function inject(page)138{139 if (jQueryData == '')...
appPageProduct.js
Source:appPageProduct.js
...35async function scrapeProduct(url) {36 const browser = await puppeteer.launch({ headless: false });37 const page = await browser.newPage();38 await page.goto(url);39 const aHandleName = await page.evaluateHandle(() => document.body.querySelector('.title-product'));40 const resultHandleName = await page.evaluateHandle(body => body.innerHTML, aHandleName);41 const name = await resultHandleName.jsonValue();42 await resultHandleName.dispose();43 const aHandleCod = await page.evaluateHandle(() => document.body.querySelector('.sku'));44 const resultHandleCod = await page.evaluateHandle(body => body.innerHTML, aHandleCod);45 const code = await resultHandleCod.jsonValue();46 await resultHandleCod.dispose();47 const aHandlePrice = await page.evaluateHandle(() => document.body.querySelector('.priceBig'));48 const resultHandlePrice = await page.evaluateHandle(body => body.innerHTML, aHandlePrice);49 const price = await resultHandlePrice.jsonValue();50 await resultHandlePrice.dispose();51 // const aHandleImg = await page.evaluateHandle(() => document.body.querySelector('div.col-sm-4.foto'));52 // const resultHandleImg = await page.evaluateHandle(body => body.innerHTML, aHandleImg);53 // const Img = await resultHandleImg.jsonValue();54 // console.log('Img_URL:', String(Img).split('"')[1]);55 // await resultHandleImg.dispose();56 await browser.close();57 return {58 name: String(name).trim(),59 code: String(code).trim().split('.')[1],60 price: String(price).trim(),61 };62}63const url = [64 `https://www.paodeacucar.com/produto/431613/vinho-italiano-tinto-elio-grasso-barolo-ginestra-vigna-casa-mate-garrafa-750ml`,65 `https://www.paodeacucar.com/produto/431345/vinho-alemao-branco-schloss-johannisberg-er-riersling-trocken-garrafa-750ml`,66]...
targetMethods.js
Source:targetMethods.js
...25 * @param {string} attr26 * @returns {Promise<string>}27 */28 getAttr: async function( attr ){29 const handle = await page.evaluateHandle( ( el, attr ) => el.getAttribute( attr ), elementHandle, attr );30 return await handle.jsonValue();31 },32 /**33 * Does element have attribute34 * @param {string} attr35 * @returns {Promise<string>}36 */37 hasAttr: async function( attr ){38 const handle = await page.evaluateHandle( ( el, attr ) => el.hasAttribute( attr ), elementHandle, attr );39 return await handle.jsonValue();40 },41 /**42 * Check if element is visible in the DOM43 * @returns {Promise<Object>}44 **/45 isVisible: async function(){46 if ( elementHandle === false ) {47 return {48 isAvailable: false49 };50 }51 try {52 const isIntersectingViewport = await elementHandle.isIntersectingViewport(),53 handleOpacity = await page.evaluateHandle( ( el ) =>54 window.getComputedStyle( el, null ).getPropertyValue( "opacity" ), elementHandle ),55 handleVisibility = await page.evaluateHandle( ( el ) =>56 window.getComputedStyle( el, null ).getPropertyValue( "visibility" ), elementHandle ),57 handleDisplay = await page.evaluateHandle( ( el ) =>58 window.getComputedStyle( el, null ).getPropertyValue( "display" ), elementHandle ),59 opacity = parseFloat( await handleOpacity.jsonValue() ),60 visibility = await handleVisibility.jsonValue(),61 display = await handleDisplay.jsonValue();62 return {63 isAvailable: true,64 display,65 visibility,66 opacity,67 isIntersecting: isIntersectingViewport68 };69 } catch( e ) {70 // Chaining in iFrame/ShadowDOM71 // JSHandles can be evaluated only in the context they were created!72 return {73 isAvailable: elementHandle !== false74 };75 }76 },77 /**78 * Set value on a select element79 * @param {string} value80 * @returns {Promise<Undefined>}81 */82 select: async function( value ) {83 await page.evaluateHandle( ( el, value ) => {84 const event = new Event( "change", { bubbles: true });85 event.simulated = true;86 el.querySelector( `option[value="${ value }"]` ).selected = true;87 el.dispatchEvent( event );88 }, elementHandle, value );89 }90 };91 };...
Using AI Code Generation
1const puppeteer = require('puppeteer');2const devices = require('puppeteer/DeviceDescriptors');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 await page.emulate(devices['iPhone 6']);7 await page.screenshot({path: 'google.png'});8 await browser.close();9})();10const puppeteer = require('puppeteer');11const devices = require('puppeteer/DeviceDescriptors');12(async () => {13 const browser = await puppeteer.launch();14 const page = await browser.newPage();15 await page.emulate(devices['iPhone 6']);16 await page.screenshot({path: 'google.png'});17 await browser.close();18})();19const puppeteer = require('puppeteer');20const devices = require('puppeteer/DeviceDescriptors');21(async () => {22 const browser = await puppeteer.launch();23 const page = await browser.newPage();24 await page.emulate(devices['iPhone 6']);25 await page.screenshot({path: 'google.png'});26 await browser.close();27})();28const puppeteer = require('puppeteer');29const devices = require('puppeteer/DeviceDescriptors');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.emulate(devices['iPhone 6']);34 await page.screenshot({path: 'google.png'});35 await browser.close();36})();37const puppeteer = require('puppeteer');38const devices = require('puppeteer/DeviceDescriptors');39(async () => {40 const browser = await puppeteer.launch();41 const page = await browser.newPage();42 await page.emulate(devices['iPhone 6']);43 await page.screenshot({path: 'google.png'});44 await browser.close();45})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const dimensions = await page.evaluateHandle(() => {6 return {7 };8 });9 console.log(dimensions);10 await browser.close();11})();12JSHandle {13 CDPSession {14 _events: [Object: null prototype] {},15 _callbacks: Map {},16 _callbackId: 0 },17 { type: 'object',18 objectId: '{"injectedScriptId":1,"id":1}' } }
Using AI Code Generation
1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 const dimensions = await page.evaluateHandle(() => {5 return {6 };7 });8 console.log('Dimensions:', dimensions);9 await browser.close();10})();11(async () => {12 const browser = await puppeteer.launch();13 const page = await browser.newPage();14 const dimensions = await page.evaluateHandle(() => {15 return {16 };17 });18 console.log('Dimensions:', dimensions);19 await browser.close();20})();21(async () => {22 const browser = await puppeteer.launch();23 const page = await browser.newPage();24 const dimensions = await page.evaluate(() => {25 return {26 };27 });28 console.log('Dimensions:', dimensions);29 await browser.close();30})();31(async () => {32 const browser = await puppeteer.launch();33 const page = await browser.newPage();34 const dimensions = await page.evaluate(() => {35 return {36 };37 });38 console.log('Dimensions:', dimensions);39 await browser.close();40})();
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!!