How to use startOnDocker method in Testcafe

Best JavaScript code snippet using testcafe

Run Testcafe automation tests on LambdaTest cloud grid

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

local-chrome.js

Source: local-chrome.js Github

copy
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';
8
9const browserStarter = new BrowserStarter();
10
11const LIST_TABS_TIMEOUT = 10000;
12const LIST_TABS_DELAY   = 500;
13
14export async function start (pageUrl, { browserName, config, cdpPort, tempProfileDir, inDocker }) {
15    const chromeInfo           = await browserTools.getBrowserInfo(config.path || browserName);
16    const chromeOpenParameters = Object.assign({}, chromeInfo);
17
18    chromeOpenParameters.cmd = buildChromeArgs({ config, cdpPort, platformArgs: chromeOpenParameters.cmd, tempProfileDir, inDocker });
19
20    await browserStarter.startBrowser(chromeOpenParameters, pageUrl);
21}
22
23async function tryListTabs (cdpPort) {
24    try {
25        return { tabs: await remoteChrome.List({ port: cdpPort }) };
26    }
27    catch (error) {
28        return { error };
29    }
30}
31
32export async function startOnDocker (pageUrl, { browserName, config, cdpPort, tempProfileDir, inDocker }) {
33    await start('', { browserName, config, cdpPort, tempProfileDir, inDocker });
34
35    let { tabs, error } = await tryListTabs(cdpPort);
36    const timer         = new Timer(LIST_TABS_TIMEOUT);
37
38    //NOTE: We should repeat getting 'List' after a while because we can get an error if the browser isn't ready.
39    while ((error || !tabs.length) && !timer.expired) {
40        await delay(LIST_TABS_DELAY);
41
42        ({ tabs, error } = await tryListTabs(cdpPort));
43    }
44
45    if (error)
46        throw error;
47
48    const target     = tabs.filter(t => t.type === 'page')[0];
49    const { Target } = await remoteChrome({ target, port: cdpPort });
50
51    await Target.createTarget({ url: pageUrl });
52    await remoteChrome.Close({ id: target.id, port: cdpPort });
53}
54
55export async function stop ({ browserId }) {
56    // NOTE: Chrome on Linux closes only after the second SIGTERM signall
57    if (!await killBrowserProcess(browserId))
58        await killBrowserProcess(browserId);
59}
60
Full Screen

index.js

Source: index.js Github

copy
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';
13
14const MIN_AVAILABLE_DIMENSION = 50;
15
16export default {
17    ...dedicatedProviderBase,
18
19    getConfig (name) {
20        return getConfig(name);
21    },
22
23    _getBrowserProtocolClient (runtimeInfo) {
24        return runtimeInfo.browserClient;
25    },
26
27    async _createRunTimeInfo (hostName, config, disableMultipleWindows) {
28        return ChromeRunTimeInfo.create(hostName, config, disableMultipleWindows);
29    },
30
31    _setUserAgentMetaInfoForEmulatingDevice (browserId, config) {
32        const { emulation, deviceName } = config;
33        const isDeviceEmulation         = emulation && deviceName;
34
35        if (!isDeviceEmulation)
36            return;
37
38        const metaInfo = `Emulating ${deviceName}`;
39        const options  = {
40            appendToUserAgent: true,
41        };
42
43        this.setUserAgentMetaInfo(browserId, metaInfo, options);
44    },
45
46    async openBrowser (browserId, pageUrl, config, disableMultipleWindows, proxyless) {
47        const parsedPageUrl = parseUrl(pageUrl);
48        const runtimeInfo   = await this._createRunTimeInfo(parsedPageUrl.hostname, config, disableMultipleWindows);
49
50        runtimeInfo.browserName = this._getBrowserName();
51        runtimeInfo.browserId   = browserId;
52
53        runtimeInfo.providerMethods = {
54            resizeLocalBrowserWindow: (...args) => this.resizeLocalBrowserWindow(...args),
55            reportWarning:            (...args) => this.reportWarning(browserId, ...args),
56        };
57
58        //NOTE: A not-working tab is opened when the browser start in the docker so we should create a new tab.
59        if (runtimeInfo.inDocker)
60            await startLocalChromeOnDocker(pageUrl, runtimeInfo);
61        else
62            await startLocalChrome(pageUrl, runtimeInfo);
63
64        await this.waitForConnectionReady(browserId);
65
66        runtimeInfo.viewportSize      = await this.runInitScript(browserId, GET_WINDOW_DIMENSIONS_INFO_SCRIPT);
67        runtimeInfo.activeWindowId    = null;
68        runtimeInfo.windowDescriptors = {};
69
70        if (!disableMultipleWindows)
71            runtimeInfo.activeWindowId = this.calculateWindowId();
72
73        const browserClient = new BrowserClient(runtimeInfo, proxyless);
74
75        this.openedBrowsers[browserId] = runtimeInfo;
76
77        await browserClient.init();
78
79        await this._ensureWindowIsExpanded(browserId, runtimeInfo.viewportSize);
80
81        this._setUserAgentMetaInfoForEmulatingDevice(browserId, runtimeInfo.config);
82    },
83
84    async closeBrowser (browserId, closingInfo = {}) {
85        const runtimeInfo = this.openedBrowsers[browserId];
86
87        if (runtimeInfo.browserClient.isHeadlessTab())
88            await runtimeInfo.browserClient.closeTab();
89        else
90            await this.closeLocalBrowser(browserId);
91
92        if (OS.mac || runtimeInfo.config.headless)
93            await stopLocalChrome(runtimeInfo);
94
95        if (runtimeInfo.tempProfileDir && !closingInfo.isRestarting)
96            await runtimeInfo.tempProfileDir.dispose();
97
98        delete this.openedBrowsers[browserId];
99    },
100
101    async resizeWindow (browserId, width, height, currentWidth, currentHeight) {
102        const runtimeInfo = this.openedBrowsers[browserId];
103
104        if (runtimeInfo.config.mobile)
105            await runtimeInfo.browserClient.updateMobileViewportSize();
106        else {
107            runtimeInfo.viewportSize.width  = currentWidth;
108            runtimeInfo.viewportSize.height = currentHeight;
109        }
110
111        await runtimeInfo.browserClient.resizeWindow({ width, height });
112    },
113
114    async getVideoFrameData (browserId) {
115        const { browserClient } = this.openedBrowsers[browserId];
116
117        return browserClient.getScreenshotData();
118    },
119
120    async hasCustomActionForBrowser (browserId) {
121        const { config, browserClient } = this.openedBrowsers[browserId];
122        const client                    = await browserClient.getActiveClient();
123
124        return {
125            hasCloseBrowser:                true,
126            hasResizeWindow:                !!client && (config.emulation || config.headless),
127            hasMaximizeWindow:              !!client && config.headless,
128            hasTakeScreenshot:              !!client,
129            hasChromelessScreenshots:       !!client,
130            hasGetVideoFrameData:           !!client,
131            hasCanResizeWindowToDimensions: false,
132            hasExecuteClientFunction:       !!client,
133            hasSwitchToIframe:              !!client,
134            hasSwitchToMainWindow:          !!client,
135            hasExecuteSelector:             !!client,
136        };
137    },
138
139    async _ensureWindowIsExpanded (browserId, { height, width, availableHeight, availableWidth, outerWidth, outerHeight }) {
140        if (height < MIN_AVAILABLE_DIMENSION || width < MIN_AVAILABLE_DIMENSION) {
141            const newHeight = Math.max(availableHeight, MIN_AVAILABLE_DIMENSION);
142            const newWidth  = Math.max(Math.floor(availableWidth / 2), MIN_AVAILABLE_DIMENSION);
143
144            await this.resizeWindow(browserId, newWidth, newHeight, outerWidth, outerHeight);
145        }
146    },
147};
148
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Testcafe on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)