How to use cleanUpListenersOnClient method in taiko

Best JavaScript code snippet using taiko

connection.js

Source:connection.js Github

copy

Full Screen

1const { defaultConfig } = require('./config');2const { eventHandler } = require('./eventBus');3const { isPromise } = require('./helper');4const { logEvent } = require('./logger');5const { errorMessageForBrowserProcessCrash, closeBrowser } = require('./browserLauncher');6const targetHandler = require('./handlers/targetHandler');7const pageHandler = require('./handlers/pageHandler');8const emulationHandler = require('./handlers/emulationHandler');9const cri = require('chrome-remote-interface');10const isReachable = require('is-reachable');11const numRetries = defaultConfig.criConnectionRetries;12const { pluginHooks } = require('./plugins');13let overlay, security, _client, page, network, dom;14const createProxyForCDPDomain = (cdpClient, cdpDomainName) => {15 const cdpDomain = cdpClient[cdpDomainName];16 const cdpDomainProxy = new Proxy(cdpDomain, {17 get: (target, name) => {18 const domainApi = target[name];19 if (typeof domainApi === 'function') {20 return async (...args) => {21 return await new Promise((resolve, reject) => {22 eventHandler.removeAllListeners('browserCrashed');23 eventHandler.on('browserCrashed', () => {24 if (_client) {25 _client.removeAllListeners();26 }27 _client = null;28 reject();29 });30 let res = domainApi.apply(null, args);31 if (isPromise(res)) {32 res.then(resolve).catch(reject);33 } else {34 resolve(res);35 }36 }).catch((e) => {37 if (e.message.match(/WebSocket is not open: readyState 3/i)) {38 errorMessageForBrowserProcessCrash();39 }40 throw e;41 });42 };43 } else {44 return domainApi;45 }46 },47 });48 cdpClient[cdpDomainName] = cdpDomainProxy;49 return cdpClient[cdpDomainName];50};51const initCRIProperties = (c) => {52 page = createProxyForCDPDomain(c, 'Page');53 network = createProxyForCDPDomain(c, 'Network');54 createProxyForCDPDomain(c, 'Runtime');55 createProxyForCDPDomain(c, 'Input');56 dom = createProxyForCDPDomain(c, 'DOM');57 overlay = createProxyForCDPDomain(c, 'Overlay');58 security = createProxyForCDPDomain(c, 'Security');59 createProxyForCDPDomain(c, 'Browser');60 createProxyForCDPDomain(c, 'Target');61 createProxyForCDPDomain(c, 'Emulation');62 _client = c;63};64const initCRI = async (target, n, options = {}) => {65 try {66 ({ target, options } = await pluginHooks.preConnectionHook(target, options));67 var c = await cri({68 target,69 host: defaultConfig.host,70 port: defaultConfig.port,71 alterPath: defaultConfig.alterPath,72 local: defaultConfig.local,73 });74 const promises = [];75 eventHandler.on('handlerActingOnNewSession', (promise) => {76 promises.push(promise);77 });78 initCRIProperties(c);79 const domainEnablePromises = [network.enable(), page.enable(), dom.enable(), security.enable()];80 if (!defaultConfig.firefox) {81 domainEnablePromises.push(overlay.enable());82 }83 await Promise.all(domainEnablePromises);84 _client.on('disconnect', reconnect);85 // Should be emitted after enabling all domains. All handlers can then perform any action on domains properly.86 eventHandler.emit('createdSession', _client, target);87 if (defaultConfig.ignoreSSLErrors) {88 security.setIgnoreCertificateErrors({ ignore: true });89 }90 defaultConfig.device = process.env.TAIKO_EMULATE_DEVICE;91 if (defaultConfig.device) {92 emulationHandler.emulateDevice(defaultConfig.device);93 }94 await Promise.all(promises);95 eventHandler.removeAllListeners('handlerActingOnNewSession');96 logEvent('Session Created');97 return _client;98 } catch (error) {99 logEvent(error);100 if (n < 2) {101 throw error;102 }103 return new Promise((r) => setTimeout(r, 100)).then(104 async () => await initCRI(target, n - 1, options),105 );106 }107};108const connect_to_cri = async (target, options = {}) => {109 if (_client && _client._ws.readyState === 1) {110 if (!defaultConfig.firefox) {111 await network.setRequestInterception({112 patterns: [],113 });114 }115 _client.removeAllListeners();116 }117 var tgt = target || (await targetHandler.waitForTargetToBeCreated(numRetries));118 return initCRI(tgt, numRetries, options);119};120const closeConnection = async (promisesToBeResolvedBeforeCloseBrowser) => {121 if (_client) {122 // remove listeners other than JS dialog for beforeUnload on client first to stop executing them when closing123 await _client.removeAllListeners();124 pageHandler.addJavascriptDialogOpeningListener();125 //TODO: Remove check once fixed https://bugs.chromium.org/p/chromium/issues/detail?id=1147809126 if (!defaultConfig.firefox && !(process.platform == 'win32' && defaultConfig.headful)) {127 await pageHandler.closePage();128 await new Promise((resolve) => {129 let timeout = setTimeout(() => {130 resolve();131 }, defaultConfig.retryTimeout);132 Promise.all(promisesToBeResolvedBeforeCloseBrowser).then(() => {133 clearTimeout(timeout);134 resolve();135 });136 });137 }138 }139 defaultConfig.connectedToRemoteBrowser ? await _client.Browser.close() : await closeBrowser();140 await _client.close();141 _client = null;142};143async function reconnect() {144 const response = await isReachable(`${defaultConfig.host}:${defaultConfig.port}`);145 if (response) {146 try {147 logEvent('Reconnecting');148 eventHandler.emit('reconnecting');149 _client.removeAllListeners();150 const pages = await targetHandler.getFirstAvailablePageTarget();151 await connect_to_cri(pages[0].targetId);152 logEvent('Reconnected');153 eventHandler.emit('reconnected');154 } catch (e) {}155 }156}157const cleanUpListenersOnClient = async () => {158 _client.removeAllListeners();159 await _client.close();160};161const validate = () => {162 if (!_client) {163 throw new Error('Browser or page not initialized. Call `openBrowser()` before using this API');164 }165 if (_client._ws.readyState > 1) {166 errorMessageForBrowserProcessCrash();167 throw new Error(168 "Connection to browser lost. This probably isn't a problem with Taiko, inspect logs for possible causes.",169 );170 }171};172const getClient = () => _client;173eventHandler.addListener('targetCreated', async (newTarget) => {174 const response = await isReachable(`${defaultConfig.host}:${defaultConfig.port}`);175 if (response) {176 const pages = await targetHandler.getFirstAvailablePageTarget();177 await connect_to_cri(pages[0].targetId).then(() => {178 logEvent(`Target Navigated: Target id: ${newTarget.targetInfo.targetId}`);179 eventHandler.emit('targetNavigated');180 });181 }182});...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, closeBrowser, cleanUpListenersOnClient } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await goto("google.com");6 await cleanUpListenersOnClient();7 } catch (e) {8 console.error(e);9 } finally {10 await closeBrowser();11 }12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, closeBrowser, cleanUpListenersOnClient } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await goto("google.com");6 await cleanUpListenersOnClient();7 } catch (e) {8 console.error(e);9 } finally {10 await closeBrowser();11 }12})();13#### `async openBrowser([options])`14await openBrowser();15await openBrowser({ headless: false });16await openBrowser({ headless: false, args: ['--window-size=1440,900'] });17#### `async closeBrowser()`18await closeBrowser();19#### `async goto(url, [options])`20await goto("google.com");21await goto("google.com", { waitForEvents: ["load", "domcontentloaded", "networkidle"] });22await goto("google.com", { waitForNavigation: true });23#### `async reload([options])`24await reload();25await reload({ waitForEvents: ["load", "domcontentloaded", "networkidle"] });26await reload({ waitForNavigation: true });27#### `async goBack([options])`28await goBack();29await goBack({ waitForEvents: ["load", "domcontentloaded", "networkidle"] });30await goBack({ waitForNavigation: true });31#### `async goForward([options])`32await goForward();33await goForward({ waitForEvents: ["load", "domcontentloaded", "networkidle"] });34await goForward({ waitForNavigation: true });35#### `async hover(selector, [options])`36await hover("button");37await hover(link("google"));38#### `async click(selector, [options])`39await click("button");40await click(link("google"));41await click("button", { button: "right" });42await click("button", { clickCount: 2 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, closeBrowser, cleanUpListenersOnClient } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await cleanUpListenersOnClient();6 await closeBrowser();7 } catch (e) {8 console.error(e);9 } finally {10 }11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, closeBrowser, cleanUpListenersOnClient } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await cleanUpListenersOnClient();6 } catch (e) {7 console.error(e);8 } finally {9 await closeBrowser();10 }11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, click, closeBrowser, cleanUpListenersOnClient } = require('taiko');2(async () => {3 try {4 await openBrowser({ headless: false });5 await goto('google.com');6 await click('Gmail');7 await cleanUpListenersOnClient();8 } catch (e) {9 console.error(e);10 } finally {11 await closeBrowser();12 }13})();14Feel free to check [issues page](

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, write, click, closeBrowser, cleanUpListenersOnClient } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await write("Hello World");6 await click("Get Started");7 await cleanUpListenersOnClient();8 } catch (e) {9 console.error(e);10 } finally {11 await closeBrowser();12 }13})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, button, closeBrowser, cleanUpListenersOnClient, intercept, toRightOf } = require('taiko');2(async () => {3 try {4 await openBrowser({ headless: false });5 await button(toRightOf("Remove")).click();6 await button("Add").click();7 await cleanUpListenersOnClient();8 await button(toRightOf("Remove")).click();9 await button("Add").click();10 } catch (e) {11 console.error(e);12 } finally {13 await closeBrowser();14 }15})();16### `cleanUpListenersOnClient()`17const { openBrowser, goto, button, closeBrowser, cleanUpListenersOnClient, intercept, toRightOf } = require('taiko');18(async () => {19 try {20 await openBrowser({ headless: false });21 await button(toRightOf("Remove")).click();22 await button("Add").click();23 await cleanUpListenersOnClient();24 await button(toRightOf("Remove")).click();25 await button("Add").click();26 } catch (e) {27 console.error(e);28 } finally {29 await closeBrowser();30 }31})();32### `overridePermissions(origin, permissions)`33const { openBrowser, goto, closeBrowser, overridePermissions } = require('

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, closeBrowser, text, button, click, cleanUpListenersOnClient } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await click(button('I agree'));6 await click(text('Gmail'));7 await cleanUpListenersOnClient();8 await click(text('Sign in'));9 await click(text('Sign up for GitHub'));10 } catch (e) {11 console.error(e);12 } finally {13 await closeBrowser();14 }15})();16### openBrowser([options])17* `options` (Object) - Optional

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run taiko automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful