Best JavaScript code snippet using wpt
helper.js
Source:helper.js
1//2// Simple Helper Functions For Testing CSS3//4(function(root) {5'use strict';6// serialize styles object and dump to dom7// appends <style id="dynamic-style"> to <head>8// setStyle("#some-selector", {"some-style" : "value"})9// setStyle({"#some-selector": {"some-style" : "value"}})10root.setStyle = function(selector, styles) {11 var target = document.getElementById('dynamic-style');12 if (!target) {13 target = document.createElement('style');14 target.id = 'dynamic-style';15 target.type = "text/css";16 document.getElementsByTagName('head')[0].appendChild(target);17 }18 var data = [];19 // single selector/styles20 if (typeof selector === 'string' && styles !== undefined) {21 data = [selector, '{', serializeStyles(styles), '}'];22 target.textContent = data.join("\n");23 return;24 }25 // map of selector/styles26 for (var key in selector) {27 if (Object.prototype.hasOwnProperty.call(selector, key)) {28 var _data = [key, '{', serializeStyles(selector[key]), '}'];29 data.push(_data.join('\n'));30 }31 }32 target.textContent = data.join("\n");33};34function serializeStyles(styles) {35 var data = [];36 for (var property in styles) {37 if (Object.prototype.hasOwnProperty.call(styles, property)) {38 var prefixedProperty = addVendorPrefix(property);39 data.push(prefixedProperty + ":" + styles[property] + ";");40 }41 }42 return data.join('\n');43}44// shorthand for computed style45root.computedStyle = function(element, property, pseudo) {46 var prefixedProperty = addVendorPrefix(property);47 return window48 .getComputedStyle(element, pseudo || null)49 .getPropertyValue(prefixedProperty);50};51// flush rendering buffer52root.reflow = function() {53 document.body.offsetWidth;54};55// merge objects56root.extend = function(target /*, ..rest */) {57 Array.prototype.slice.call(arguments, 1).forEach(function(obj) {58 Object.keys(obj).forEach(function(key) {59 target[key] = obj[key];60 });61 });62 return target;63};64// dom fixture helper ("resetting dom test elements")65var _domFixture;66var _domFixtureSelector;67root.domFixture = function(selector) {68 var fixture = document.querySelector(selector || _domFixtureSelector);69 if (!fixture) {70 throw new Error('fixture ' + (selector || _domFixtureSelector) + ' not found!');71 }72 if (!_domFixture && selector) {73 // save a copy74 _domFixture = fixture.cloneNode(true);75 _domFixtureSelector = selector;76 } else if (_domFixture) {77 // restore the copy78 var tmp = _domFixture.cloneNode(true);79 fixture.parentNode.replaceChild(tmp, fixture);80 } else {81 throw new Error('domFixture must be initialized first!');82 }83};84root.MS_PER_SEC = 1000;85/*86 * The recommended minimum precision to use for time values.87 *88 * Based on Web Animations:89 * https://w3c.github.io/web-animations/#precision-of-time-values90 */91const TIME_PRECISION = 0.0005; // ms92/*93 * Allow implementations to substitute an alternative method for comparing94 * times based on their precision requirements.95 */96root.assert_times_equal = function(actual, expected, description) {97 assert_approx_equals(actual, expected, TIME_PRECISION, description);98};99/*100 * Compare a time value based on its precision requirements with a fixed value.101 */102root.assert_time_equals_literal = (actual, expected, description) => {103 assert_approx_equals(actual, expected, TIME_PRECISION, description);104};105/**106 * Assert that CSSTransition event, |evt|, has the expected property values107 * defined by |propertyName|, |elapsedTime|, and |pseudoElement|.108 */109root.assert_end_events_equal = function(evt, propertyName, elapsedTime,110 pseudoElement = '') {111 assert_equals(evt.propertyName, propertyName);112 assert_times_equal(evt.elapsedTime, elapsedTime);113 assert_equals(evt.pseudoElement, pseudoElement);114};115/**116 * Assert that array of simultaneous CSSTransition events, |evts|, have the117 * corresponding property names listed in |propertyNames|, and the expected118 * |elapsedTimes| and |pseudoElement| members.119 *120 * |elapsedTimes| may be a single value if all events are expected to have the121 * same elapsedTime, or an array parallel to |propertyNames|.122 */123root.assert_end_event_batch_equal = function(evts, propertyNames, elapsedTimes,124 pseudoElement = '') {125 assert_equals(126 evts.length,127 propertyNames.length,128 'Test harness error: should have waited for the correct number of events'129 );130 assert_true(131 typeof elapsedTimes === 'number' ||132 (Array.isArray(elapsedTimes) &&133 elapsedTimes.length === propertyNames.length),134 'Test harness error: elapsedTimes must either be a number or an array of' +135 ' numbers with the same length as propertyNames'136 );137 if (typeof elapsedTimes === 'number') {138 elapsedTimes = Array(propertyNames.length).fill(elapsedTimes);139 }140 const testPairs = propertyNames.map((propertyName, index) => ({141 propertyName,142 elapsedTime: elapsedTimes[index]143 }));144 const sortByPropertyName = (a, b) =>145 a.propertyName.localeCompare(b.propertyName);146 evts.sort(sortByPropertyName);147 testPairs.sort(sortByPropertyName);148 for (let evt of evts) {149 const expected = testPairs.shift();150 assert_end_events_equal(151 evt,152 expected.propertyName,153 expected.elapsedTime,154 pseudoElement155 );156 }157}158/**159 * Appends a div to the document body.160 *161 * @param t The testharness.js Test object. If provided, this will be used162 * to register a cleanup callback to remove the div when the test163 * finishes.164 *165 * @param attrs A dictionary object with attribute names and values to set on166 * the div.167 */168root.addDiv = function(t, attrs) {169 var div = document.createElement('div');170 if (attrs) {171 for (var attrName in attrs) {172 div.setAttribute(attrName, attrs[attrName]);173 }174 }175 document.body.appendChild(div);176 if (t && typeof t.add_cleanup === 'function') {177 t.add_cleanup(function() {178 if (div.parentNode) {179 div.remove();180 }181 });182 }183 return div;184};185/**186 * Appends a style div to the document head.187 *188 * @param t The testharness.js Test object. If provided, this will be used189 * to register a cleanup callback to remove the style element190 * when the test finishes.191 *192 * @param rules A dictionary object with selector names and rules to set on193 * the style sheet.194 */195root.addStyle = (t, rules) => {196 const extraStyle = document.createElement('style');197 document.head.appendChild(extraStyle);198 if (rules) {199 const sheet = extraStyle.sheet;200 for (const selector in rules) {201 sheet.insertRule(selector + '{' + rules[selector] + '}',202 sheet.cssRules.length);203 }204 }205 if (t && typeof t.add_cleanup === 'function') {206 t.add_cleanup(() => {207 extraStyle.remove();208 });209 }210 return extraStyle;211};212/**213 * Promise wrapper for requestAnimationFrame.214 */215root.waitForFrame = () => {216 return new Promise(resolve => {217 window.requestAnimationFrame(resolve);218 });219};220/**221 * Returns a Promise that is resolved after the given number of consecutive222 * animation frames have occured (using requestAnimationFrame callbacks).223 *224 * @param frameCount The number of animation frames.225 * @param onFrame An optional function to be processed in each animation frame.226 */227root.waitForAnimationFrames = (frameCount, onFrame) => {228 const timeAtStart = document.timeline.currentTime;229 return new Promise(resolve => {230 function handleFrame() {231 if (onFrame && typeof onFrame === 'function') {232 onFrame();233 }234 if (timeAtStart != document.timeline.currentTime &&235 --frameCount <= 0) {236 resolve();237 } else {238 window.requestAnimationFrame(handleFrame); // wait another frame239 }240 }241 window.requestAnimationFrame(handleFrame);242 });243};244/**245 * Wrapper that takes a sequence of N animations and returns:246 *247 * Promise.all([animations[0].ready, animations[1].ready, ... animations[N-1].ready]);248 */249root.waitForAllAnimations = animations =>250 Promise.all(animations.map(animation => animation.ready));251/**252 * Utility that takes a Promise and a maximum number of frames to wait and253 * returns a new Promise that behaves as follows:254 *255 * - If the provided Promise resolves _before_ the specified number of frames256 * have passed, resolves with the result of the provided Promise.257 * - If the provided Promise rejects _before_ the specified number of frames258 * have passed, rejects with the error result of the provided Promise.259 * - Otherwise, rejects with a 'Timed out' error message. If |message| is260 * provided, it will be appended to the error message.261 */262root.frameTimeout = (promiseToWaitOn, framesToWait, message) => {263 let framesRemaining = framesToWait;264 let aborted = false;265 const timeoutPromise = new Promise(function waitAFrame(resolve, reject) {266 if (aborted) {267 resolve();268 return;269 }270 if (framesRemaining-- > 0) {271 requestAnimationFrame(() => {272 waitAFrame(resolve, reject);273 });274 return;275 }276 let errorMessage = 'Timed out waiting for Promise to resolve';277 if (message) {278 errorMessage += `: ${message}`;279 }280 reject(new Error(errorMessage));281 });282 const wrappedPromiseToWaitOn = promiseToWaitOn.then(result => {283 aborted = true;284 return result;285 });286 return Promise.race([timeoutPromise, wrappedPromiseToWaitOn]);287};...
Using AI Code Generation
1var wptw = require('wptw');2var wrappedPromiseToWaitOn = wptw.wrappedPromiseToWaitOn;3var promise = wrappedPromiseToWaitOn(function (resolve, reject) {4 setTimeout(function () {5 resolve('done');6 }, 1000);7});8promise.then(function (result) {9 console.log(result);10});11var wptw = require('wptw');12var wrappedPromiseToWaitOn = wptw.wrappedPromiseToWaitOn;13var promise = wrappedPromiseToWaitOn(function (resolve, reject) {14 setTimeout(function () {15 reject('error');16 }, 1000);17});18promise.then(function (result) {19 console.log(result);20}, function (error) {21 console.log(error);22});23var wptw = require('wptw');24var wrappedPromiseToWaitOn = wptw.wrappedPromiseToWaitOn;25var promise = wrappedPromiseToWaitOn(function (resolve, reject) {26 setTimeout(function () {27 resolve('done');28 }, 1000);29});30promise.then(function (result) {31 console.log(result);32 return wrappedPromiseToWaitOn(function (resolve, reject) {33 setTimeout(function () {34 resolve('done again');35 }, 1000);36 });37}).then(function (result) {38 console.log(result);39});40var wptw = require('wptw');41var wrappedPromiseToWaitOn = wptw.wrappedPromiseToWaitOn;42var promise = wrappedPromiseToWaitOn(function (resolve, reject) {43 setTimeout(function () {44 resolve('done');45 }, 1000);46});47promise.then(function (result) {48 console.log(result);49 return wrappedPromiseToWaitOn(function (resolve, reject) {50 setTimeout(function () {51 reject('error again');52 }, 1000);53 });54}).then(function (result) {55 console.log(result);56}, function (error) {57 console.log(error);58});
Using AI Code Generation
1var wptools = require('wptools');2var wp = wptools.page('Albert Einstein');3wp.get(function(err, response) {4 if (err) {5 console.log(err);6 }7 else {8 console.log(response);9 }10});11var wptools = require('wptools');12var wp = wptools.page('Albert Einstein');13wp.get(function(err, response) {14 if (err) {15 console.log(err);16 }17 else {18 console.log(response);19 }20});21 at errnoException (child_process.js:988:11)22 at Process.ChildProcess._handle.onexit (child_process.js:779:34)
Using AI Code Generation
1const wptw = require('wrapped-promise-to-wait-on');2const wrappedPromiseToWaitOn = wptw.wrappedPromiseToWaitOn;3var promise = new Promise(function(resolve, reject) {4 setTimeout(function() {5 resolve('foo');6 }, 300);7});8var wrappedPromise = wrappedPromiseToWaitOn(promise);9setTimeout(function() {10 wrappedPromise.then(function(value) {11 console.log(value);12 });13}, 100);14const WPTW = require('wrapped-promise-to-wait-on');15const wptw = new WPTW();16var promise = new Promise(function(resolve, reject) {17 setTimeout(function() {18 resolve('foo');19 }, 300);20});21var wrappedPromise = wptw.wrappedPromiseToWaitOn(promise);22setTimeout(function() {23 wrappedPromise.then(function(value) {24 console.log(value);25 });26}, 100);27const WPTW = require('wrapped-promise-to-wait-on');28const wptw = new WPTW();29var promise = new Promise(function(resolve, reject) {30 setTimeout(function() {31 resolve('foo');32 }, 300);33});34var wrappedPromise = wptw.wrappedPromiseToWaitOn(promise);35setTimeout(function() {36 wrappedPromise.then(function(value) {37 console.log(value);38 });39}, 100);40const WPTW = require('wrapped-promise-to-wait-on');41const wptw = new WPTW();42var promise = new Promise(function(resolve, reject) {43 setTimeout(function() {44 resolve('foo');45 }, 300);46});47var wrappedPromise = wptw.wrappedPromiseToWaitOn(promise);48setTimeout(function() {49 wrappedPromise.then(function(value) {50 console.log(value);51 });52}, 100);
Using AI Code Generation
1var wptools = require('wptools');2var wpt = new wptools('Barack Obama');3wpt.get(function(err, resp) {4 if (err) {5 console.log(err);6 } else {7 console.log(resp);8 }9});10var wptools = require('wptools');11var wpt = new wptools('Barack Obama');12wpt.get(function(err, resp) {13 if (err) {14 console.log(err);15 } else {16 console.log(resp);17 }18});19var wptools = require('wptools');20var wpt = new wptools('Barack Obama');21wpt.get(function(err, resp) {22 if (err) {23 console.log(err);24 } else {25 console.log(resp);26 }27});28var wptools = require('wptools');29var wpt = new wptools('Barack Obama');30wpt.get(function(err, resp) {31 if (err) {32 console.log(err);33 } else {34 console.log(resp);35 }36});37var wptools = require('wptools');38var wpt = new wptools('Barack Obama');39wpt.get(function(err, resp) {40 if (err) {41 console.log(err);42 } else {43 console.log(resp);44 }45});46var wptools = require('wptools');47var wpt = new wptools('Barack Obama');48wpt.get(function(err, resp) {49 if (err) {50 console.log(err);51 } else {52 console.log(resp);53 }54});55var wptools = require('wptools');56var wpt = new wptools('Barack Obama');57wpt.get(function(err
Using AI Code Generation
1var wrappedPromiseToWaitOn = require('wptools').wrappedPromiseToWaitOn;2var wp = require('wptools')();3wp.page('Albert Einstein').then(function(page) {4 return page.get();5}).then(function(page) {6 console.log(page);7}).catch(function(err) {8 console.log(err);9});10var wrappedPromiseToWaitOn = require('wptools').wrappedPromiseToWaitOn;11var wp = require('wptools')();12wp.page('Albert Einstein').then(function(page) {13 return page.get();14}).then(function(page) {15 console.log(page);16}).catch(function(err) {17 console.log(err);18});19var wrappedPromiseToWaitOn = require('wptools').wrappedPromiseToWaitOn;20var wp = require('wptools')();21wp.page('Albert Einstein').then(function(page) {22 return page.get();23}).then(function(page) {24 console.log(page);25}).catch(function(err) {26 console.log(err);27});28var wrappedPromiseToWaitOn = require('wptools').wrappedPromiseToWaitOn;29var wp = require('wptools')();30wp.page('Albert Einstein').then(function(page) {31 return page.get();32}).then(function(page) {33 console.log(page);34}).catch(function(err) {35 console.log(err);36});37var wrappedPromiseToWaitOn = require('wptools').wrappedPromiseToWaitOn;38var wp = require('wptools')();39wp.page('Albert Einstein').then(function(page) {40 return page.get();41}).then(function(page) {42 console.log(page);43}).catch(function(err) {44 console.log(err);45});46var wrappedPromiseToWaitOn = require('wptools').wrappedPromiseToWaitOn;47var wp = require('wptools')();48wp.page('Albert Einstein').then(function(page) {49 return page.get();50}).then
Using AI Code Generation
1var wptools = require('wptools');2var wiki = wptools.page('Barack Obama');3wiki.get(function(err,resp){4 console.log(resp);5})6var wptools = require('wptools');7var wiki = wptools.page('Barack Obama');8wiki.get(function(err,resp){9 console.log(resp);10})11var wptools = require('wptools');12var wiki = wptools.page('Barack Obama');13wiki.get(function(err,resp){14 console.log(resp);15})16var wptools = require('wptools');17var wiki = wptools.page('Barack Obama');18wiki.get(function(err,resp){19 console.log(resp);20})21var wptools = require('wptools');22var wiki = wptools.page('Barack Obama');23wiki.get(function(err,resp){24 console.log(resp);25})26var wptools = require('wptools');27var wiki = wptools.page('Barack Obama');28wiki.get(function(err,resp){29 console.log(resp);30})31var wptools = require('wptools');32var wiki = wptools.page('Barack Obama');33wiki.get(function(err,resp){34 console.log(resp);35})36var wptools = require('wptools
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!!