Best JavaScript code snippet using taiko
extendable-event-async-waituntil.js
Source:extendable-event-async-waituntil.js  
1// This worker calls waitUntil() and respondWith() asynchronously and2// reports back to the test whether they threw.3//4// These test cases are confusing. Bear in mind that the event is active5// (calling waitUntil() is allowed) if:6// * The pending promise count is not 0, or7// * The event dispatch flag is set.8// Controlled by 'init'/'done' messages.9var resolveLockPromise;10var port;11self.addEventListener('message', function(event) {12    var waitPromise;13    var resolveTestPromise;14    switch (event.data.step) {15      case 'init':16        event.waitUntil(new Promise((res) => { resolveLockPromise = res; }));17        port = event.data.port;18        break;19      case 'done':20        resolveLockPromise();21        break;22      // Throws because waitUntil() is called in a task after event dispatch23      // finishes.24      case 'no-current-extension-different-task':25        async_task_waituntil(event).then(reportResultExpecting('InvalidStateError'));26        break;27      // OK because waitUntil() is called in a microtask that runs after the28      // event handler runs, while the event dispatch flag is still set.29      case 'no-current-extension-different-microtask':30        async_microtask_waituntil(event).then(reportResultExpecting('OK'));31        break;32      // OK because the second waitUntil() is called while the first waitUntil()33      // promise is still pending.34      case 'current-extension-different-task':35        event.waitUntil(new Promise((res) => { resolveTestPromise = res; }));36        async_task_waituntil(event).then(reportResultExpecting('OK')).then(resolveTestPromise);37        break;38      // OK because all promises involved resolve "immediately", so the second39      // waitUntil() is called during the microtask checkpoint at the end of40      // event dispatching, when the event dispatch flag is still set.41      case 'during-event-dispatch-current-extension-expired-same-microtask-turn':42        waitPromise = Promise.resolve();43        event.waitUntil(waitPromise);44        waitPromise.then(() => { return sync_waituntil(event); })45          .then(reportResultExpecting('OK'))46        break;47      // OK for the same reason as above.48      case 'during-event-dispatch-current-extension-expired-same-microtask-turn-extra':49        waitPromise = Promise.resolve();50        event.waitUntil(waitPromise);51        waitPromise.then(() => { return async_microtask_waituntil(event); })52          .then(reportResultExpecting('OK'))53        break;54      // OK because the pending promise count is decremented in a microtask55      // queued upon fulfillment of the first waitUntil() promise, so the second56      // waitUntil() is called while the pending promise count is still57      // positive.58      case 'after-event-dispatch-current-extension-expired-same-microtask-turn':59        waitPromise = makeNewTaskPromise();60        event.waitUntil(waitPromise);61        waitPromise.then(() => { return sync_waituntil(event); })62          .then(reportResultExpecting('OK'))63        break;64      // Throws because the second waitUntil() is called after the pending65      // promise count was decremented to 0.66      case 'after-event-dispatch-current-extension-expired-same-microtask-turn-extra':67        waitPromise = makeNewTaskPromise();68        event.waitUntil(waitPromise);69        waitPromise.then(() => { return async_microtask_waituntil(event); })70          .then(reportResultExpecting('InvalidStateError'))71        break;72      // Throws because the second waitUntil() is called in a new task, after73      // first waitUntil() promise settled and the event dispatch flag is unset.74      case 'current-extension-expired-different-task':75        event.waitUntil(Promise.resolve());76        async_task_waituntil(event).then(reportResultExpecting('InvalidStateError'));77        break;78      case 'script-extendable-event':79        self.dispatchEvent(new ExtendableEvent('nontrustedevent'));80        break;81    }82    event.source.postMessage('ACK');83  });84self.addEventListener('fetch', function(event) {85  const path = new URL(event.request.url).pathname;86  const step = path.substring(path.lastIndexOf('/') + 1);87  let response;88  switch (step) {89    // OK because waitUntil() is called while the respondWith() promise is still90    // unsettled, so the pending promise count is positive.91    case 'pending-respondwith-async-waituntil':92      var resolveFetch;93      response = new Promise((res) => { resolveFetch = res; });94      event.respondWith(response);95      async_task_waituntil(event)96        .then(reportResultExpecting('OK'))97        .then(() => { resolveFetch(new Response('OK')); });98      break;99    // OK because all promises involved resolve "immediately", so waitUntil() is100    // called during the microtask checkpoint at the end of event dispatching,101    // when the event dispatch flag is still set.102    case 'during-event-dispatch-respondwith-microtask-sync-waituntil':103      response = Promise.resolve(new Response('RESP'));104      event.respondWith(response);105      response.then(() => { return sync_waituntil(event); })106        .then(reportResultExpecting('OK'));107      break;108    // OK because all promises involved resolve "immediately", so waitUntil() is109    // called during the microtask checkpoint at the end of event dispatching,110    // when the event dispatch flag is still set.111    case 'during-event-dispatch-respondwith-microtask-async-waituntil':112      response = Promise.resolve(new Response('RESP'));113      event.respondWith(response);114      response.then(() => { return async_microtask_waituntil(event); })115        .then(reportResultExpecting('OK'));116      break;117    // OK because the pending promise count is decremented in a microtask queued118    // upon fulfillment of the respondWith() promise, so waitUntil() is called119    // while the pending promise count is still positive.120    case 'after-event-dispatch-respondwith-microtask-sync-waituntil':121      response = makeNewTaskPromise().then(() => {return new Response('RESP');});122      event.respondWith(response);123      response.then(() => { return sync_waituntil(event); })124        .then(reportResultExpecting('OK'));125      break;126    // Throws because waitUntil() is called after the pending promise count was127    // decremented to 0.128    case 'after-event-dispatch-respondwith-microtask-async-waituntil':129      response = makeNewTaskPromise().then(() => {return new Response('RESP');});130      event.respondWith(response);131      response.then(() => { return async_microtask_waituntil(event); })132        .then(reportResultExpecting('InvalidStateError'))133      break;134  }135});136self.addEventListener('nontrustedevent', function(event) {137    sync_waituntil(event).then(reportResultExpecting('InvalidStateError'));138  });139function reportResultExpecting(expectedResult) {140  return function (result) {141    port.postMessage({result : result, expected: expectedResult});142    return result;143  };144}145function sync_waituntil(event) {146  return new Promise((res, rej) => {147    try {148      event.waitUntil(Promise.resolve());149      res('OK');150    } catch (error) {151      res(error.name);152    }153  });154}155function async_microtask_waituntil(event) {156  return new Promise((res, rej) => {157    Promise.resolve().then(() => {158      try {159        event.waitUntil(Promise.resolve());160        res('OK');161      } catch (error) {162        res(error.name);163      }164    });165  });166}167function async_task_waituntil(event) {168  return new Promise((res, rej) => {169    setTimeout(() => {170      try {171        event.waitUntil(Promise.resolve());172        res('OK');173      } catch (error) {174        res(error.name);175      }176    }, 0);177  });178}179// Returns a promise that settles in a separate task.180function makeNewTaskPromise() {181  return new Promise(resolve => {182    setTimeout(resolve, 0);183  });...Using AI Code Generation
1const { openBrowser, goto, write, closeBrowser } = require('taiko');2(async () => {3    try {4        await openBrowser();5        await goto("google.com");6        await write("Taiko", into(textBox("Search")));7    } catch (e) {8        console.error(e);9    } finally {10        await closeBrowser();11    }12})();Using AI Code Generation
1const { openBrowser, goto, write, click, button, closeBrowser, waitFor, waitUntil } = require('taiko');2(async () => {3    try {4        await openBrowser({headless:false});5        await write("Taiko",into(textBox({id:'lst-ib'})));6        await click(button({id:'gbqfbb'}));7        await waitFor(2000);8        await waitUntil(async () => {9            return (await text('Taiko').exists());10        }, 2000);11        await click(text('Taiko'));12        await waitFor(2000);13        await click(text('Taiko'));14        await waitFor(2000);15        await click(text('Taiko'));16        await waitFor(2000);17    } catch (e) {18        console.error(e);19    } finally {20        await closeBrowser();21    }22})();Using AI Code Generation
1const { openBrowser, goto, write, click, closeBrowser, into, $, waitUntil } = require('taiko');2(async () => {3    try {4        await openBrowser();5        await write("Taiko", into($("#lst-ib")));6        await click("Google Search");7        await waitUntil(async () => {8            return (await $("h3").exists());9        }, 5000);10    } catch (e) {11        console.error(e);12    } finally {13        await closeBrowser();14    }15})();16const { openBrowser, goto, write, click, closeBrowser, into, $, waitUntil } = require('taiko');17(async () => {18    try {19        await openBrowser();20        await write("Taiko", into($("#lst-ib")));21        await click("Google Search");22        await waitUntil(async () => {23            return !(await $("h3").exists());24        }, 5000);25    } catch (e) {26        console.error(e);27    } finally {28        await closeBrowser();29    }30})();31const { openBrowser, goto, write, click, closeBrowser, into, $, waitUntil } = require('taiko');32(async () => {Using AI Code Generation
1const { openBrowser, goto, write, click, closeBrowser, waitFor, button, link } = require('taiko');2(async () => {3    try {4        await openBrowser();5        await write("Taiko", into("Search"));6        await click("Google Search");7        await waitFor(3000);8        await click(link("Taiko"));9        await click("Get Started");10        await waitFor(3000);11        await click(link("API"));12        await waitFor(3000);13        await click(link("waitUntil"));14        await waitFor(3000);15        await click(button("Run"));16        await waitFor(3000);17    } catch (e) {18        console.error(e);19    } finally {20        await closeBrowser();21    }22})();Using AI Code Generation
1const { openBrowser, goto, write, closeBrowser, $, click, into, text, waitFor } = require('taiko');2(async () => {3    try {4        await openBrowser();5        await click("Login");6        await write("admin", into("Username"));7        await write("admin", into("Password"));8        await click("Login");9        await waitFor(5000);10        await click("New");11        await write("Test", into("Title"));12        await write("Test", into("Description"));13        await click("Save");14        await waitFor(5000);15        await click("Logout");16    } catch (e) {17        console.error(e);18    } finally {19        await closeBrowser();20    }21})();22const { openBrowser, goto, write, closeBrowser, $, click, into, text, waitFor } = require('taiko');23(async () => {24    try {25        await openBrowser();26        await click("Login");27        await write("admin", into("Username"));28        await write("admin", into("Password"));29        await click("Login");30        await waitFor(5000);31        await click("New");32        await write("Test", into("Title"));33        await write("Test", into("Description"));34        await click("Save");35        await waitFor(5000);36        await click("Logout");37    } catch (e) {38        console.error(e);39    } finally {40        await closeBrowser();41    }42})();43const { openBrowser, goto, write, closeBrowser, $, click, into, text, waitFor } = require('taiko');44(async () => {45    try {46        await openBrowser();47        await click("Login");48        await write("admin", into("Username"));49        await write("admin", into("Password"));50        await click("Login");51        await waitFor(5000);52        await click("New");53        await write("Test", into("Title"));54        await write("Test", into("Description"));55        await click("Save");56        await waitFor(5000);57        await click("Logout");58    } catch (e) {59        console.error(eUsing AI Code Generation
1const { openBrowser, goto, write, click, closeBrowser, waitFor, below, $, link, button, text, toRightOf, toLeftOf, near, image, focus, textBox, into, dropDown, evaluate, accept, dismiss, waitUntil } = require('taiko');2(async () => {3    try {4        await openBrowser({headless:false});5        await click("Taiko - Test Automation Framework");6        await click("Getting Started");7        await click("Installation");8        await click("Installation");9        await click("Installation");Using AI Code Generation
1const { openBrowser, goto, click, text, closeBrowser, write, toRightOf, button, link, $, waitFor, waitUntil, into, focus, textBox, image, toLeftOf, below, above, near, to, rightOf, intercept, evaluate, accept, dismiss, reload, clear, press, screenshot, currentURL, hover, doubleClick, dragAndDrop, highlight, scrollDown, scrollUp, scrollLeft, scrollRight, emulate, setConfig, setViewPort, setCookie, deleteCookie, Cookies, select } = require('taiko');2(async () => {3    try {4        await openBrowser({headless:false});5        await click(link("Dynamic Loading"));6        await click(link("Example 1: Element on page that is hidden"));7        await click(button("Start"));8        await waitUntil(async () => {9            return await text("Hello World!").exists();10        }, 10000);11        await click(link("Example 2: Element rendered after the fact"));12        await click(button("Start"));13        await waitUntil(async () => {14            return await text("Hello World!").exists();15        }, 10000);16        await closeBrowser();17    } catch (error) {18        console.error(error);19    }20})();21const { openBrowser, goto, click, text, closeBrowser, write, toRightOf, button, link, $, waitFor, waitUntil, into, focus, textBox, image, toLeftOf, below, above, near, to, rightOf, intercept, evaluate, accept, dismiss, reload, clear, press, screenshot, currentURL, hover, doubleClick, dragAndDrop, highlight, scrollDown, scrollUp, scrollLeft, scrollRight, emulate, setConfig, setViewPort, setCookie, deleteCookie, Cookies, select } = require('taiko');22(async () => {23    try {24        await openBrowser({headless:false});25        await click(link("Dynamic Loading"));26        await click(link("Example 1: Element on page that is hidden"));27        await click(button("Start"));28        await waitFor(10000);29        await click(link("Example 2: Element rendered after the fact"));30        await click(button("Start"));Using AI Code Generation
1const { openBrowser, goto, closeBrowser, text, link, button, write, $, waitFor, click, into, waitUntil, inputField, press, toRightOf, textBox, toLeftOf, evaluate } = require('taiko');2(async () => {3    try {4        await openBrowser({ headless: false });5        await write("Taiko", into(textBox(toRightOf("Google Search"))));6        await press("Enter");7        await click(link("Taiko"), below(text("Taiko is an open source test automation framework for ...")));8        await click("API");9        await click(link("openBrowser"));10        await waitUntil(async () => {11            let text = await evaluate(() => document.querySelector('body').innerText);12            return text.includes('openBrowser');13        });14        await click("openBrowser");15        await click(link("openBrowser"));16        await click("openBrowser");17        await click(linLearn 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!!
