Best JavaScript code snippet using navalia
HARImporter.js
Source:HARImporter.js
1// Copyright 2017 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4import * as Common from '../common/common.js';5import * as SDK from '../sdk/sdk.js';6import {HAREntry, HARLog, HARPage, HARTimings} from './HARFormat.js'; // eslint-disable-line no-unused-vars7export class Importer {8 /**9 * @param {!HARLog} log10 * @return {!Array<!SDK.NetworkRequest.NetworkRequest>}11 */12 static requestsFromHARLog(log) {13 /** @type {!Map<string, !HARPage>} */14 const pages = new Map();15 for (const page of log.pages) {16 pages.set(page.id, page);17 }18 log.entries.sort((a, b) => a.startedDateTime - b.startedDateTime);19 /** @type {!Map<string, !SDK.NetworkLog.PageLoad>} */20 const pageLoads = new Map();21 /** @type {!Array<!SDK.NetworkRequest.NetworkRequest>} */22 const requests = [];23 for (const entry of log.entries) {24 let pageLoad = pageLoads.get(entry.pageref);25 const documentURL = pageLoad ? pageLoad.mainRequest.url() : entry.request.url;26 let initiator = null;27 if (entry._initiator) {28 initiator = {29 type: entry._initiator.type,30 url: entry._initiator.url,31 lineNumber: entry._initiator.lineNumber32 };33 }34 const request = new SDK.NetworkRequest.NetworkRequest(35 'har-' + requests.length, entry.request.url, documentURL, '', '', initiator);36 const page = pages.get(entry.pageref);37 if (!pageLoad && page) {38 pageLoad = Importer._buildPageLoad(page, request);39 pageLoads.set(entry.pageref, pageLoad);40 }41 Importer._fillRequestFromHAREntry(request, entry, pageLoad);42 if (pageLoad) {43 pageLoad.bindRequest(request);44 }45 requests.push(request);46 }47 return requests;48 }49 /**50 * @param {!HARPage} page51 * @param {!SDK.NetworkRequest.NetworkRequest} mainRequest52 * @return {!SDK.NetworkLog.PageLoad}53 */54 static _buildPageLoad(page, mainRequest) {55 const pageLoad = new SDK.NetworkLog.PageLoad(mainRequest);56 pageLoad.startTime = page.startedDateTime;57 pageLoad.contentLoadTime = page.pageTimings.onContentLoad * 1000;58 pageLoad.loadTime = page.pageTimings.onLoad * 1000;59 return pageLoad;60 }61 /**62 * @param {!SDK.NetworkRequest.NetworkRequest} request63 * @param {!HAREntry} entry64 * @param {?SDK.NetworkLog.PageLoad} pageLoad65 */66 static _fillRequestFromHAREntry(request, entry, pageLoad) {67 // Request data.68 if (entry.request.postData) {69 request.setRequestFormData(true, entry.request.postData.text);70 } else {71 request.setRequestFormData(false, null);72 }73 request.connectionId = entry.connection || '';74 request.requestMethod = entry.request.method;75 request.setRequestHeaders(entry.request.headers);76 // Response data.77 if (entry.response.content.mimeType && entry.response.content.mimeType !== 'x-unknown') {78 request.mimeType = entry.response.content.mimeType;79 }80 request.responseHeaders = entry.response.headers;81 request.statusCode = entry.response.status;82 request.statusText = entry.response.statusText;83 let protocol = entry.response.httpVersion.toLowerCase();84 if (protocol === 'http/2.0') {85 protocol = 'h2';86 }87 request.protocol = protocol.replace(/^http\/2\.0?\+quic/, 'http/2+quic');88 // Timing data.89 const issueTime = entry.startedDateTime.getTime() / 1000;90 request.setIssueTime(issueTime, issueTime);91 // Content data.92 const contentSize = entry.response.content.size > 0 ? entry.response.content.size : 0;93 const headersSize = entry.response.headersSize > 0 ? entry.response.headersSize : 0;94 const bodySize = entry.response.bodySize > 0 ? entry.response.bodySize : 0;95 request.resourceSize = contentSize || (headersSize + bodySize);96 let transferSize = entry.response.customAsNumber('transferSize');97 if (transferSize === undefined) {98 transferSize = entry.response.headersSize + entry.response.bodySize;99 }100 request.setTransferSize(transferSize >= 0 ? transferSize : 0);101 const fromCache = entry.customAsString('fromCache');102 if (fromCache === 'memory') {103 request.setFromMemoryCache();104 } else if (fromCache === 'disk') {105 request.setFromDiskCache();106 }107 const contentData = {error: null, content: null, encoded: entry.response.content.encoding === 'base64'};108 if (entry.response.content.text !== undefined) {109 contentData.content = entry.response.content.text;110 }111 request.setContentDataProvider(async () => contentData);112 // Timing data.113 Importer._setupTiming(request, issueTime, entry.time, entry.timings);114 // Meta data.115 request.setRemoteAddress(entry.serverIPAddress || '', 80); // Har does not support port numbers.116 request.setResourceType(Importer._getResourceType(request, entry, pageLoad));117 const priority = entry.customAsString('priority');118 if (Protocol.Network.ResourcePriority.hasOwnProperty(priority)) {119 request.setPriority(/** @type {!Protocol.Network.ResourcePriority} */ (priority));120 }121 const messages = entry.customAsArray('webSocketMessages');122 if (messages) {123 for (const message of messages) {124 if (message.time === undefined) {125 continue;126 }127 if (!Object.values(SDK.NetworkRequest.WebSocketFrameType).includes(message.type)) {128 continue;129 }130 if (message.opcode === undefined) {131 continue;132 }133 if (message.data === undefined) {134 continue;135 }136 const mask = message.type === SDK.NetworkRequest.WebSocketFrameType.Send;137 request.addFrame(138 {time: message.time, text: message.data, opCode: message.opcode, mask: mask, type: message.type});139 }140 }141 request.finished = true;142 }143 /**144 * @param {!SDK.NetworkRequest.NetworkRequest} request145 * @param {!HAREntry} entry146 * @param {?SDK.NetworkLog.PageLoad} pageLoad147 * @return {!Common.ResourceType.ResourceType}148 */149 static _getResourceType(request, entry, pageLoad) {150 const customResourceTypeName = entry.customAsString('resourceType');151 if (customResourceTypeName) {152 const customResourceType = Common.ResourceType.ResourceType.fromName(customResourceTypeName);153 if (customResourceType) {154 return customResourceType;155 }156 }157 if (pageLoad && pageLoad.mainRequest === request) {158 return Common.ResourceType.resourceTypes.Document;159 }160 const resourceTypeFromMime = Common.ResourceType.ResourceType.fromMimeType(entry.response.content.mimeType);161 if (resourceTypeFromMime !== Common.ResourceType.resourceTypes.Other) {162 return resourceTypeFromMime;163 }164 const resourceTypeFromUrl = Common.ResourceType.ResourceType.fromURL(entry.request.url);165 if (resourceTypeFromUrl) {166 return resourceTypeFromUrl;167 }168 return Common.ResourceType.resourceTypes.Other;169 }170 /**171 * @param {!SDK.NetworkRequest.NetworkRequest} request172 * @param {number} issueTime173 * @param {number} entryTotalDuration174 * @param {!HARTimings} timings175 */176 static _setupTiming(request, issueTime, entryTotalDuration, timings) {177 /**178 * @param {number|undefined} timing179 * @return {number}180 */181 function accumulateTime(timing) {182 if (timing === undefined || timing < 0) {183 return -1;184 }185 lastEntry += timing;186 return lastEntry;187 }188 let lastEntry = timings.blocked >= 0 ? timings.blocked : 0;189 const proxy = timings.customAsNumber('blocked_proxy') || -1;190 const queueing = timings.customAsNumber('blocked_queueing') || -1;191 // SSL is part of connect for both HAR and Chrome's format so subtract it here.192 const ssl = timings.ssl >= 0 ? timings.ssl : 0;193 if (timings.connect > 0) {194 timings.connect -= ssl;195 }196 const timing = {197 proxyStart: proxy > 0 ? lastEntry - proxy : -1,198 proxyEnd: proxy > 0 ? lastEntry : -1,199 requestTime: issueTime + (queueing > 0 ? queueing : 0) / 1000,200 dnsStart: timings.dns >= 0 ? lastEntry : -1,201 dnsEnd: accumulateTime(timings.dns),202 // Add ssl to end time without modifying lastEntry (see comment above).203 connectStart: timings.connect >= 0 ? lastEntry : -1,204 connectEnd: accumulateTime(timings.connect) + ssl,205 // Now update lastEntry to add ssl timing back in (see comment above).206 sslStart: timings.ssl >= 0 ? lastEntry : -1,207 sslEnd: accumulateTime(timings.ssl),208 workerStart: -1,209 workerReady: -1,210 sendStart: timings.send >= 0 ? lastEntry : -1,211 sendEnd: accumulateTime(timings.send),212 pushStart: 0,213 pushEnd: 0,214 receiveHeadersEnd: accumulateTime(timings.wait)215 };216 accumulateTime(timings.receive);217 request.timing = timing;218 request.endTime = issueTime + Math.max(entryTotalDuration, lastEntry) / 1000;219 }...
testPageLoadStats.js
Source:testPageLoadStats.js
1/* global window */2'use strict'3var assert = require('assert')4var sinon = require('sinon')5require('./_fakeDom.js')6require('../lib/pageLoadStats.js')7var transport = require('../lib/transport.js')8describe('Testing pageLoadStats', function () {9 before(function () {10 sinon.stub(transport, 'timing')11 window.barometer.pageStartedAt = 612 window.trigger('load')13 })14 after(function () {15 transport.timing.restore()16 })17 it('should timing page load times', function () {18 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="unloadEventStart"}', 1)19 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="unloadEventEnd"}', 2)20 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="redirectStart"}', 3)21 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="redirectEnd"}', 4)22 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="fetchStart"}', 5)23 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="domainLookupStart"}', 6)24 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="domainLookupEnd"}', 7)25 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="connectStart"}', 8)26 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="connectEnd"}', 9)27 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="secureConnectionStart"}', 10)28 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="requestStart"}', 11)29 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="responseStart"}', 12)30 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="responseEnd"}', 13)31 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="domLoading"}', 14)32 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="domInteractive"}', 15)33 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="domContentLoadedEventStart"}', 16)34 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="domContentLoadedEventEnd"}', 17)35 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="domComplete"}', 18)36 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="loadEventStart"}', 19)37 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="loadEventEnd"}', 20)38 sinon.assert.calledWith(transport.timing, 'client_pageload_seconds{host="localhost:9876",path="context.html/",measure="timeToFirstScript"}', 5)39 assert.equal(transport.timing.callCount, 21)40 })...
Using AI Code Generation
1const navalia = require('navalia');2const browser = new navalia();3 .type('input[name="q"]', 'navalia')4 .click('input[name="btnK"]')5 .wait('h3')6 .screenshot('google.png')7 .pdf('google.pdf')8 .html('google.html')9 .close();10### async goto(url: string): Promise\<void>11### async type(selector: string, text: string): Promise\<void>12### async click(selector: string): Promise\<void>13### async wait(selector: string): Promise\<void>14### async screenshot(path: string): Promise\<void>15### async pdf(path: string): Promise\<void>16### async html(path: string): Promise\<void>17### async close(): Promise\<void>18### async evaluate(fn: Function, ...args: any[]): Promise\<any>19### async evaluateInPage(fn: Function, ...args: any[]): Promise\<any>20### async get(url: string): Promise\<string>21### async post(url: string, data: any): Promise\<string>22### async put(url: string, data: any): Promise\<string>23### async patch(url: string, data: any): Promise\<string>24### async delete(url: string): Promise\<string>25### async head(url: string): Promise\<string>26### async options(url: string): Promise\<string>27### async cookies(): Promise\<any[]>28### async cookie(name: string): Promise\<any>29### async setCookie(name: string, value: string, options: any): Promise\<void>30### async deleteCookie(name: string): Promise\<void>31### async deleteCookies(): Promise\<void>
Using AI Code Generation
1var navalia = require('navalia');2var assert = require('assert');3 .wait('input[name="q"]')4 .type('input[name="q"]', 'navalia')5 .click('input[name="btnK"]')6 .wait('h3.r a')7 .evaluate(function() {8 return document.querySelector('h3.r a').innerHTML;9 })10 .then(function(result) {11 assert.equal(result, 'Navalia - A headless browser for Node.js');12 console.log(result);13 navalia.close();14 })15 .catch(function(error) {16 console.log(error);17 navalia.close();18 });19var navalia = require('navalia');20var assert = require('assert');21 .wait('input[name="q"]')22 .type('input[name="q"]', 'navalia')23 .click('input[name="btnK"]')24 .wait('h3.r a')25 .evaluate(function() {26 return document.querySelector('h3.r a').innerHTML;27 })28 .then(function(result) {29 assert.equal(result, 'Navalia - A headless browser for Node.js');30 console.log(result);31 navalia.close();32 })33 .catch(function(error) {34 console.log(error);35 navalia.close();36 });37var navalia = require('navalia');38var assert = require('assert');39 .wait('input[name="q"]')40 .type('input[name="q"]', 'navalia')41 .click('input[name="btnK"]')42 .wait('h3.r a')43 .evaluate(function() {44 return document.querySelector('h3.r a').innerHTML;45 })46 .then(function(result) {47 assert.equal(result, 'Navalia - A headless browser for Node.js');48 console.log(result);49 navalia.close();50 })51 .catch(function(error) {52 console.log(error);53 navalia.close();54 });
Using AI Code Generation
1const navalia = require('navalia');2const browser = navalia().chrome();3 .then(() => browser.type('navalia', 'input[name="q"]'))4 .then(() => browser.click('input[value="Google Search"]'))5 .then(() => browser.wait('navalia'))6 .then(() => browser.screenshot('search.png'))7 .then(() => browser.close())8 .catch((error) => {9 console.error(error);10 process.exit(1);11 });
Using AI Code Generation
1const navalia = require('navalia');2const { Page } = navalia;3const page = new Page();4 .then(() => page.waitForSelector('input[title="Search"]'))5 .then(() => page.type('input[title="Search"]', 'navalia'))6 .then(() => page.click('input[value="Google Search"]'))7 .then(() => page.waitForNavigation())8 .then(() => page.waitForSelector('h3'))9 .then(() => page.evaluate(() => document.querySelector('h3').innerText))10 .then((text) => console.log(text))11 .then(() => page.close())12 .catch((err) => console.error(err));13#### `new Page([options])`14#### `page.goto(url, [options])`
Using AI Code Generation
1const navalia = require('navalia');2const browser = navalia('chrome');3const page = browser.page();4(async () => {5 await page.type('input[name="q"]', 'navalia');6 await page.click('input[name="btnK"]');7 await page.waitForNavigation();8 await page.screenshot('google.png');9 await browser.close();10})();11### `navalia(browserName, [options])`12### `browser.page([options])`13- `waitUntil` (string or array of strings, default: `load`): When to consider navigation succeeded, defaults to `load`. Events can be either:
Using AI Code Generation
1const navalia = require('navalia');2const browser = navalia();3 .then(() => browser.waitForNavigation())4 .then(() => browser.evaluate(() => window.location.href))5 .then((url) => console.log(url))6 .catch((err) => console.error(err))7 .then(() => browser.close());
Using AI Code Generation
1 .then(function(browser) {2 .type("#lst-ib", "Hello World")3 .click("#tsbb")4 .waitForSelector("#resultStats")5 .evaluate(function() {6 return document.querySelector("#resultStats").textContent;7 })8 .then(function(text) {9 console.log(text);10 });11 })12 .catch(function(error) {13 console.log(error);14 });15 .then(function(browser) {16 .type("#lst-ib", "Hello World")17 .click("#tsbb")18 .waitForSelector("#resultStats")19 .evaluate(function() {20 return document.querySelector("#resultStats").textContent;21 })22 .then(function(text) {23 console.log(text);24 });25 })26 .catch(function(error) {27 console.log(error);28 });29 .then(function(browser) {30 .type("#lst-ib", "Hello World")31 .click("#tsbb")32 .waitForSelector("#resultStats")33 .evaluate(function() {34 return document.querySelector("#resultStats").textContent;35 })36 .then(function(text) {37 console.log(text);38 });39 })40 .catch(function(error) {41 console.log(error);42 });43 .then(function(browser) {44 .type("#lst-ib", "Hello World")45 .click("#tsbb")46 .waitForSelector("#resultStats")47 .evaluate(function() {48 return document.querySelector("#
Using AI Code Generation
1const navalia = require('navalia');2const browser = new navalia();3 .then(() => browser.run('testpage.js'))4 .then(() => browser.close());5console.log(document.title);6console.log(document.title);7const navalia = require('navalia');8const browser = new navalia();9 .then(() => browser.run('testpage.js'))10 .then(() => browser.close());11console.log(document.title);
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!!