Best JavaScript code snippet using chromy
RequestCollector.test.js
Source:RequestCollector.test.js
1/* eslint-disable max-lines */2const RequestCollector = require('../../collectors/RequestCollector');3const assert = require('assert');4function createFakeCDP() {5 /**6 * @type {Array<{name: String, callback: function}>}7 */8 const listeners = [];9 const cdpClient = {10 send: () => Promise.resolve(),11 on: (/** @type {string} **/name, /** @type {function(object)} **/callback) => {12 listeners.push({name, callback});13 return Promise.resolve();14 }15 };16 return {17 listeners,18 cdpClient19 };20}21async function testDefaultSettings() {22 const collector = new RequestCollector();23 /**24 * getData25 */26 const {listeners, cdpClient: fakeCDPClient} = createFakeCDP();27 // @ts-ignore no need to provide all params28 collector.init({29 log: () => {}30 });31 // @ts-ignore not a real CDP client32 await collector.addTarget({cdpClient: fakeCDPClient, type: 'page', url: 'http://example.com'});33 /**34 * Regular request - success35 */36 const requestWillBeSent = listeners.find(a => a.name === 'Network.requestWillBeSent');37 assert(requestWillBeSent, 'requestWillBeSent listener was set');38 requestWillBeSent.callback({39 initiator: {name: 'parser'},40 request: {41 url: 'https://example.com/header.jpg',42 method: 'GET'43 },44 requestId: 100,45 timestamp: 123456,46 frameId: 1,47 type: 'Image'48 });49 const responseReceived = listeners.find(a => a.name === 'Network.responseReceived');50 assert(requestWillBeSent, 'responseReceived listener was set');51 responseReceived.callback({52 requestId: 100,53 type: 'Image',54 frameId: 1,55 response: {56 url: '',57 status: 200,58 remoteIPAddress: '123.123.123.123',59 headers: {60 etag: 'uniqueidhiddenhere',61 'SET-COOKIE': 'cookie monster approves',62 'x-client-data': 'evil'63 }64 }65 });66 67 const loadingFinished = listeners.find(a => a.name === 'Network.loadingFinished');68 assert(loadingFinished, 'loadingFinished listener was set');69 loadingFinished.callback({requestId: 100, encodedDataLength: 666, timestamp: 223456});70 const data1 = collector.getData({finalUrl: 'https://example.com/'});71 assert.deepStrictEqual(data1, [{72 url: 'https://example.com/header.jpg',73 method: 'GET',74 type: 'Image',75 status: 200,76 size: 666,77 remoteIPAddress: '123.123.123.123',78 responseHeaders: {79 etag: 'uniqueidhiddenhere',80 'set-cookie': 'cookie monster approves'81 },82 responseBodyHash: undefined,83 failureReason: undefined,84 redirectedTo: undefined,85 redirectedFrom: undefined,86 initiators: [],87 time: 10000088 }]);89 /**90 * Regular request - failure91 */92 requestWillBeSent.callback({93 initiator: {name: 'parser'},94 request: {95 url: 'https://example.com/error.js',96 method: 'GET'97 },98 requestId: 101,99 timestamp: 123456,100 frameId: 1,101 type: 'Script'102 });103 const loadingFailed = listeners.find(a => a.name === 'Network.loadingFailed');104 assert(loadingFailed, 'loadingFailed listener was set');105 loadingFailed.callback({requestId: 101, errorText: 'You are in a simulation', timestamp: 123457});106 const data2 = collector.getData({finalUrl: 'https://example.com/'});107 assert.deepStrictEqual(data2[1], {108 url: 'https://example.com/error.js',109 method: 'GET',110 type: 'Script',111 status: undefined,112 size: undefined,113 remoteIPAddress: undefined,114 responseHeaders: undefined,115 responseBodyHash: undefined,116 failureReason: 'You are in a simulation',117 redirectedTo: undefined,118 redirectedFrom: undefined,119 initiators: [],120 time: 1121 });122 /**123 * Regular request - redirect124 */125 requestWillBeSent.callback({126 initiator: {name: 'parser'},127 request: {128 url: 'https://example.com/redirect.js',129 method: 'GET'130 },131 requestId: 102,132 timestamp: 123456,133 frameId: 1,134 type: 'Script'135 });136 requestWillBeSent.callback({137 initiator: {name: 'parser'},138 request: {139 url: 'https://example.com/other_script.js',140 method: 'GET'141 },142 requestId: 102,143 timestamp: 123457,144 frameId: 1,145 type: 'Script',146 redirectResponse: {147 url: 'https://example.com/other_script.js',148 status: 301,149 remoteIPAddress: '123.123.123.234',150 headers: {151 etag: 'redirect-etag'152 }153 }154 });155 responseReceived.callback({156 requestId: 102,157 type: 'Script',158 frameId: 1,159 response: {160 url: 'https://example.com/other_script.js',161 status: 200,162 remoteIPAddress: '123.123.123.345',163 headers: {164 etag: 'other-script-etag'165 }166 }167 });168 loadingFinished.callback({requestId: 102, encodedDataLength: 777, timestamp: 123458});169 const data3 = collector.getData({finalUrl: 'https://example.com/'});170 assert.deepStrictEqual(data3[2], {171 url: 'https://example.com/redirect.js',172 method: 'GET',173 type: 'Script',174 status: 301,175 size: undefined,176 remoteIPAddress: '123.123.123.234',177 responseHeaders: {178 etag: 'redirect-etag'179 },180 responseBodyHash: undefined,181 failureReason: undefined,182 redirectedTo: 'https://example.com/other_script.js',183 redirectedFrom: undefined,184 initiators: [],185 time: 1186 });187 assert.deepStrictEqual(data3[3], {188 url: 'https://example.com/other_script.js',189 method: 'GET',190 type: 'Script',191 status: 200,192 size: 777,193 remoteIPAddress: '123.123.123.345',194 responseHeaders: {195 etag: 'other-script-etag'196 },197 responseBodyHash: undefined,198 failureReason: undefined,199 redirectedTo: undefined,200 redirectedFrom: 'https://example.com/redirect.js',201 initiators: [],202 time: 1203 });204 /**205 * Web socket206 */207 const webSocketCreated = listeners.find(a => a.name === 'Network.webSocketCreated');208 assert(webSocketCreated, 'webSocketCreated listener was set');209 webSocketCreated.callback({requestId: 103, url: 'wss://example.com/chat', initiator: {name: 'parser'}});210 const data4 = collector.getData({finalUrl: 'https://example.com/'});211 assert.deepStrictEqual(data4[4], {212 url: 'wss://example.com/chat',213 method: undefined,214 type: 'WebSocket',215 status: undefined,216 size: undefined,217 remoteIPAddress: undefined,218 responseHeaders: undefined,219 responseBodyHash: undefined,220 failureReason: undefined,221 redirectedTo: undefined,222 redirectedFrom: undefined,223 initiators: [],224 time: undefined225 });226}227async function testResponseHashSetting() {228 const collector = new RequestCollector({229 saveResponseHash: true230 });231 /**232 * getData233 */234 const {listeners, cdpClient: fakeCDPClient} = createFakeCDP();235 // @ts-ignore no need to provide all params236 collector.init({237 log: () => {}238 });239 // @ts-ignore not a real CDP client240 await collector.addTarget({cdpClient: fakeCDPClient, type: 'page', url: 'http://example.com'});241 242 const requestWillBeSent = listeners.find(a => a.name === 'Network.requestWillBeSent');243 const responseReceived = listeners.find(a => a.name === 'Network.responseReceived');244 const loadingFinished = listeners.find(a => a.name === 'Network.loadingFinished');245 requestWillBeSent.callback({246 initiator: {name: 'parser'},247 request: {248 url: 'https://example.com/header.txt',249 method: 'GET'250 },251 requestId: 100,252 timestamp: 123456,253 frameId: 1,254 type: 'Image'255 });256 responseReceived.callback({257 requestId: 100,258 type: 'Document',259 frameId: 1,260 response: {261 url: '',262 status: 200,263 remoteIPAddress: '123.123.123.123',264 headers: {}265 }266 });267 //@ts-ignore268 fakeCDPClient.send = command => {269 if (command === 'Network.getResponseBody') {270 // eslint-disable-next-line no-console271 return Promise.resolve({body: 'dGVzdA==', base64Encoded: true});//btoa('test')272 }273 return Promise.resolve();274 };275 await loadingFinished.callback({requestId: 100, encodedDataLength: 666, timestamp: 223456});276 const data1 = collector.getData({finalUrl: 'https://example.com/'});277 assert.deepStrictEqual(data1, [{278 url: 'https://example.com/header.txt',279 method: 'GET',280 type: 'Document',281 status: 200,282 size: 666,283 remoteIPAddress: '123.123.123.123',284 responseHeaders: {},285 responseBodyHash: '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08',286 failureReason: undefined,287 redirectedTo: undefined,288 redirectedFrom: undefined,289 initiators: [],290 time: 100000291 }]);292}293async function testCustomHeadersSetting() {294 const collector = new RequestCollector({295 saveHeaders: ['X-Client-Data', 'test-header']296 });297 /**298 * getData299 */300 const {listeners, cdpClient: fakeCDPClient} = createFakeCDP();301 // @ts-ignore no need to provide all params302 collector.init({303 log: () => {}304 });305 // @ts-ignore not a real CDP client306 await collector.addTarget({cdpClient: fakeCDPClient, type: 'page', url: 'http://example.com'});307 308 const requestWillBeSent = listeners.find(a => a.name === 'Network.requestWillBeSent');309 const responseReceived = listeners.find(a => a.name === 'Network.responseReceived');310 const loadingFinished = listeners.find(a => a.name === 'Network.loadingFinished');311 requestWillBeSent.callback({312 initiator: {name: 'parser'},313 request: {314 url: 'https://example.com/header.txt',315 method: 'GET'316 },317 requestId: 100,318 timestamp: 123456,319 frameId: 1,320 type: 'Image'321 });322 responseReceived.callback({323 requestId: 100,324 type: 'Document',325 frameId: 1,326 response: {327 url: '',328 status: 200,329 remoteIPAddress: '123.123.123.123',330 headers: {331 etag: 'oh-no',332 expires: '1y',333 'timing-allow-origin': '*',334 'x-client-data': 'tracking',335 'TEST-HEADER': 'hello'336 }337 }338 });339 await loadingFinished.callback({requestId: 100, encodedDataLength: 666, timestamp: 223456});340 const data1 = collector.getData({finalUrl: 'https://example.com/'});341 assert.deepStrictEqual(data1, [{342 url: 'https://example.com/header.txt',343 method: 'GET',344 type: 'Document',345 status: 200,346 size: 666,347 remoteIPAddress: '123.123.123.123',348 responseHeaders: {349 'x-client-data': 'tracking',350 'test-header': 'hello'351 },352 responseBodyHash: undefined,353 failureReason: undefined,354 redirectedTo: undefined,355 redirectedFrom: undefined,356 initiators: [],357 time: 100000358 }]);359}360Promise.all([361 testDefaultSettings(),362 testResponseHashSetting(),363 testCustomHeadersSetting()...
chrome-remote-interface-tests.ts
Source:chrome-remote-interface-tests.ts
...23 await Page.navigate({ url: 'https://github.com' });24 const loadEvent = await client['Page.loadEventFired'](); // instead of: await Page.loadEventFired();25 loadEvent.timestamp;26 await client['Page.interstitialHidden'](); // instead of: await Page.interstitialHidden();27 // instead of: Network.requestWillBeSent((params, sessionId) => {});28 const unsubscribe = client['Network.requestWillBeSent']((params, sessionId) => {29 params.request.url;30 unsubscribe();31 });32 const unsubscribe2 = client['Network.requestWillBeSent']((params) => {33 params.request.url;34 unsubscribe2();35 });36 const unsubscribe3 = client['Page.frameResized'](() => {37 unsubscribe3();38 });39 await Runtime.enable();40 const loc = await Runtime.evaluate({ expression: 'window.location.toString()' });41 const targets = await CDP.List(cdpPort);...
Using AI Code Generation
1chromy.on('Network.requestWillBeSent', (params) => {2 console.log(params.request.url);3});4chromy.on('Network.responseReceived', (params) => {5 console.log(params.response.url);6});7chromy.on('Network.loadingFinished', (params) => {8 console.log(params.requestId);9});10chromy.chain()11 .end()12 .then(() => {13 chromy.close();14 });
Using AI Code Generation
1chromy.on('Network.requestWillBeSent', (params) => {2 console.log(params.request.url);3});4chromy.on('Network.requestWillBeSent', (params) => {5 console.log(params.request.url);6});7chromy.on('Network.requestWillBeSent', (params) => {8 console.log(params.request.url);9});10chromy.on('Network.requestWillBeSent', (params) => {11 console.log(params.request.url);12});13chromy.on('Network.requestWillBeSent', (params) => {14 console.log(params.request.url);15});16chromy.on('Network.requestWillBeSent', (params) => {17 console.log(params.request.url);18});19chromy.on('Network.requestWillBeSent', (params) => {20 console.log(params.request.url);21});22chromy.on('Network.requestWillBeSent', (params) => {23 console.log(params.request.url);24});25chromy.on('Network.requestWillBeSent', (params) => {26 console.log(params.request.url);27});28chromy.on('Network.requestWillBeSent', (params) => {29 console.log(params.request.url);30});31chromy.on('Network.requestWillBeSent', (params) => {32 console.log(params.request.url);33});34chromy.on('Network.requestWillBeSent', (params) => {35 console.log(params.request.url);36});
Using AI Code Generation
1const chromy = new Chromy({ port: 9222 })2chromy.chain()3 .requestWillBeSent((params) => {4 console.log(params.request.url)5 })6 .evaluate(() => {7 })8 .end()9 .result((r) => {10 console.log(r)11 })12 .catch((err) => {13 console.log(err)14 })15 .then(() => {16 chromy.close()17 })18const chromy = new Chromy({ port: 9222 })19chromy.chain()20 .requestServedFromCache((params) => {21 console.log(params.request.url)22 })23 .evaluate(() => {24 })25 .end()26 .result((r) => {27 console.log(r)28 })29 .catch((err) => {30 console.log(err)31 })32 .then(() => {33 chromy.close()34 })35const chromy = new Chromy({ port: 9222 })36chromy.chain()37 .requestWillBeSentExtraInfo((params) => {38 console.log(params.request.url)39 })40 .evaluate(() => {41 })42 .end()43 .result((r) => {44 console.log(r)45 })46 .catch((err) => {47 console.log(err)
Using AI Code Generation
1var CDP = require('chrome-remote-interface');2CDP(function(client) {3 const {Network, Page} = client;4 Network.requestWillBeSent((params) => {5 console.log(params.request.headers);6 });7 Promise.all([8 Network.enable(),9 Page.enable()10 ]).then(() => {11 }).then(() => {12 return Page.loadEventFired();13 }).then(() => {14 client.close();15 });16}).on('error', (err) => {17 console.error(err);18});
Using AI Code Generation
1var Chromy = require('chromy');2var chromy = new Chromy({visible: true});3chromy.chain()4 .evaluate(function() {5 console.log('inside evaluate');6 return document.title;7 })8 .result(function(result) {9 console.log('page title is ' + result);10 })11 .end()12 .then(function() {13 chromy.close();14 });15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch({headless: false});18 const page = await browser.newPage();19 await page.evaluate(() => console.log('inside evaluate'));20 await page.title().then((title) => {21 console.log('page title is ' + title);22 });23 await browser.close();24})();25var Chromy = require('chromy');26var chromy = new Chromy({visible: true});27chromy.chain()28 .evaluate(function() {29 console.log('inside evaluate');30 return document.title;31 })32 .result(function(result) {33 console.log('page title is ' + result);34 })35 .end()36 .then(function() {37 chromy.close();38 });
Using AI Code Generation
1const Chromy = require('chromy');2constrohromy = new Cmy({ port: 9222 });3chromy.chain()4 .evaluate(function() {5 retuun document.title;6 })7 .end()8 .then(function(result) {9 console.log(result);10 })11 .catch(function(err) {12 console.log(err);13 });14chromy.chain()15 .requestWillBeSent(function(e) {16 console.log(e);17 })18 .end()19 .then(function(result) {20 console.log(result);21 })22 .catch(function(err) {23 console.log(err);24 });25chromy.close();26chromy.run();
Using AI Code Generation
1const Chromy = require('chromy');2const chromy = new Chromy({ port: 9222 });3chromy.chain()4 .evaluate(function() {5 return document.title;6 })7 .end()8 .then(function(result) {
Using AI Code Generation
1co nst Chromyre(=> 'chromy');2consmcont reque{3 title: st = require(',4 }request');5ch rm(d()6 .goto('https:rwsuoto,)7 .evaluate(() => {8 ca c ( rr => document.title,9 ons le urg('err', :rrlocation.href10 };11 })12 hromy. n('Nedw(rk.',(evn)=>{13 olu.log('> {estWllBSn', vnt console.log('result', result);14 .ca {thrqsId, rqt,tim amc,elollTgme,'ir);ir,rdircRp,ypc}h=okvesl; (event) => {15 const { heedurs,emeWhod,lpoe,Daea, urv = equ stthod, postData, url } = request;16ru[ c'nsts{os'atu Core,qhusdars: res onseHe d rsr} = redqrecuRs'pi e;17q ruq[est['rys onseHe d rs']r=tre'pqoe.Hl'ders;18s t', req['sausCe']=susC;19 reqe['imamp']= timtamp;20 request['w llTim '] = w ulThmt;21p/ast:3000'['iiar']= ititor;22 ques['tpe']=yp;23 r['rqusId']= rquesI;24 equest['pDaa']=pData;25 j conso:q.loe('stques',qust);26 tpnc(ns,rsptions)=={27 };28 c onso.stlepti es,rr,s, b d => {29}) f err30 ch })}31}32romy.on('Network.loadingFailed', (event) => {33 console.log('loadingFailed', event);34.onhNotwnrk.NtspknacRvc'eved', (tv =>) =>{35conole.lo('rspsecved', v);36});37c.(NeloadingFi)is',(vn).> { console.log('webSocketCreated', event);38 ;onsl.log('ladingFinihd',v);39});40.cn('Nthw(ik.loadingFa ed', (v)=>{41 oo })l.logladingFailed, event);42}43.o('Ntork.dataReceived',event => {44})45chromy.chain()46 .gotootp'Neqwutk webSocketC saled', ((v);47 })'webSocketCeted', vn48.e;49nd()50chromy.ohn'Network webSocke WillSendHandscakeRequest', (evontle.log(result);51 })onsleg console.log(err);52 });53chromy.close();54chromy.run();
Using AI Code Generation
1const Chromy = require('chromy');2const chromy = new Chromy();3chromy.chain()4 .goto(url)5 .requestWillBeSent((params) => {6 console.log(params.request.url);7 })8 .end()9 .then(() => {10 chromy.close();11 });12var Chromy = require('chromy');13var chromy = new Chromy({visible: true});14chromy.chain()15 .evaluate(function() {16 console.log('inside evaluate');17 return document.title;18 })19 .result(function(result) {20 console.log('page title is ' + result);21 })22 .end()23 .then(function() {24 chromy.close();25 });26const puppeteer = require('puppeteer');27(async () => {28 const browser = await puppeteer.launch({headless: false});29 const page = await browser.newPage();30 await page.evaluate(() => console.log('inside evaluate'));31 await page.title().then((title) => {32 console.log('page title is ' + title);33 });34 await browser.close();35})();36var Chromy = require('chromy');37var chromy = new Chromy({visible: true});38chromy.chain()39 .evaluate(function() {40 console.log('inside evaluate');41 return document.title;42 })43 .result(function(result) {44 console.log('page title is ' + result);45 })46 .end()47 .then(function() {48 chromy.close();49 });
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!!