Best JavaScript code snippet using wpt
MapboxStylesSpec.js
Source:MapboxStylesSpec.js
1import "../../../tool/mock_ol";2import "../../../libs/openlayers/plugins/ol-mapbox-style/2.11.2/olms";3import { MapboxStyles } from "../../../../src/openlayers/overlay/vectortile/MapboxStyles";4import { FetchRequest } from "../../../../src/common/util/FetchRequest";5import Map from 'ol/Map';6import View from 'ol/View';7import Feature from 'ol/Feature';8import Polygon from 'ol/geom/Polygon';9import * as olColor from 'ol/color';10describe("openlayers_MapboxStyles", () => {11 var url = GlobeParameter.californiaURL;12 var testDiv, map, mapboxStyles, originalTimeout, stylesOptions;13 var feature, feature3, feature2;14 beforeAll(() => {15 testDiv = window.document.createElement("div");16 testDiv.setAttribute("id", "map");17 testDiv.style.styleFloat = "left";18 testDiv.style.marginLeft = "8px";19 testDiv.style.marginTop = "50px";20 testDiv.style.width = "500px";21 testDiv.style.height = "500px";22 window.document.body.appendChild(testDiv);23 map = new Map({24 target: "map",25 view: new View({26 center: [-122.228687503369, 38.1364932162598],27 zoom: 10,28 minZoom: 10,29 maxZoom: 14,30 projection: "EPSG:4326"31 })32 });33 stylesOptions = {34 url: url,35 map: map,36 source: "California"37 };38 feature = new Feature({39 geometry: new Polygon([[[0, 0], [-10, 30], [-30, 0], [0, 0]]]),40 layer: "Military_R@California"41 });42 feature.setId(1);43 feature2 = new Feature({44 geometry: new Polygon([[[5, 5], [-15, 35], [-35, 5], [5, 5]]]),45 layer: "Military_R@California"46 });47 feature2.setId(2);48 feature3 = new Feature({49 geometry: new Polygon([[[10, 10], [-20, 40], [-20, 10], [10, 10]]]),50 layer: "Military_R@California"51 });52 feature3.setId(3);53 spyOn(FetchRequest, "get").and.callFake((testUrl, params, options) => {54 if (testUrl.indexOf("vectorstyles") > 0) {55 expect(testUrl).toBe(url + "/tileFeature/vectorstyles?type=MapBox_GL&styleonly=true");56 return Promise.resolve(new Response(JSON.stringify(vectorstylesEscapedJson)));57 } else if (testUrl.indexOf("sprite.json") > 0) {58 return Promise.resolve(new Response(JSON.stringify(spriteEscapedJson)));59 }60 return null;61 });62 });63 beforeEach(() => {64 originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;65 jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;66 });67 afterEach(() => {68 jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;69 });70 afterAll(() => {71 window.document.body.removeChild(testDiv);72 });73 const defaultColor = [249, 224, 219, 0.9];74 const highlightColor = [255, 0, 0, 1];75 const matchFillColor = function(style, expectColor) {76 matchColor(style.getFill().getColor(),expectColor);77 };78 const matchColor = function(sourceColor, expectColor) {79 expect(sourceColor).not.toBeNull();80 const color = olColor.asArray(sourceColor);81 expectColor[0] && expect(color[0]).toBeCloseTo(expectColor[0]);82 expectColor[1] && expect(color[1]).toBeCloseTo(expectColor[1]);83 expectColor[2] && expect(color[2]).toBeCloseTo(expectColor[2]);84 expectColor[3] && expect(color[3]).toBeCloseTo(expectColor[3]);85 };86 it("getStyleFunction", done => {87 var style;88 mapboxStyles = new MapboxStyles(stylesOptions);89 mapboxStyles.on("styleloaded", () => {90 style = mapboxStyles.getStyleFunction();91 expect(style).not.toBeNull();92 done();93 });94 });95 it("getStyleFunction,setSelectedId", done => {96 mapboxStyles = new MapboxStyles(stylesOptions);97 mapboxStyles.on("styleloaded", () => {98 var style = mapboxStyles.getStyleFunction()(feature, 2.388657133911758);99 expect(style).not.toBeNull();100 matchFillColor(style[0],defaultColor);101 matchColor(style[1].getStroke().getColor(),defaultColor)102 mapboxStyles.updateStyles({103 paint: {104 "fill-color": "rgba(249,0,0,0.90)"105 },106 id: "Military_R@California#26",107 maxzoom: 17108 });109 style = mapboxStyles.getStyleFunction()(feature, 2.388657133911758 / 2);110 expect(style).not.toBeNull();111 expect(style.length).toBe(2);112 matchFillColor(style[0],[249,0,0,0.9]);113 matchColor(style[1].getStroke().getColor(),defaultColor)114 mapboxStyles.setSelectedId(1, "Military_R@California");115 style = mapboxStyles.getStyleFunction()(feature, 2.388657133911758);116 expect(style).not.toBeNull();117 matchFillColor(style[0],highlightColor);118 done();119 });120 });121 it("selectedObjects", done => {122 mapboxStyles = new MapboxStyles(stylesOptions);123 mapboxStyles.on("styleloaded", () => {124 var style = mapboxStyles.getStyleFunction()(feature, 2.388657133911758);125 expect(style).not.toBeNull();126 matchFillColor(style[0],defaultColor);127 mapboxStyles.setSelectedObjects({ id: 1, sourceLayer: "Military_R@California" });128 style = mapboxStyles.getStyleFunction()(feature, 2.388657133911758);129 expect(style).not.toBeNull();130 matchFillColor(style[0],highlightColor);131 //add132 mapboxStyles.addSelectedObjects({ id: 2, sourceLayer: "Military_R@California" });133 style = mapboxStyles.getStyleFunction()(feature, 2.388657133911758);134 expect(style).not.toBeNull();135 matchFillColor(style[0],highlightColor);136 style = mapboxStyles.getStyleFunction()(feature2, 2.388657133911758);137 expect(style).not.toBeNull();138 matchFillColor(style[0],highlightColor);139 //remove140 mapboxStyles.removeSelectedObjects({ id: 2, sourceLayer: "Military_R@California" });141 style = mapboxStyles.getStyleFunction()(feature, 2.388657133911758);142 expect(style).not.toBeNull();143 matchFillColor(style[0],highlightColor);144 style = mapboxStyles.getStyleFunction()(feature2, 2.388657133911758);145 expect(style).not.toBeNull();146 matchFillColor(style[0],defaultColor);147 //set148 mapboxStyles.setSelectedObjects({ id: 2, sourceLayer: "Military_R@California" });149 style = mapboxStyles.getStyleFunction()(feature, 2.388657133911758);150 expect(style).not.toBeNull();151 matchFillColor(style[0],defaultColor);152 style = mapboxStyles.getStyleFunction()(feature2, 2.388657133911758);153 expect(style).not.toBeNull();154 matchFillColor(style[0],highlightColor);155 //clear156 mapboxStyles.clearSelectedObjects();157 style = mapboxStyles.getStyleFunction()(feature, 2.388657133911758);158 expect(style).not.toBeNull();159 matchFillColor(style[0],defaultColor);160 style = mapboxStyles.getStyleFunction()(feature2, 2.388657133911758);161 expect(style).not.toBeNull();162 matchFillColor(style[0],defaultColor);163 done();164 });165 });166 it("getStylesBySourceLayer", done => {167 mapboxStyles = new MapboxStyles(stylesOptions);168 mapboxStyles.once("styleloaded", () => {169 try {170 var layer = mapboxStyles.getStylesBySourceLayer("Military_R@California");171 expect(layer).not.toBeNull();172 expect(layer[0].paint).not.toBeNull();173 expect(layer[0].paint["fill-color"]).toBe("rgba(249,224,219,0.90)");174 vectorstylesEscapedJson.layers[2].paint["fill-color"] = "rgba(255,0,0,0)";175 mapboxStyles.setStyle(vectorstylesEscapedJson);176 layer = mapboxStyles.getStylesBySourceLayer("Military_R@California");177 expect(layer).not.toBeNull();178 expect(layer[0].paint).not.toBeNull();179 expect(layer[0].paint["fill-color"]).toBe("rgba(255,0,0,0)");180 done();181 } catch (e) {182 console.log("'getStylesBySourceLayer'æ¡ä¾å¤±è´¥" + e.name + ":" + e.message);183 expect(false).toBeTruthy();184 done();185 }186 });187 });188 it("init_StyleObject", done => {189 var style;190 mapboxStyles = new MapboxStyles({191 style: vectorstylesEscapedJson,192 map: map,193 source: "California"194 });195 mapboxStyles.on("styleloaded", () => {196 try {197 style = mapboxStyles.getStyleFunction();198 expect(style).not.toBeNull();199 done();200 } catch (e) {201 console.log("'init_StyleObject'æ¡ä¾å¤±è´¥" + e.name + ":" + e.message);202 expect(false).toBeTruthy();203 done();204 }205 });206 });207 it("init_StyleObject_nullSource", done => {208 var style;209 mapboxStyles = new MapboxStyles({210 style: vectorstylesEscapedJson,211 map: map212 });213 mapboxStyles.on("styleloaded", () => {214 try {215 style = mapboxStyles.getStyleFunction();216 expect(style).not.toBeNull();217 expect(mapboxStyles.source).toEqual("California");218 done();219 } catch (e) {220 console.log("'init_StyleObject_nullSource'æ¡ä¾å¤±è´¥" + e.name + ":" + e.message);221 expect(false).toBeTruthy();222 done();223 }224 });225 });226 it("init_StyleUrl", done => {227 var style;228 mapboxStyles = new MapboxStyles({229 style: url + "/tileFeature/vectorstyles?type=MapBox_GL&styleonly=true",230 map: map,231 source: "California"232 });233 mapboxStyles.on("styleloaded", () => {234 try {235 style = mapboxStyles.getStyleFunction();236 expect(style).not.toBeNull();237 done();238 } catch (e) {239 console.log("'init_StyleUrl'æ¡ä¾å¤±è´¥" + e.name + ":" + e.message);240 expect(false).toBeTruthy();241 done();242 }243 });244 });...
userColorManager.test.ts
Source:userColorManager.test.ts
...27 colors,28}29describe('user color manager', () => {30 test('chooses prefered color based on hash if unused', () => {31 expectColor(createUserColorManager(options).listen('bamse'), 'magenta')32 return nextTick()33 })34 test('returns same color when still assigned', () => {35 const manager = createUserColorManager(options)36 expectColor(manager.listen('bamse'), 'magenta')37 expectColor(manager.listen('bamse'), 'magenta')38 return nextTick()39 })40 test('returns same color when still assigned (has open subscriptions)', () => {41 const manager = createUserColorManager(options)42 const sub1 = manager.listen('bamse').subscribe((color) => expect(color).toBe(colors.magenta))43 const sub2 = manager.listen('bamse').subscribe((color) => expect(color).toBe(colors.magenta))44 sub1.unsubscribe()45 sub2.unsubscribe()46 return nextTick()47 })48 test('falls back to "least used" if preferred color is not available', () => {49 // kokos and espen has the same preferred color (purple),50 // but as kokos got it assigned first, espen will have to waive51 let manager = createUserColorManager(options)52 let sub = manager.listen('kokos').subscribe((color) => expect(color).toBe(colors.purple))53 expectColor(manager.listen('espen'), 'blue')54 sub.unsubscribe()55 // just to make sure, reverse and see that the opposite is also true:56 // kokos and espen has the same preferred color (purple),57 // but as espen got it assigned first, kokos will have to waive58 manager = createUserColorManager(options)59 sub = manager.listen('espen').subscribe((color) => expect(color).toBe(colors.purple))60 expectColor(manager.listen('kokos'), 'blue')61 sub.unsubscribe()62 return nextTick()63 })64 test('returns the same color as previously chosen if there are no unused', () => {65 const manager = createUserColorManager(options)66 // Ask for a color, but release it right away67 expectColor(manager.listen('kokos'), 'purple')68 // Both espen and kokos prefers purple. Assign all but one color slot to non-kokos69 // people, and include Espen. This means kokos will ask at a time when there are70 // unused colors, and the previously assigned color is in use, which should prioritize71 // giving a unique color instead of giving the previously used one.72 const nonKokos = ['espen'].concat(73 peopleNames.filter((name) => name !== 'kokos' && name !== 'yggrasil')74 )75 const subs = nonKokos.map((name) =>76 manager77 .listen(name)78 .subscribe((color) => expect(color).toBe(colors[colorPreferences[name] || 'purple']))79 )80 // Now, when kokos wants her previous color, and there is an unused slot, she should81 // be given the unused color instead of the previously assigned one82 expectColor(manager.listen('kokos'), 'yellow')83 subs.forEach((sub) => sub.unsubscribe())84 return nextTick()85 })86 test('falls back on last used color if all colors are taken', () => {87 const manager = createUserColorManager(options)88 const subs = [89 manager.listen('espen').subscribe((color) => expect(color).toBe(colors.purple)),90 ].concat(91 peopleNames92 .filter((name) => name !== 'kokos')93 .map((name) =>94 manager95 .listen(name)96 .subscribe((color) => expect(color).toBe(colors[colorPreferences[name]]))97 )98 )99 // espen "stole" purple, so kokos will have to pick a different color100 expectColor(manager.listen('kokos'), 'blue')101 // subsequent calls will still give that color102 expectColor(manager.listen('kokos'), 'blue')103 subs.forEach((sub) => sub.unsubscribe())104 return nextTick()105 })106 test('"current user" has static color (empty state)', () => {107 const manager = createUserColorManager({...options, userStore: getMockUserStore()})108 expectColor(manager.listen('current'), options.currentUserColor)109 return nextTick()110 })111 test('"current user" has static color (all slots filled state)', () => {112 const manager = createUserColorManager({...options, userStore: getMockUserStore()})113 const subs = peopleNames.map((name) => manager.listen(name).subscribe(() => null))114 expectColor(manager.listen('current'), options.currentUserColor)115 subs.forEach((sub) => sub.unsubscribe())116 return nextTick()117 })118 test('"current user" presence means default color is taken from the start', async () => {119 const manager = createUserColorManager({...options, userStore: getMockUserStore()})120 await nextTick()121 const nextHueInLine = hues.find((color) => color !== options.currentUserColor)122 const prefersBlue = peopleNames.find(123 (name) => colorPreferences[name] === options.currentUserColor124 )125 expectColor(manager.listen(prefersBlue), nextHueInLine)126 await new Promise((resolve) => setTimeout(resolve, 100))127 return nextTick()128 })129 test('throws if current user color is not in colors list', () => {130 const {blue, ...incompleteColors} = options.colors131 expect(() => {132 createUserColorManager({...options, colors: incompleteColors})133 }).toThrowErrorMatchingInlineSnapshot(`"'colors' must contain 'currentUserColor' (blue)"`)134 })135 test('can return sync value', () => {136 expect(createUserColorManager(options).get('kokos')).toBe(colors[colorPreferences.kokos])137 })138})139function expectColor(obs: Observable<UserColor>, expectedHue: string) {140 let returned: UserColor | undefined141 obs142 .subscribe((color) => {143 returned = color144 })145 .unsubscribe()146 expect(returned).toBe(colors[expectedHue])147}148// Because observables can be both sync and async, and errors are async,149// returning a promise that waits until the next tick (ish) will ensure150// that errors thrown after test code does not silently get swallowed151function nextTick() {152 return new Promise((resolve) => setImmediate(resolve))153}
normalizeColor.spec.js
Source:normalizeColor.spec.js
...7 normalizeColor(input),8 expected,9 `${input} should be a ${expected}`10 );11 expectColor('000', '#000000');12 expectColor('fa9', '#FFAA99');13 expectColor('ffaa76', '#FFAA76');14 expectColor('#000', '#000000');15 expectColor('#fa9', '#FFAA99');16 expectColor('#DEC', '#DDEECC');17 expectColor('#fa9de8', '#FA9DE8');18 expectColor('#0CDE87', '#0CDE87');19 // Fallback to default20 expectColor('hello world', '#000000');21 expectColor('#gaf', '#000000');22 });...
Using AI Code Generation
1module.exports = {2 {3 },4 {5 }6 {7 }8 "paths": {9 },10 "engineOptions": {11 },12}
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3 console.log(data);4});5### new WebPageTest(apiKey, [options])6### wpt.runTest(url, [options], [callback])
Using AI Code Generation
1var expectColor = require('wpt').expectColor;2expectColor('test.jpg', 'rgb(0,0,0)', 0, 0, 0, 0, 0, 0, function(err, result){3 if(err){4 console.log(err);5 }6 else{7 console.log(result);8 }9});10var expectElement = require('wpt').expectElement;11expectElement('div', function(err, result){12 if(err){13 console.log(err);14 }15 else{16 console.log(result);17 }18});19var expectHttpCode = require('wpt').expectHttpCode;20expectHttpCode(200, function(err, result){21 if(err){22 console.log(err);23 }24 else{25 console.log(result);26 }27});
Using AI Code Generation
1var expectColor = require('expectColor');2var wpt = require('webpagetest');3var fs = require('fs');4var wpt = new WebPageTest('www.webpagetest.org');5var config = require('./config.json');6var url = config.url;7var key = config.key;8var location = config.location;9var browser = config.browser;10var timeout = config.timeout;11var script = config.script;12var run = config.run;13var video = config.video;14var connectivity = config.connectivity;15var label = config.label;16var mobile = config.mobile;17var firstViewOnly = config.firstViewOnly;18var pollResults = config.pollResults;19var pollResultsInterval = config.pollResultsInterval;20var timeout = config.timeout;21var script = config.script;22var run = config.run;23var video = config.video;24var connectivity = config.connectivity;25var label = config.label;26var mobile = config.mobile;27var firstViewOnly = config.firstViewOnly;28var pollResults = config.pollResults;29var pollResultsInterval = config.pollResultsInterval;30var timeout = config.timeout;31var script = config.script;32var run = config.run;33var video = config.video;34var connectivity = config.connectivity;35var label = config.label;36var mobile = config.mobile;37var firstViewOnly = config.firstViewOnly;38var pollResults = config.pollResults;39var pollResultsInterval = config.pollResultsInterval;40var timeout = config.timeout;41var script = config.script;42var run = config.run;43var video = config.video;44var connectivity = config.connectivity;45var label = config.label;46var mobile = config.mobile;47var firstViewOnly = config.firstViewOnly;48var pollResults = config.pollResults;49var pollResultsInterval = config.pollResultsInterval;50var timeout = config.timeout;51var script = config.script;52var run = config.run;53var video = config.video;54var connectivity = config.connectivity;55var label = config.label;56var mobile = config.mobile;57var firstViewOnly = config.firstViewOnly;58var pollResults = config.pollResults;59var pollResultsInterval = config.pollResultsInterval;60var timeout = config.timeout;61var script = config.script;62var run = config.run;63var video = config.video;64var connectivity = config.connectivity;65var label = config.label;66var mobile = config.mobile;67var firstViewOnly = config.firstViewOnly;
Using AI Code Generation
1var wpt = require('wpt');2var options = {3};4wpt.runTest(options, function(err, data) {5 if (err) {6 console.log('Error: ' + err.message);7 } else {8 console.log('Test Status: ' + data.statusCode);9 console.log('Test ID: ' + data.data.testId);10 console.log('Test URL: ' + data.data.summary);11 console.log('Test Started: ' + data.data.startedDateTime);12 console.log('Test Completed: ' + data.data.completedDateTime);13 console.log('Test First View: ' + data.data.average.firstView);14 console.log('Test Repeat View: ' + data.data.average.repeatView);15 console.log('Test Median: ' + data.data.median.firstView);16 console.log('Test Median Repeat View: ' + data.data.median.repeatView);17 console.log('Test Standard Deviation: ' + data.data.standardDeviation.firstView);18 console.log('Test Standard Deviation Repeat View: ' + data.data.standardDeviation.repeatView);19 console.log('Test Video: ' + data.data.video);20 console.log('Test Timeline: ' + data.data.timeline);21 console.log('Test Connectivity: ' + data.data.connectivity);22 console.log('Test BwDown: ' + data.data.bwDown);23 console.log('Test BwUp: ' + data.data.bwUp);24 console.log('Test Latency: ' + data.data.latency);25 console.log('Test Plr: ' + data.data.plr);26 console.log('Test Location: ' + data.data.location);27 console.log('Test Browser: ' + data.data.browser);28 console.log('Test Runs: ' + data.data.runs);29 console.log('Test First View Only:
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org','A.7eaa3a0c3c3f4a4e4e0f0e9f4b4e8b6c');3 if(err){4 console.log('error: '+err);5 }else{6 console.log('data: '+data);7 }8});9 at Object.exports._errnoException (util.js:907:11)10 at exports._exceptionWithHostPort (util.js:930:20)11 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)
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!!