Best JavaScript code snippet using wpt
events.spec.js
Source:events.spec.js
1/*2Copyright 2020 Javier Brea3Copyright 2019 XByOrange4Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at5http://www.apache.org/licenses/LICENSE-2.06Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.7*/8const sinon = require("sinon");9const { Provider, providers } = require("../../src/index");10describe("Provider events", () => {11 let sandbox;12 let TestProvider;13 let provider;14 let childProvider;15 let hasToThrow;16 beforeEach(() => {17 sandbox = sinon.createSandbox();18 TestProvider = class extends Provider {19 readMethod(data) {20 return new Promise((resolve, reject) => {21 setTimeout(() => {22 if (!hasToThrow) {23 resolve(data);24 } else {25 reject(hasToThrow);26 }27 }, 100);28 });29 }30 };31 provider = new TestProvider();32 childProvider = provider.query({ foo: "foo" });33 });34 afterEach(() => {35 sandbox.restore();36 providers.clear();37 });38 describe("listener", () => {39 it("should execute listener every time event is emitted", async () => {40 const spy = sandbox.spy();41 provider.on("readStart", spy);42 await provider.read();43 provider.cleanCache();44 await provider.read();45 expect(spy.callCount).toEqual(2);46 });47 it("should remove listener when returned function is executed", async () => {48 const spy = sandbox.spy();49 const removeListener = provider.on("readStart", spy);50 await provider.read();51 provider.cleanCache();52 removeListener();53 await provider.read();54 expect(spy.callCount).toEqual(1);55 });56 it("should execute listener only once when listener was added with once", async () => {57 const spy = sandbox.spy();58 provider.once("readStart", spy);59 await provider.read();60 provider.cleanCache();61 await provider.read();62 expect(spy.callCount).toEqual(1);63 });64 it("should remove listener when returned function is executed and listener was added with once", async () => {65 const spy = sandbox.spy();66 const removeListener = provider.once("readStart", spy);67 removeListener();68 await provider.read();69 expect(spy.callCount).toEqual(0);70 });71 it("should execute child listener every time child event is emitted", async () => {72 const spy = sandbox.spy();73 provider.onChild("readStart", spy);74 await childProvider.read();75 childProvider.cleanCache();76 await childProvider.read();77 expect(spy.callCount).toEqual(2);78 });79 it("should remove child listener when returned function is executed", async () => {80 const spy = sandbox.spy();81 const removeListener = provider.onChild("readStart", spy);82 await childProvider.read();83 provider.cleanCache();84 removeListener();85 await childProvider.read();86 expect(spy.callCount).toEqual(1);87 });88 it("should execute listener only once when child listener was added with once", async () => {89 const spy = sandbox.spy();90 provider.onceChild("readStart", spy);91 await childProvider.read();92 childProvider.cleanCache();93 await childProvider.read();94 expect(spy.callCount).toEqual(1);95 });96 it("should remove child listener when returned function is executed and listener was added with once", async () => {97 const spy = sandbox.spy();98 const removeListener = provider.onceChild("readStart", spy);99 removeListener();100 await childProvider.read();101 expect(spy.callCount).toEqual(0);102 });103 });104 describe("listener arguments", () => {105 it("should pass child to child listener as first argument", async () => {106 const spy = sandbox.spy();107 provider.onChild("readStart", spy);108 await childProvider.read();109 expect(spy.getCall(0).args[0]).toEqual(childProvider);110 });111 it("should pass child to once child listener as first argument", async () => {112 const spy = sandbox.spy();113 provider.onceChild("readStart", spy);114 await childProvider.read();115 expect(spy.getCall(0).args[0]).toEqual(childProvider);116 });117 it("should pass event name to child listener as first argument when child listener is added with wildcard", async () => {118 const spy = sandbox.spy();119 provider.onChild("*", spy);120 await childProvider.read();121 expect(spy.getCall(0).args[0]).toEqual("readStart");122 });123 it("should pass event name to once child listener as first argument when child listener is added with wildcard", async () => {124 const spy = sandbox.spy();125 provider.onceChild("*", spy);126 await childProvider.read();127 expect(spy.getCall(0).args[0]).toEqual("readStart");128 });129 it("should pass child to child listener as second argument when child listener is added with wildcard", async () => {130 const spy = sandbox.spy();131 provider.onChild("*", spy);132 await childProvider.read();133 expect(spy.getCall(0).args[0]).toEqual("readStart");134 expect(spy.getCall(0).args[1]).toEqual(childProvider);135 });136 it("should pass child to once child listener as second argument when child listener is added with wildcard", async () => {137 const spy = sandbox.spy();138 provider.onceChild("*", spy);139 await childProvider.read();140 expect(spy.getCall(0).args[0]).toEqual("readStart");141 expect(spy.getCall(0).args[1]).toEqual(childProvider);142 });143 });144 describe("readStart event", () => {145 it("should emit a readStart event when provider starts read method", async () => {146 const spy = sandbox.spy();147 provider.on("readStart", spy);148 await provider.read();149 expect(spy.callCount).toEqual(1);150 });151 it("should emit a readStart event when listener is added with wildcard", async () => {152 const spy = sandbox.spy();153 provider.on("*", spy);154 await provider.read();155 expect(spy.getCall(0).args[0]).toEqual("readStart");156 });157 it("should emit a child readStart event when child starts read method", async () => {158 const spy = sandbox.spy();159 provider.onChild("readStart", spy);160 await childProvider.read();161 expect(spy.callCount).toEqual(1);162 });163 });164 describe("readSuccess event", () => {165 it("should emit a readSuccess event when provider finish read method", async () => {166 const spy = sandbox.spy();167 provider.on("readSuccess", spy);168 await provider.read();169 expect(spy.callCount).toEqual(1);170 });171 it("should emit a readSuccess event when listener is added with wildcard", async () => {172 const spy = sandbox.spy();173 provider.on("*", spy);174 await provider.read();175 expect(spy.getCall(1).args[0]).toEqual("readSuccess");176 });177 it("should emit a child readStart event when child finish read method", async () => {178 const spy = sandbox.spy();179 provider.onChild("readSuccess", spy);180 await childProvider.read();181 expect(spy.callCount).toEqual(1);182 });183 });184 describe("readError event", () => {185 beforeEach(() => {186 hasToThrow = new Error();187 });188 it("should emit a readError event when provider throws in read method", async () => {189 const spy = sandbox.spy();190 provider.on("readError", spy);191 try {192 await provider.read();193 } catch (err) {}194 expect(spy.callCount).toEqual(1);195 });196 it("should emit a readError event when listener is added with wildcard", async () => {197 const spy = sandbox.spy();198 provider.on("*", spy);199 try {200 await provider.read();201 } catch (err) {}202 expect(spy.getCall(1).args[0]).toEqual("readError");203 });204 it("should emit a child readError event when child finish read method", async () => {205 const spy = sandbox.spy();206 provider.onChild("readError", spy);207 try {208 await childProvider.read();209 } catch (err) {}210 expect(spy.callCount).toEqual(1);211 });212 });213 describe("cleanCache event", () => {214 beforeEach(() => {215 hasToThrow = new Error();216 });217 it("should emit a cleanCache event when provider cache is clean", async () => {218 const spy = sandbox.spy();219 provider.on("cleanCache", spy);220 provider.cleanCache();221 expect(spy.callCount).toEqual(1);222 expect(spy.getCall(0).args[0]).toEqual(undefined);223 });224 it("should emit a cleanCache event when listener is added with wildcard", async () => {225 const spy = sandbox.spy();226 provider.on("*", spy);227 provider.cleanCache();228 expect(spy.getCall(0).args[0]).toEqual("cleanCache");229 });230 it("should emit a child cleanCache event when child cache is clean", async () => {231 const spy = sandbox.spy();232 provider.onChild("cleanCache", spy);233 childProvider.cleanCache();234 expect(spy.callCount).toEqual(1);235 expect(spy.getCall(0).args[0]).toEqual(childProvider);236 });237 it("should emit a child cleanCache event when parent cache is clean", async () => {238 const spy = sandbox.spy();239 provider.onChild("cleanCache", spy);240 provider.cleanCache();241 expect(spy.callCount).toEqual(1);242 expect(spy.getCall(0).args[0]).toEqual(childProvider);243 });244 });245 describe("resetState event", () => {246 beforeEach(() => {247 hasToThrow = new Error();248 });249 it("should emit a resetState event when provider resetState is called", async () => {250 const spy = sandbox.spy();251 provider.on("resetState", spy);252 provider.resetState();253 expect(spy.callCount).toEqual(1);254 });255 it("should emit a resetState event when listener is added with wildcard", async () => {256 const spy = sandbox.spy();257 provider.on("*", spy);258 provider.resetState();259 expect(spy.getCall(0).args[0]).toEqual("resetState");260 });261 it("should emit a child resetState event when child resetState is called", async () => {262 const spy = sandbox.spy();263 provider.onChild("resetState", spy);264 childProvider.resetState();265 expect(spy.callCount).toEqual(1);266 });267 it("should emit a child resetState event when parent resetState is called", async () => {268 const spy = sandbox.spy();269 provider.onChild("resetState", spy);270 provider.resetState();271 expect(spy.callCount).toEqual(1);272 });273 });...
Tokenizer.js
Source:Tokenizer.js
1import * as Backend from './Backend.js'2function isInteger(str){3 if(typeof str != 'string') return false4 if(str.length == 0) return false5 if(str.includes('.')) return false6 if(str.includes(' ')) return false7 if(str.includes('\n')) return false8 if(str.includes('\r')) return false9 return Number.isInteger(Number(str))10}11function isFloat(){12}13const whitespace = [14 ' ',15 '\t',16]17const symbols = [18 '(',19 ')',20 '+',21 '-',22 '*',23 '/',24 '=',25 '<',26 '>',27 '!',28 '&',29 '|',30 ',',31 '?',32 '!',33 '$',34 '"',35 '{',36 '}',37 "'",38 '#'39]40const keywords = [41 'if',42 'fif',43 'func',44 'delay',45 'else'46]47export function Tokenize(input) {48 let tokens = []49 let readStart = 050 let lastUnkown = -151 while(readStart < input.length) {52 let found = false53 let foundAt = -154 for(let i = Math.min(input.length, readStart + 30) + 1; i >= readStart; i--) {55 const sub = input.substring(readStart, i)56 if(isInteger(sub)){57 tokens.push({ value: sub, token: 'INTEGER' })58 found = true59 foundAt = i60 break61 }else if(whitespace.includes(sub)){62 tokens.push({ value: sub, token: 'WHITESPACE' })63 found = true64 foundAt = i65 break66 }else if(symbols.includes(sub)){ 67 tokens.push({ value: sub, token: 'SYMBOL' })68 found = true69 foundAt = i70 break71 }else if(keywords.includes(sub)){72 tokens.push({ value: sub, token: 'KEYWORD' })73 found = true74 foundAt = i75 break76 }else if(sub == '\n'){77 tokens.push({ value: sub, token: 'NEWLINE' })78 found = true79 foundAt = i80 break81 }else if(sub == '\r'){82 tokens.push({ value: sub, token: 'NEWLINE' })83 found = true84 foundAt = i85 break86 }else if(sub == 'false' || sub == 'true'){87 tokens.push({ value: sub, token: 'BOOLEAN' })88 found = true89 foundAt = i90 break91 }92 }93 if(found){94 if(lastUnkown != -1){95 tokens.splice(tokens.length - 1, 0, { value: input.substring(lastUnkown, readStart), token: 'NAME' })96 lastUnkown = -197 }98 readStart = foundAt99 }else{100 if(lastUnkown == -1) lastUnkown = readStart101 readStart++102 }103 }104 if(lastUnkown != -1) {105 tokens.push({ value: input.substring(lastUnkown, readStart), token: 'NAME' })106 }107 return tokens...
DataLoader.test.ts
Source:DataLoader.test.ts
1import { AxiosDataLoader } from "../src/loader";2import { BufferedDataLoader } from "../src/loader/DataLoader";3import Axios from "axios";4import { stat, open, read } from "fs";5import { promisify } from "util";6import * as path from "path";7async function fsRead(path: string, start: number, size: number): Promise<Uint8Array> {8 const fd: number = await promisify(open)(path, "r");9 const buffer = Buffer.alloc(size);10 await promisify(read)(fd, buffer, 0, size, start);11 return new Uint8Array(buffer);12}13const filename = "testbw.bigwig";14const url = `http://localhost:8001/${filename}`15const fsPath = path.join(__dirname, "..", "resources", "static", filename);16describe("AxiosDataLoader", () => {17 it("should load the correct data", async () => {18 const readStart = 0, readSize = 64;19 const loader = new AxiosDataLoader(url, Axios.create());20 const data = new Uint8Array(await loader.load(readStart, readSize));21 const fsData = await fsRead(fsPath, readStart, readSize);22 expect(data.toString()).toBe(fsData.toString());23 });24});25describe("BufferedDataLoader", () => {26 it("should buffer data for subsequent calls", async () => {27 const loader = new AxiosDataLoader(url, Axios.create());28 const bufferedLoader = new BufferedDataLoader(loader, 250);29 const loaderSpy = jest.spyOn(loader, "load");30 let readStart = 100, readSize = 100;31 let data = new Uint8Array(await bufferedLoader.load(readStart, readSize));32 let fsData = await fsRead(fsPath, readStart, readSize);33 expect(data.toString()).toBe(fsData.toString());34 expect(loaderSpy).toHaveBeenCalled();35 36 // This call should use buffered data. It should not need to call out to the loader.37 readStart = 200;38 data = new Uint8Array(await bufferedLoader.load(readStart, readSize));39 fsData = await fsRead(fsPath, readStart, readSize);40 expect(data.toString()).toBe(fsData.toString());41 expect(loaderSpy).toHaveBeenCalledTimes(1);42 // This call should request more data than the buffer contains. It should call out to the loader.43 readStart = 300;44 data = new Uint8Array(await bufferedLoader.load(readStart, readSize));45 fsData = await fsRead(fsPath, readStart, readSize);46 expect(data.toString()).toBe(fsData.toString());47 expect(loaderSpy).toHaveBeenCalledTimes(2);48 });...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var location = 'Dulles:Chrome';4var options = {5};6wpt.runTest(url, options, function(err, data) {7 if (err) return console.error(err);8 console.log('Test submitted for: %s', data.data.testUrl);9 console.log('View the test at: %s', data.data.userUrl);10 console.log('Poll the test status at: %s', data.data.jsonUrl);11 var testId = data.data.testId;12 wpt.getTestStatus(testId, function(err, data) {13 if (err) return console.error(err);14 console.log('Test status for %s: %s', testId, data.data.statusText);15 if (data.data.statusCode === 200) {16 console.log('Test completed at: %s', data.data.summaryCSV);17 }18 });19});20var wpt = require('webpagetest');21var wpt = new WebPageTest('www.webpagetest.org');22var location = 'Dulles:Chrome';23var script = 'document.getElementById("lst-ib").value="Hello World";';24var options = {25};26wpt.runTest(url, options, function(err, data) {27 if (err) return console.error(err);28 console.log('Test submitted for: %s', data.data.testUrl);29 console.log('View the test at: %s', data.data.userUrl);30 console.log('Poll the test status at: %s', data.data.jsonUrl);31 var testId = data.data.testId;32 wpt.getTestStatus(testId, function(err, data) {33 if (err) return console.error(err);34 console.log('Test status for %s: %s', testId, data.data.statusText);35 if (data.data.statusCode === 200) {36 console.log('Test completed at: %s', data.data
Using AI Code Generation
1const wpt = require('webpagetest');2const test = new wpt('A.4c4f4f4f4f4f4f4f4f4f4f4f4f4f4f4f');3 if (err) return console.error(err);4 test.readStart(data.data.testId, (err, data) => {5 if (err) return console.error(err);6 console.log(data);7 });8});9const wpt = require('webpagetest');10const test = new wpt('A.4c4f4f4f4f4f4f4f4f4f4f4f4f4f4f4f');11 if (err) return console.error(err);12 test.readResults(data.data.testId, (err, data) => {13 if (err) return console.error(err);14 console.log(data);15 });16});17const wpt = require('webpagetest');18const test = new wpt('A.4c4f4f4f4f4f4f4f4f4f4f4f4f4f4f4f');19test.readTesters('Dulles:Chrome', (err, data) => {20 if (err) return console.error(err);21 console.log(data);22});23const wpt = require('webpagetest');24const test = new wpt('A.4c4f4f4f4f4f4f4f4f4f4f4f4f4f4f4f');25test.readLocations((err, data) => {26 if (err) return console.error(err);27 console.log(data);28});
Using AI Code Generation
1var wpt = require('webpagetest');2var fs = require('fs');3var util = require('util');4var options = {5};6var test = new wpt(options);7var location = 'Dulles:Chrome';8var runs = 1;9var firstViewOnly = true;10var pollResults = 5;11var video = true;12var timeline = true;13var netlog = true;14var speedIndex = true;15var pollInterval = 5000;16var timeout = 30000;17var label = 'test';18var connectivity = 'Cable';19var bwDown = 100;20var bwUp = 100;21var latency = 28;22var plr = 0;23var login = '';24var password = '';25var basicAuth = '';26var script = '';27var scriptPath = '';28var notifyEmail = '';29var notifySlack = '';30var notifyWebhook = '';31var notifyMattermost = '';32var notifyHipchat = '';33var notifyPushover = '';34var notifyTelegram = '';35var notifyFlowdock = '';36var notifyTwitter = '';37var notifyCampfire = '';38var notifyPushbullet = '';39var notifyPushalot = '';40var notifyPushover = '';41var notifyPushsafer = '';42var notifyDiscord = '';43var notifyIFTTT = '';44var notifyLine = '';45var notifyPagerDuty = '';46var notifySlack = '';47var notifySMS = '';48var notifyViber = '';49var notifyWhatsApp = '';50var notifyWebhook = '';51var notifyZulip = '';52var notifyMattermost = '';53var notifyHipchat = '';54var notifySNS = '';55var notifyTelegram = '';56var notifyFlowdock = '';57var notifyTwitter = '';58var notifyCampfire = '';59var notifyPushbullet = '';60var notifyPushalot = '';61var notifyPushover = '';62var notifyPushsafer = '';63var notifyDiscord = '';64var notifyIFTTT = '';65var notifyLine = '';66var notifyPagerDuty = '';67var notifySlack = '';68var notifySMS = '';69var notifyViber = '';70var notifyWhatsApp = '';
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3var testId = '170107_8W_8d4ad4f2e2c4f4e4b4f9d6a9a1a4b6f8';4wpt.readStart(testId, function(err, data) {5 if (err) {6 console.log(err);7 } else {8 console.log(data);9 }10});11var wpt = require('wpt');12var wpt = new WebPageTest('www.webpagetest.org');13var testId = '170107_8W_8d4ad4f2e2c4f4e4b4f9d6a9a1a4b6f8';14wpt.readResult(testId, function(err, data) {15 if (err) {16 console.log(err);17 } else {18 console.log(data);19 }20});21var wpt = require('wpt');22var wpt = new WebPageTest('www.webpagetest.org');23wpt.readTesters(function(err, data) {24 if (err) {25 console.log(err);26 } else {27 console.log(data);28 }29});
Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var test = new wpt('www.webpagetest.org', options.key);5 videoParams: {6 }7}, function(err, data) {8 if (err) {9 console.error(err);10 } else {11 console.log(data);12 test.readStart(data.data.testId, function(err, data) {13 if (err) {14 console.error(err);15 } else {16 console.log(data);17 }18 });19 }20});
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!!