Best JavaScript code snippet using testcafe
index.js
Source:index.js
1import OS from 'os-family';2import { parse as parseUrl } from 'url';3import dedicatedProviderBase from '../base';4import ChromeRunTimeInfo from './runtime-info';5import getConfig from './config';6import {7 start as startLocalChrome,8 startOnDocker as startLocalChromeOnDocker,9 stop as stopLocalChrome,10} from './local-chrome';11import { GET_WINDOW_DIMENSIONS_INFO_SCRIPT } from '../../../utils/client-functions';12import { BrowserClient } from './cdp-client';13const MIN_AVAILABLE_DIMENSION = 50;14export default {15 ...dedicatedProviderBase,16 getConfig (name) {17 return getConfig(name);18 },19 _getBrowserProtocolClient (runtimeInfo) {20 return runtimeInfo.browserClient;21 },22 async _createRunTimeInfo (hostName, config, disableMultipleWindows) {23 return ChromeRunTimeInfo.create(hostName, config, disableMultipleWindows);24 },25 _setUserAgentMetaInfoForEmulatingDevice (browserId, config) {26 const { emulation, deviceName } = config;27 const isDeviceEmulation = emulation && deviceName;28 if (!isDeviceEmulation)29 return;30 const metaInfo = `Emulating ${deviceName}`;31 const options = {32 appendToUserAgent: true,33 };34 this.setUserAgentMetaInfo(browserId, metaInfo, options);35 },36 async openBrowser (browserId, pageUrl, config, disableMultipleWindows, proxyless) {37 const parsedPageUrl = parseUrl(pageUrl);38 const runtimeInfo = await this._createRunTimeInfo(parsedPageUrl.hostname, config, disableMultipleWindows);39 runtimeInfo.browserName = this._getBrowserName();40 runtimeInfo.browserId = browserId;41 runtimeInfo.providerMethods = {42 resizeLocalBrowserWindow: (...args) => this.resizeLocalBrowserWindow(...args),43 reportWarning: (...args) => this.reportWarning(browserId, ...args),44 };45 //NOTE: A not-working tab is opened when the browser start in the docker so we should create a new tab.46 if (runtimeInfo.inDocker)47 await startLocalChromeOnDocker(pageUrl, runtimeInfo);48 else49 await startLocalChrome(pageUrl, runtimeInfo);50 await this.waitForConnectionReady(browserId);51 runtimeInfo.viewportSize = await this.runInitScript(browserId, GET_WINDOW_DIMENSIONS_INFO_SCRIPT);52 runtimeInfo.activeWindowId = null;53 runtimeInfo.windowDescriptors = {};54 if (!disableMultipleWindows)55 runtimeInfo.activeWindowId = this.calculateWindowId();56 const browserClient = new BrowserClient(runtimeInfo, proxyless);57 this.openedBrowsers[browserId] = runtimeInfo;58 await browserClient.init();59 await this._ensureWindowIsExpanded(browserId, runtimeInfo.viewportSize);60 this._setUserAgentMetaInfoForEmulatingDevice(browserId, runtimeInfo.config);61 },62 async closeBrowser (browserId, closingInfo = {}) {63 const runtimeInfo = this.openedBrowsers[browserId];64 if (runtimeInfo.browserClient.isHeadlessTab())65 await runtimeInfo.browserClient.closeTab();66 else67 await this.closeLocalBrowser(browserId);68 if (OS.mac || runtimeInfo.config.headless)69 await stopLocalChrome(runtimeInfo);70 if (runtimeInfo.tempProfileDir && !closingInfo.isRestarting)71 await runtimeInfo.tempProfileDir.dispose();72 delete this.openedBrowsers[browserId];73 },74 async resizeWindow (browserId, width, height, currentWidth, currentHeight) {75 const runtimeInfo = this.openedBrowsers[browserId];76 if (runtimeInfo.config.mobile)77 await runtimeInfo.browserClient.updateMobileViewportSize();78 else {79 runtimeInfo.viewportSize.width = currentWidth;80 runtimeInfo.viewportSize.height = currentHeight;81 }82 await runtimeInfo.browserClient.resizeWindow({ width, height });83 },84 async getVideoFrameData (browserId) {85 const { browserClient } = this.openedBrowsers[browserId];86 return browserClient.getScreenshotData();87 },88 async hasCustomActionForBrowser (browserId) {89 const { config, browserClient } = this.openedBrowsers[browserId];90 const client = await browserClient.getActiveClient();91 return {92 hasCloseBrowser: true,93 hasResizeWindow: !!client && (config.emulation || config.headless),94 hasMaximizeWindow: !!client && config.headless,95 hasTakeScreenshot: !!client,96 hasChromelessScreenshots: !!client,97 hasGetVideoFrameData: !!client,98 hasCanResizeWindowToDimensions: false,99 hasExecuteClientFunction: !!client,100 hasSwitchToIframe: !!client,101 hasSwitchToMainWindow: !!client,102 hasExecuteSelector: !!client,103 };104 },105 async _ensureWindowIsExpanded (browserId, { height, width, availableHeight, availableWidth, outerWidth, outerHeight }) {106 if (height < MIN_AVAILABLE_DIMENSION || width < MIN_AVAILABLE_DIMENSION) {107 const newHeight = Math.max(availableHeight, MIN_AVAILABLE_DIMENSION);108 const newWidth = Math.max(Math.floor(availableWidth / 2), MIN_AVAILABLE_DIMENSION);109 await this.resizeWindow(browserId, newWidth, newHeight, outerWidth, outerHeight);110 }111 },...
local-chrome.js
Source:local-chrome.js
1import browserTools from 'testcafe-browser-tools';2import { killBrowserProcess } from '../../../../../utils/process';3import BrowserStarter from '../../../utils/browser-starter';4import { buildChromeArgs } from './build-chrome-args';5import remoteChrome from 'chrome-remote-interface';6import Timer from '../../../../../utils/timer';7import delay from '../../../../../utils/delay';8const browserStarter = new BrowserStarter();9const LIST_TABS_TIMEOUT = 10000;10const LIST_TABS_DELAY = 500;11export async function start (pageUrl, { browserName, config, cdpPort, tempProfileDir, inDocker }) {12 const chromeInfo = await browserTools.getBrowserInfo(config.path || browserName);13 const chromeOpenParameters = Object.assign({}, chromeInfo);14 chromeOpenParameters.cmd = buildChromeArgs({ config, cdpPort, platformArgs: chromeOpenParameters.cmd, tempProfileDir, inDocker });15 await browserStarter.startBrowser(chromeOpenParameters, pageUrl);16}17async function tryListTabs (cdpPort) {18 try {19 return { tabs: await remoteChrome.List({ port: cdpPort }) };20 }21 catch (error) {22 return { error };23 }24}25export async function startOnDocker (pageUrl, { browserName, config, cdpPort, tempProfileDir, inDocker }) {26 await start('', { browserName, config, cdpPort, tempProfileDir, inDocker });27 let { tabs, error } = await tryListTabs(cdpPort);28 const timer = new Timer(LIST_TABS_TIMEOUT);29 //NOTE: We should repeat getting 'List' after a while because we can get an error if the browser isn't ready.30 while ((error || !tabs.length) && !timer.expired) {31 await delay(LIST_TABS_DELAY);32 ({ tabs, error } = await tryListTabs(cdpPort));33 }34 if (error)35 throw error;36 const target = tabs.filter(t => t.type === 'page')[0];37 const { Target } = await remoteChrome({ target, port: cdpPort });38 await Target.createTarget({ url: pageUrl });39 await remoteChrome.Close({ id: target.id, port: cdpPort });40}41export async function stop ({ browserId }) {42 // NOTE: Chrome on Linux closes only after the second SIGTERM signall43 if (!await killBrowserProcess(browserId))44 await killBrowserProcess(browserId);...
Using AI Code Generation
1const createTestCafe = require('testcafe');2let testcafe = null;3createTestCafe('localhost', 1337, 1338)4 .then(tc => {5 testcafe = tc;6 const runner = testcafe.createRunner();7 .src(['tests/test1.js', 'tests/test2.js'])8 .browsers(['chrome:headless', 'firefox:headless'])9 .screenshots('reports/screenshots/', true)10 .startOnDocker('testcafe/testcafe', 'chrome:headless')11 .run();12 })13 .then(failedCount => {14 console.log('Tests failed: ' + failedCount);15 testcafe.close();16 });
Using AI Code Generation
1const createTestCafe = require('testcafe');2let testcafe = null;3createTestCafe('localhost', 1337, 1338)4 .then(tc => {5 testcafe = tc;6 const runner = testcafe.createRunner();7 .src('test.js')8 .browsers('chrome:headless:headless')9 .screenshots('reports/screenshots/', true)10 .oep(rtpec')pc')11 .ru({12 }{13 });14 })15 .then(failedCount => {16 console.log('Tests failed: ' + failedCount);17 testcafe.close();18 });19const createTestCafe = requIre('testcafe');20let testcafe = null;21createTestCafe('localhost', 1337, 1338)22 .then(tc => {23 testcafe = tc;24 const runner = testcafe.createRunner();25 .src('test.js')26 .browsers('chrome:headless')27 .run();28 })29 .then(failedCount => {30 console.log('Tests failed: ' + failedCount);31 testcafe.close();32 });33import { Selector } from 'testcafe';34test('My first test', async t => {35});
Using AI Code Generation
1const createTestCafe = require('testcafe');2let testcafe = null;3createTestCafe('localhost', 1337, 1338)4 .then(tc => {5 testcafe = tc;6 const runner = testcafe.createRunner();7 .src('test.js')8 .browsers('chrome')9 .screenshots('reports/screenshots/', true)10 .startOnDocker('selenium/standalone-chrome:3.141.59-20200525', {seleniumImage: 'selenium/standalone-chrome:3.141.59-20200525', seleniumArgs: ['-debug']})11 .run();12 })13 .then(failedCount => {14 console.log('Tests failed: ' + failedCount);15 testcafe.close();16 });
Using AI Code Generation
1const createTestCafe = require('testcafe');2let testcafe = null;3createTestCafe('localhost', 1337, 1338)4 .then(tc => {5 testcafe = tc;6 const runner = testcafe.createRunner();7 .src('test.js')8 .browsers('chrome:headless')9 .run();10 })11 .then(failedCount => {12 console.log('Tests failed: ' + failedCount);13 testcafe.close();14 });15import { Selector } from 'testcafe';16test('My first test', async t => {17});18TestCafe=Studio=i= a visual UI ingtoolthatall you to rcod, at, n/e tctests.oItncansbetused toctestrwebettee and hybtid mabile=applica ions.ire('testcafe');19r = testcafe.createRunner();20* [terecafe-brtwser-urovrdeu-eecon]( .src('test.js')21 .browsers('chrome')22 .screenshots('reports/screenshots/', true)23 .startOnDocker('selenium/standalone-chrome:3.141.59-20200525', {seleniumImage: 'selenium/standalone-chrome:3.141.59-20200525', seleniumArgs: ['-debug']})24 .run();25 })Selcor26imp r(C{={ OoDockns }ofrome'.log('Te-dotk '' 27failedCount);28f xture `Get ing Sta tsd`cafe.close();29 }ge `htp:/devexpress.gihub.ica/xapl/`;30t('Myftst'/async/tc=>o{31import {.typSTlxc('#develtpeo-na} 'c'Jh Sih')32fixture .clSck('#subtit-bteton')33e hs.oxp 13(lr('#ricl-')ex).q('Thak,Jhn S!');34});35 UariOnDoTktr(cr I, 'hom'36Ycu cPn}pa: additTsnol epni## Uos htk` Iai OnDockDr`untin:37=rOnDckt/sc,t'c romu', {38sc plataer.:crWindowt 10e,();39 Re olu.i(n:t'1280x960',40t 'fcuco:optk':e{41 }FROM testcafe/testcafe:latest42});43varExamplestestcafe');44testcafe.createRunner()
Using AI Code Generation
1import tcafe = require('testcafe');2testcafe.createRunner()/3 .src('test.js')4 .browsers(['chrome:headless'])5 .run({6 .txpOct(Silecsor('#ie-h')).eql('Thank you, John Smith!')7 });8startOn(test,'chro');9impor{ Selectr} frm'scaf';10ipr{ otartOnDonst t} feomc'e await -doaker';11eixtur.c`G(ttingStad`
Using AI Code Generation
1vf= reqir('caf');2tcfe.ceR nir()3p:.s('.j')4 .bowsrs(['hrme:healss'])5.ru({6 });7### TestCafe.create([remoteConnectionSettings])8import { Testcafe } from 'testcafe';9const testcafe = await Testcafe.create();10### TestCafe.close()11import { Testcafe } from 'testcafe';12const testcafe = await Testcafe.create();13await testcafe.close();14### TestCafe.listRemoteBrowsers()15import { Testcafe } from 'testcafe';16const testcafe = await Testcafe.create();17const browsers = await testcafe.listRemoteBrowsers();18await testcafe.close();19import { Testcafe } from 'testcafe';20const testcafe = await Testcafe.create();21const version = await testcafe.version();22await testcafe.close();23### TestCafe.createRunner()
Using AI Code Generation
1import { Selector } from 'testcafe';2import { startOnDocker } from 'testcafe-docker';3import { getTestcafe } from 'testcafe';4test('My first test', async t => {5 .typeText('#developer-name', 'John Smith')6 .click('#submit-button');7 const articleHeader = await Selector('.result-content').find('h1');8 let headerText = await articleHeader.innerText;9});10import { Testcafe } from 'testcafe';11const testcafe = await Testcafe.create();12const runner = testcafe.createRunner();13await testcafe.close();14### runner.src(source)
Using AI Code Generation
1import { Selector } from 'testcafe';2import { startOnDocker } from 'testcafe-docker';3import { getTestcafe } from 'testcafe';4test('My first test', async t => {5 .typeText('#developer-name', 'John Smith')6 .click('#submit-button');7 const articleHeader = await Selector('.result-content').find('h1');8 let headerText = await articleHeader.innerText;9});
Using AI Code Generation
1import { Selector } from 'testcafe';2import { startOnDocker } from 'testcafe-docker';3import { getTestcafe } from 'testcafe';4test('My first test', async t => {5 .typeText('#developer-name', 'John Smith')6 .click('#submit-button');7 const articleHeader = await Selector('.result-content').find('h1');8 let headerText = await articleHeader.innerText;9});10* [testcafe-browser-provider-electron](
Using AI Code Generation
1import { Testcafe } from 'testcafe';2const testcafe = await Testcafe.create();3const runner = testcafe.createRunner();4 .src('path/to/test/file.js')5 .browsers('chrome')6 .run({7 });8await testcafe.close();9### TestCafe.create([remoteConnectionSettings])10import { Testcafe } from 'testcafe';11const testcafe = await Testcafe.create();12### TestCafe.close()13import { Testcafe } from 'testcafe';14const testcafe = await Testcafe.create();15await testcafe.close();16### TestCafe.listRemoteBrowsers()17import { Testcafe } from 'testcafe';18const testcafe = await Testcafe.create();19const browsers = await testcafe.listRemoteBrowsers();20await testcafe.close();21### TestCafe.version()22import { Testcafe } from 'testcafe';23const testcafe = await Testcafe.create();24const version = await testcafe.version();25await testcafe.close();26### TestCafe.createRunner()27import { Testcafe } from 'testcafe';28const testcafe = await Testcafe.create();29const runner = testcafe.createRunner();30await testcafe.close();31### runner.src(source)
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!!