Best JavaScript code snippet using wpt
update-with-retry.test.ts
Source:update-with-retry.test.ts  
...405    clock.next();406    clock.restore();407    // It turns out we need to wait quiet a few frames to be sure the completion408    // would happen if we hadn't canceled things.409    await waitForAnimationFrames(8);410    assert.isFalse(completeCalled);411  });412  it('should allow canceling the retries', async () => {413    fetchMock.mock('end:jpdict-rc-en-version.json', VERSION_INFO);414    fetchMock.once('end:.ljson', 404);415    fetchMock.mock(416      'end:kanji-rc-en-4.0.0.ljson',417      `{"type":"header","version":{"major":4,"minor":0,"patch":0,"databaseVersion":"175","dateOfCreation":"2019-07-09"},"records":0}418`419    );420    fetchMock.mock(421      'end:radicals-rc-en-4.0.0.ljson',422      `{"type":"header","version":{"major":4,"minor":0,"patch":0,"dateOfCreation":"2019-09-06"},"records":0}423`424    );425    // Wait for first error426    const clock = sinon.useFakeTimers({427      toFake: ['setTimeout', 'clearTimeout'],428    });429    let completeCalled = false;430    await new Promise((resolve) => {431      updateWithRetry({432        db,433        series: 'kanji',434        lang: 'en',435        onUpdateComplete: () => {436          completeCalled = true;437        },438        onUpdateError: resolve,439      });440    });441    // Then cancel442    await cancelUpdateWithRetry({ db, series: 'kanji' });443    // Then make sure that the completion doesn't happen444    clock.next();445    clock.restore();446    // It turns out we need to wait quiet a few frames to be sure the completion447    // would happen if we hadn't canceled things.448    await waitForAnimationFrames(8);449    assert.isFalse(completeCalled);450  });451  it('should cancel the retries when the database is deleted', async () => {452    fetchMock.mock('end:jpdict-rc-en-version.json', VERSION_INFO);453    fetchMock.once('end:.ljson', 404);454    fetchMock.mock(455      'end:kanji-rc-en-4.0.0.ljson',456      `{"type":"header","version":{"major":4,"minor":0,"patch":0,"databaseVersion":"175","dateOfCreation":"2019-07-09"},"records":0}457`458    );459    fetchMock.mock(460      'end:radicals-rc-en-4.0.0.ljson',461      `{"type":"header","version":{"major":4,"minor":0,"patch":0,"dateOfCreation":"2019-09-06"},"records":0}462`463    );464    // Wait for first error465    const clock = sinon.useFakeTimers({466      toFake: ['setTimeout', 'clearTimeout'],467    });468    let completeCalled = false;469    await new Promise((resolve) => {470      updateWithRetry({471        db,472        series: 'kanji',473        lang: 'en',474        onUpdateComplete: () => {475          completeCalled = true;476        },477        onUpdateError: resolve,478      });479    });480    // Then destroy database481    await db.destroy();482    // Then make sure that the completion doesn't happen483    clock.next();484    clock.restore();485    await waitForAnimationFrames(15); // We seem to need at least ~15486    assert.isFalse(completeCalled);487  });488  it('should reset the timeout after each successful download', async () => {489    fetchMock.mock('end:jpdict-rc-en-version.json', VERSION_INFO);490    fetchMock.mock('end:.ljson', 404, { repeat: 2 });491    fetchMock.mock(492      'end:kanji-rc-en-4.0.0.ljson',493      `{"type":"header","version":{"major":4,"minor":0,"patch":0,"databaseVersion":"175","dateOfCreation":"2019-07-09"},"records":0}494`495    );496    // Make radical file fail only once497    let callCount = 0;498    fetchMock.mock('end:radicals-rc-en-4.0.0.ljson', () => {499      if (callCount++) {500        return `{"type":"header","version":{"major":4,"minor":0,"patch":0,"dateOfCreation":"2019-09-06"},"records":0}501`;502      } else {503        return 404;504      }505    });506    const clock = sinon.useFakeTimers({507      now: Date.now(),508      toFake: ['setTimeout'],509    });510    const errors: Array<{511      error: Error;512      retryInterval?: number;513      retryCount?: number;514    }> = [];515    await new Promise<void>((resolve, reject) => {516      updateWithRetry({517        db,518        series: 'kanji',519        lang: 'en',520        onUpdateComplete: resolve,521        onUpdateError: ({ error, nextRetry, retryCount }) => {522          errors.push({523            error,524            retryInterval: nextRetry525              ? nextRetry.getTime() - Date.now()526              : undefined,527            retryCount,528          });529          if (!nextRetry) {530            reject(error);531          } else {532            clock.runAllAsync();533          }534        },535      });536    });537    clock.restore();538    assert.lengthOf(errors, 3);539    // The first two failures should have increasing retry intervals540    assert.isBelow(errors[0].retryInterval!, errors[1].retryInterval!);541    // The third failure should have a less (or equal) interval to the second542    // one543    assert.isAtMost(errors[2].retryInterval!, errors[1].retryInterval!);544    // The retry count should be reset too545    assert.deepEqual(546      errors.map((e) => e.retryCount),547      [0, 1, 0]548    );549  });550  it('should retry when saving to the database fails', async () => {551    fetchMock.mock('end:jpdict-rc-en-version.json', VERSION_INFO);552    fetchMock.mock(553      'end:kanji-rc-en-4.0.0.ljson',554      `{"type":"header","version":{"major":4,"minor":0,"patch":0,"databaseVersion":"175","dateOfCreation":"2019-07-09"},"records":0}555{"c":"ã","r":{},"m":[],"rad":{"x":1},"refs":{"nelson_c":265,"halpern_njecd":2028},"misc":{"sc":6}}556`557    );558    fetchMock.mock(559      'end:radicals-rc-en-4.0.0.ljson',560      `{"type":"header","version":{"major":4,"minor":0,"patch":0,"dateOfCreation":"2019-09-06"},"records":0}561`562    );563    const stub = sinon.stub(db, 'update');564    stub.onFirstCall().throws('ConstraintError');565    stub.onSecondCall().throws('ConstraintError');566    await new Promise<void>((resolve, reject) => {567      updateWithRetry({568        db,569        series: 'kanji',570        lang: 'en',571        onUpdateComplete: resolve,572        onUpdateError: ({ error }) => reject(error),573      });574    });575  });576  it('should give up after saving to the database fails too many times', async () => {577    fetchMock.mock('end:jpdict-rc-en-version.json', VERSION_INFO);578    fetchMock.mock(579      'end:kanji-rc-en-4.0.0.ljson',580      `{"type":"header","version":{"major":4,"minor":0,"patch":0,"databaseVersion":"175","dateOfCreation":"2019-07-09"},"records":0}581{"c":"ã","r":{},"m":[],"rad":{"x":1},"refs":{"nelson_c":265,"halpern_njecd":2028},"misc":{"sc":6}}582`583    );584    fetchMock.mock(585      'end:radicals-rc-en-4.0.0.ljson',586      `{"type":"header","version":{"major":4,"minor":0,"patch":0,"dateOfCreation":"2019-09-06"},"records":0}587`588    );589    const constraintError = new Error('Constraint error');590    constraintError.name = 'ConstraintError';591    // We need to actually stub out the store method since we want the DB592    // update state to reach 'updatingdb' since we want to test that when593    // we reach that condition we DON'T clear the retryCount.594    const stub = sinon.stub(db.store, 'bulkUpdateTable');595    stub.throws(constraintError);596    const errors: Array<Error> = [];597    const updateResult = new Promise<void>((resolve, reject) => {598      updateWithRetry({599        db,600        series: 'kanji',601        lang: 'en',602        onUpdateComplete: resolve,603        onUpdateError: ({ error, nextRetry }) => {604          errors.push(error);605          if (!nextRetry) {606            reject(error);607          }608        },609      });610    });611    await assert.isRejected(updateResult, constraintError);612    // Wait a moment to check there are no further errors reported613    await waitForAnimationFrames(1);614    assert.lengthOf(errors, 1);615  });616});617function waitForAnimationFrames(frameCount: number): Promise<void> {618  return new Promise((resolve) => {619    function handleFrame() {620      if (--frameCount <= 0) {621        resolve();622      } else {623        requestAnimationFrame(handleFrame);624      }625    }626    requestAnimationFrame(handleFrame);627  });...utils.js
Source:utils.js  
1function waitForAnimationFrames(count) {2  return new Promise(resolve => {3    if (count-- <= 0) {4      resolve();5    } else {6      requestAnimationFrame(() => {7        waitForAnimationFrames(count).then(resolve);8      });9    }10  });11}12// Asserts that there is currently no FCP reported. Pass t to add some wait, in case CSS is loaded13// and FCP is incorrectly fired afterwards.14async function assertNoFirstContentfulPaint(t) {15  await waitForAnimationFrames(3);16  assert_equals(performance.getEntriesByName('first-contentful-paint').length, 0, 'First contentful paint marked too early. ');17}18// Function that is resolved once FCP is reported, using PerformanceObserver. It rejects after a long19// wait time so that failing tests don't timeout.20async function assertFirstContentfulPaint(t) {21  return new Promise(resolve  => {22    function checkFCP() {23      if (performance.getEntriesByName('first-contentful-paint').length === 1) {24        resolve();25      } else {26        requestAnimationFrame(checkFCP)27      }28    }29    t.step(checkFCP);...Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.runTest(url, {4}, function(err, data) {5    if (err) {6        console.log(err);7    } else {8        console.log(data);9        wpt.waitForTestComplete(data.data.testId, function(err, data) {10            if (err) {11                console.log(err);12            } else {13                console.log(data);14                wpt.getTestResults(data.data.testId, function(err, data) {15                    if (err) {16                        console.log(err);17                    } else {18                        console.log(data);19                    }20                });21            }22        });23    }24});Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3}, function(err, data) {4    if (err) {5        console.log(err);6    } else {7        console.log(data);8        wpt.waitForTestComplete(data.data.testId, function(err, data) {9            if (err) {10                console.log(err);11            } else {12                console.log(data);13                wpt.getVideo(data.data.testId, function(err, data) {14                    if (err) {15                        console.log(err);16                    } else {17                        console.log(data);18                    }19                });20            }21        });22    }23});24var wpt = require('webpagetest');25var wpt = new WebPageTest('www.webpagetest.org');26}, function(err, data) {27    if (err) {28        console.log(err);29    } else {30        console.log(data);31        wpt.waitForTestComplete(data.data.testId, function(err, data) {32            if (err) {33                console.log(err);34            } else {35                console.log(data);36                wpt.getVideo(data.data.testId, function(err, data) {37                    if (err) {38                        console.log(err);39                    } else {40                        console.log(data);41                    }42                });43            }44        });45    }46});47var wpt = require('webpagetest');48var wpt = new WebPageTest('www.webpagetest.orgUsing AI Code Generation
1var wptools = require('wptools');2var page = wptools.createPage();3    if (status !== 'success') {4        console.log('Unable to access network');5    } else {6        page.waitForAnimationFrames(2, function() {7            page.render('google.png');8            page.close();9        });10    }11});12var wptools = require('wptools');13var page = wptools.createPage();14    if (status !== 'success') {15        console.log('Unable to access network');16    } else {17        page.waitFor(2000, function() {18            page.render('google.png');19            page.close();20        });21    }22});23var wptools = require('wptools');24var page = wptools.createPage();25    if (status !== 'success') {26        console.log('Unable to access network');27    } else {28        page.waitForEvent('onLoadFinished', function() {29            page.render('google.png');30            page.close();31        });32    }33});Using AI Code Generation
1waitForAnimationFrames(10, function() {2  console.log("10 frames have been rendered");3});4function waitForAnimationFrames(frames, callback) {5  var frameCount = 0;6  var raf = window.requestAnimationFrame;7  var cancel = window.cancelAnimationFrame;8  function onFrame() {9    frameCount++;10    if (frameCount === frames) {11      cancel(handle);12      callback();13    } else {14      handle = raf(onFrame);15    }16  }17  var handle = raf(onFrame);18}Using AI Code Generation
1var wptdriver = require('wptdriver');2wptdriver.waitForAnimationFrames(5);3var wptdriver = require('wptdriver');4wptdriver.waitForAnimationFrames(5);5var wptdriver = require('wptdriver');6wptdriver.waitForAnimationFrames(5);7var wptdriver = require('wptdriver');8wptdriver.waitForAnimationFrames(5);9var wptdriver = require('wptdriver');10wptdriver.waitForAnimationFrames(5);11var wptdriver = require('wptdriver');12wptdriver.waitForAnimationFrames(5);13var wptdriver = require('wptdriver');14wptdriver.waitForAnimationFrames(5);15var wptdriver = require('wptdriver');16wptdriver.waitForAnimationFrames(5);17var wptdriver = require('wptdriver');18wptdriver.waitForAnimationFrames(5);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!!
