How to use screencastOpts method in Cypress

Best JavaScript code snippet using cypress

chrome.js

Source:chrome.js Github

copy

Full Screen

1"use strict";2const tslib_1 = require("tslib");3const bluebird_1 = (0, tslib_1.__importDefault)(require("bluebird"));4const check_more_types_1 = (0, tslib_1.__importDefault)(require("check-more-types"));5const debug_1 = (0, tslib_1.__importDefault)(require("debug"));6const lazy_ass_1 = (0, tslib_1.__importDefault)(require("lazy-ass"));7const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));8const os_1 = (0, tslib_1.__importDefault)(require("os"));9const path_1 = (0, tslib_1.__importDefault)(require("path"));10const extension_1 = (0, tslib_1.__importDefault)(require("../../../extension"));11const mime_1 = (0, tslib_1.__importDefault)(require("mime"));12const launcher_1 = require("../../../launcher");13const app_data_1 = (0, tslib_1.__importDefault)(require("../util/app_data"));14const fs_1 = require("../util/fs");15const cdp_automation_1 = require("./cdp_automation");16const CriClient = (0, tslib_1.__importStar)(require("./cri-client"));17const protocol = (0, tslib_1.__importStar)(require("./protocol"));18const utils_1 = (0, tslib_1.__importDefault)(require("./utils"));19const debug = (0, debug_1.default)('cypress:server:browsers:chrome');20const LOAD_EXTENSION = '--load-extension=';21const CHROME_VERSIONS_WITH_BUGGY_ROOT_LAYER_SCROLLING = '66 67'.split(' ');22const CHROME_VERSION_INTRODUCING_PROXY_BYPASS_ON_LOOPBACK = 72;23const CHROME_VERSION_WITH_FPS_INCREASE = 89;24const CHROME_PREFERENCE_PATHS = {25 default: path_1.default.join('Default', 'Preferences'),26 defaultSecure: path_1.default.join('Default', 'Secure Preferences'),27 localState: 'Local State',28};29const pathToExtension = extension_1.default.getPathToExtension();30const pathToTheme = extension_1.default.getPathToTheme();31// Common Chrome Flags for Automation32// https://github.com/GoogleChrome/chrome-launcher/blob/master/docs/chrome-flags-for-tools.md33const DEFAULT_ARGS = [34 '--test-type',35 '--ignore-certificate-errors',36 '--start-maximized',37 '--silent-debugger-extension-api',38 '--no-default-browser-check',39 '--no-first-run',40 '--noerrdialogs',41 '--enable-fixed-layout',42 '--disable-popup-blocking',43 '--disable-password-generation',44 '--disable-single-click-autofill',45 '--disable-prompt-on-repos',46 '--disable-background-timer-throttling',47 '--disable-renderer-backgrounding',48 '--disable-renderer-throttling',49 '--disable-backgrounding-occluded-windows',50 '--disable-restore-session-state',51 '--disable-new-profile-management',52 '--disable-new-avatar-menu',53 '--allow-insecure-localhost',54 '--reduce-security-for-testing',55 '--enable-automation',56 '--disable-print-preview',57 '--disable-device-discovery-notifications',58 // https://github.com/cypress-io/cypress/issues/237659 '--autoplay-policy=no-user-gesture-required',60 // http://www.chromium.org/Home/chromium-security/site-isolation61 // https://github.com/cypress-io/cypress/issues/195162 '--disable-site-isolation-trials',63 // the following come frome chromedriver64 // https://code.google.com/p/chromium/codesearch#chromium/src/chrome/test/chromedriver/chrome_launcher.cc&sq=package:chromium&l=7065 '--metrics-recording-only',66 '--disable-prompt-on-repost',67 '--disable-hang-monitor',68 '--disable-sync',69 // this flag is causing throttling of XHR callbacks for70 // as much as 30 seconds. If you VNC in and open dev tools or71 // click on a button, it'll "instantly" work. with this72 // option enabled, it will time out some of our tests in circle73 // "--disable-background-networking"74 '--disable-web-resources',75 '--safebrowsing-disable-download-protection',76 '--disable-client-side-phishing-detection',77 '--disable-component-update',78 // Simulate when chrome needs an update.79 // This prevents an 'update' from displaying til the given date80 `--simulate-outdated-no-au='Tue, 31 Dec 2099 23:59:59 GMT'`,81 '--disable-default-apps',82 // These flags are for webcam/WebRTC testing83 // https://github.com/cypress-io/cypress/issues/270484 '--use-fake-ui-for-media-stream',85 '--use-fake-device-for-media-stream',86 // so Cypress commands don't get throttled87 // https://github.com/cypress-io/cypress/issues/513288 '--disable-ipc-flooding-protection',89 // misc. options puppeteer passes90 // https://github.com/cypress-io/cypress/issues/363391 '--disable-backgrounding-occluded-window',92 '--disable-breakpad',93 '--password-store=basic',94 '--use-mock-keychain',95 // write shared memory files into '/tmp' instead of '/dev/shm'96 // https://github.com/cypress-io/cypress/issues/533697 '--disable-dev-shm-usage',98];99/**100 * Reads all known preference files (CHROME_PREFERENCE_PATHS) from disk and retur101 * @param userDir102 */103const _getChromePreferences = (userDir) => {104 debug('reading chrome preferences... %o', { userDir, CHROME_PREFERENCE_PATHS });105 return bluebird_1.default.props(lodash_1.default.mapValues(CHROME_PREFERENCE_PATHS, (prefPath) => {106 return fs_1.fs.readJson(path_1.default.join(userDir, prefPath))107 .catch((err) => {108 // return empty obj if it doesn't exist109 if (err.code === 'ENOENT') {110 return {};111 }112 throw err;113 });114 }));115};116const _mergeChromePreferences = (originalPrefs, newPrefs) => {117 return lodash_1.default.mapValues(CHROME_PREFERENCE_PATHS, (_v, prefPath) => {118 const original = lodash_1.default.cloneDeep(originalPrefs[prefPath]);119 if (!newPrefs[prefPath]) {120 return original;121 }122 let deletions = [];123 lodash_1.default.mergeWith(original, newPrefs[prefPath], (_objValue, newValue, key, obj) => {124 if (newValue == null) {125 // setting a key to null should remove it126 deletions.push([obj, key]);127 }128 });129 deletions.forEach(([obj, key]) => {130 delete obj[key];131 });132 return original;133 });134};135const _writeChromePreferences = (userDir, originalPrefs, newPrefs) => {136 return bluebird_1.default.map(lodash_1.default.keys(originalPrefs), (key) => {137 const originalJson = originalPrefs[key];138 const newJson = newPrefs[key];139 if (!newJson || lodash_1.default.isEqual(originalJson, newJson)) {140 return;141 }142 return fs_1.fs.outputJson(path_1.default.join(userDir, CHROME_PREFERENCE_PATHS[key]), newJson);143 })144 .return();145};146/**147 * Merge the different `--load-extension` arguments into one.148 *149 * @param extPath path to Cypress extension150 * @param args all browser args151 * @param browser the current browser being launched152 * @returns the modified list of arguments153 */154const _normalizeArgExtensions = function (extPath, args, pluginExtensions, browser) {155 if (browser.isHeadless) {156 return args;157 }158 let userExtensions = [];159 const loadExtension = lodash_1.default.find(args, (arg) => {160 return arg.includes(LOAD_EXTENSION);161 });162 if (loadExtension) {163 args = lodash_1.default.without(args, loadExtension);164 // form into array, enabling users to pass multiple extensions165 userExtensions = userExtensions.concat(loadExtension.replace(LOAD_EXTENSION, '').split(','));166 }167 if (pluginExtensions) {168 userExtensions = userExtensions.concat(pluginExtensions);169 }170 const extensions = [].concat(userExtensions, extPath, pathToTheme);171 args.push(LOAD_EXTENSION + lodash_1.default.compact(extensions).join(','));172 return args;173};174// we now store the extension in each browser profile175const _removeRootExtension = () => {176 return fs_1.fs177 .removeAsync(app_data_1.default.path('extensions'))178 .catchReturn(null);179}; // noop if doesn't exist fails for any reason180// https://github.com/cypress-io/cypress/issues/2048181const _disableRestorePagesPrompt = function (userDir) {182 const prefsPath = path_1.default.join(userDir, 'Default', 'Preferences');183 return fs_1.fs.readJson(prefsPath)184 .then((preferences) => {185 const profile = preferences.profile;186 if (profile) {187 if ((profile['exit_type'] !== 'Normal') || (profile['exited_cleanly'] !== true)) {188 debug('cleaning up unclean exit status');189 profile['exit_type'] = 'Normal';190 profile['exited_cleanly'] = true;191 return fs_1.fs.outputJson(prefsPath, preferences);192 }193 }194 return;195 })196 .catch(() => { });197};198// After the browser has been opened, we can connect to199// its remote interface via a websocket.200const _connectToChromeRemoteInterface = function (port, onError, browserDisplayName) {201 // @ts-ignore202 (0, lazy_ass_1.default)(check_more_types_1.default.userPort(port), 'expected port number to connect CRI to', port);203 debug('connecting to Chrome remote interface at random port %d', port);204 return protocol.getWsTargetFor(port, browserDisplayName)205 .then((wsUrl) => {206 debug('received wsUrl %s for port %d', wsUrl, port);207 return CriClient.create(wsUrl, onError);208 });209};210const _maybeRecordVideo = function (client, options, browserMajorVersion) {211 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {212 if (!options.onScreencastFrame) {213 debug('options.onScreencastFrame is false');214 return client;215 }216 debug('starting screencast');217 client.on('Page.screencastFrame', (meta) => {218 options.onScreencastFrame(meta);219 client.send('Page.screencastFrameAck', { sessionId: meta.sessionId });220 });221 yield client.send('Page.startScreencast', browserMajorVersion >= CHROME_VERSION_WITH_FPS_INCREASE ? (0, cdp_automation_1.screencastOpts)() : (0, cdp_automation_1.screencastOpts)(1));222 return client;223 });224};225// a utility function that navigates to the given URL226// once Chrome remote interface client is passed to it.227const _navigateUsingCRI = function (client, url) {228 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {229 // @ts-ignore230 (0, lazy_ass_1.default)(check_more_types_1.default.url(url), 'missing url to navigate to', url);231 (0, lazy_ass_1.default)(client, 'could not get CRI client');232 debug('received CRI client');233 debug('navigating to page %s', url);234 // when opening the blank page and trying to navigate235 // the focus gets lost. Restore it and then navigate.236 yield client.send('Page.bringToFront');237 yield client.send('Page.navigate', { url });238 });239};240const _handleDownloads = function (client, dir, automation) {241 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {242 yield client.send('Page.enable');243 client.on('Page.downloadWillBegin', (data) => {244 const downloadItem = {245 id: data.guid,246 url: data.url,247 };248 const filename = data.suggestedFilename;249 if (filename) {250 // @ts-ignore251 downloadItem.filePath = path_1.default.join(dir, data.suggestedFilename);252 // @ts-ignore253 downloadItem.mime = mime_1.default.getType(data.suggestedFilename);254 }255 automation.push('create:download', downloadItem);256 });257 client.on('Page.downloadProgress', (data) => {258 if (data.state !== 'completed')259 return;260 automation.push('complete:download', {261 id: data.guid,262 });263 });264 yield client.send('Page.setDownloadBehavior', {265 behavior: 'allow',266 downloadPath: dir,267 });268 });269};270const _setAutomation = (client, automation) => {271 return automation.use(new cdp_automation_1.CdpAutomation(client.send, client.on, automation));272};273module.exports = {274 //275 // tip:276 // by adding utility functions that start with "_"277 // as methods here we can easily stub them from our unit tests278 //279 _normalizeArgExtensions,280 _removeRootExtension,281 _connectToChromeRemoteInterface,282 _maybeRecordVideo,283 _navigateUsingCRI,284 _handleDownloads,285 _setAutomation,286 _getChromePreferences,287 _mergeChromePreferences,288 _writeChromePreferences,289 _writeExtension(browser, options) {290 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {291 if (browser.isHeadless) {292 debug('chrome is running headlessly, not installing extension');293 return;294 }295 // get the string bytes for the final extension file296 const str = yield extension_1.default.setHostAndPath(options.proxyUrl, options.socketIoRoute);297 const extensionDest = utils_1.default.getExtensionDir(browser, options.isTextTerminal);298 const extensionBg = path_1.default.join(extensionDest, 'background.js');299 // copy the extension src to the extension dist300 yield utils_1.default.copyExtension(pathToExtension, extensionDest);301 yield fs_1.fs.chmod(extensionBg, 0o0644);302 yield fs_1.fs.writeFileAsync(extensionBg, str);303 return extensionDest;304 });305 },306 _getArgs(browser, options, port) {307 const args = [].concat(DEFAULT_ARGS);308 if (os_1.default.platform() === 'linux') {309 args.push('--disable-gpu');310 args.push('--no-sandbox');311 }312 const ua = options.userAgent;313 if (ua) {314 args.push(`--user-agent=${ua}`);315 }316 const ps = options.proxyServer;317 if (ps) {318 args.push(`--proxy-server=${ps}`);319 }320 if (options.chromeWebSecurity === false) {321 args.push('--disable-web-security');322 args.push('--allow-running-insecure-content');323 }324 // prevent AUT shaking in 66 & 67, but flag breaks chrome in 68+325 // https://github.com/cypress-io/cypress/issues/2037326 // https://github.com/cypress-io/cypress/issues/2215327 // https://github.com/cypress-io/cypress/issues/2223328 const { majorVersion, isHeadless } = browser;329 if (CHROME_VERSIONS_WITH_BUGGY_ROOT_LAYER_SCROLLING.includes(majorVersion)) {330 args.push('--disable-blink-features=RootLayerScrolling');331 }332 // https://chromium.googlesource.com/chromium/src/+/da790f920bbc169a6805a4fb83b4c2ab09532d91333 // https://github.com/cypress-io/cypress/issues/1872334 if (majorVersion >= CHROME_VERSION_INTRODUCING_PROXY_BYPASS_ON_LOOPBACK) {335 args.push('--proxy-bypass-list=<-loopback>');336 }337 if (isHeadless) {338 args.push('--headless');339 // set default headless size to 1280x720340 // https://github.com/cypress-io/cypress/issues/6210341 args.push('--window-size=1280,720');342 // set default headless DPR to 1343 // https://github.com/cypress-io/cypress/issues/17375344 args.push('--force-device-scale-factor=1');345 }346 // force ipv4347 // https://github.com/cypress-io/cypress/issues/5912348 args.push(`--remote-debugging-port=${port}`);349 args.push('--remote-debugging-address=127.0.0.1');350 return args;351 },352 open(browser, url, options = {}, automation) {353 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {354 const { isTextTerminal } = options;355 const userDir = utils_1.default.getProfileDir(browser, isTextTerminal);356 const [port, preferences] = yield bluebird_1.default.all([357 protocol.getRemoteDebuggingPort(),358 _getChromePreferences(userDir),359 ]);360 const defaultArgs = this._getArgs(browser, options, port);361 const defaultLaunchOptions = utils_1.default.getDefaultLaunchOptions({362 preferences,363 args: defaultArgs,364 });365 const [cacheDir, launchOptions] = yield bluebird_1.default.all([366 // ensure that we have a clean cache dir367 // before launching the browser every time368 utils_1.default.ensureCleanCache(browser, isTextTerminal),369 utils_1.default.executeBeforeBrowserLaunch(browser, defaultLaunchOptions, options),370 ]);371 if (launchOptions.preferences) {372 launchOptions.preferences = _mergeChromePreferences(preferences, launchOptions.preferences);373 }374 const [extDest] = yield bluebird_1.default.all([375 this._writeExtension(browser, options),376 _removeRootExtension(),377 _disableRestorePagesPrompt(userDir),378 _writeChromePreferences(userDir, preferences, launchOptions.preferences),379 ]);380 // normalize the --load-extensions argument by381 // massaging what the user passed into our own382 const args = _normalizeArgExtensions(extDest, launchOptions.args, launchOptions.extensions, browser);383 // this overrides any previous user-data-dir args384 // by being the last one385 args.push(`--user-data-dir=${userDir}`);386 args.push(`--disk-cache-dir=${cacheDir}`);387 debug('launching in chrome with debugging port', { url, args, port });388 // FIRST load the blank page389 // first allows us to connect the remote interface,390 // start video recording and then391 // we will load the actual page392 const launchedBrowser = yield (0, launcher_1.launch)(browser, 'about:blank', args);393 (0, lazy_ass_1.default)(launchedBrowser, 'did not get launched browser instance');394 // SECOND connect to the Chrome remote interface395 // and when the connection is ready396 // navigate to the actual url397 const criClient = yield this._connectToChromeRemoteInterface(port, options.onError, browser.displayName);398 (0, lazy_ass_1.default)(criClient, 'expected Chrome remote interface reference', criClient);399 yield criClient.ensureMinimumProtocolVersion('1.3')400 .catch((err) => {401 // if this minumum chrome version changes, sync it with402 // packages/web-config/webpack.config.base.ts and403 // npm/webpack-batteries-included-preprocessor/index.js404 throw new Error(`Cypress requires at least Chrome 64.\n\nDetails:\n${err.message}`);405 });406 this._setAutomation(criClient, automation);407 // monkey-patch the .kill method to that the CDP connection is closed408 const originalBrowserKill = launchedBrowser.kill;409 /* @ts-expect-error */410 launchedBrowser.kill = (...args) => {411 debug('closing remote interface client');412 criClient.close();413 debug('closing chrome');414 originalBrowserKill.apply(launchedBrowser, args);415 };416 yield this._maybeRecordVideo(criClient, options, browser.majorVersion);417 yield this._navigateUsingCRI(criClient, url);418 yield this._handleDownloads(criClient, options.downloadsFolder, automation);419 // return the launched browser process420 // with additional method to close the remote connection421 return launchedBrowser;422 });423 },...

Full Screen

Full Screen

electron.js

Source:electron.js Github

copy

Full Screen

1const _ = require('lodash')2const EE = require('events')3const path = require('path')4const Bluebird = require('bluebird')5const debug = require('debug')('cypress:server:browsers:electron')6const menu = require('../gui/menu')7const Windows = require('../gui/windows')8const { CdpAutomation, screencastOpts } = require('./cdp_automation')9const savedState = require('../saved_state')10const utils = require('./utils')11const errors = require('../errors')12// additional events that are nice to know about to be logged13// https://electronjs.org/docs/api/browser-window#instance-events14const ELECTRON_DEBUG_EVENTS = [15 'close',16 'responsive',17 'session-end',18 'unresponsive',19]20let instance = null21const tryToCall = function (win, method) {22 try {23 if (!win.isDestroyed()) {24 if (_.isString(method)) {25 return win[method]()26 }27 return method()28 }29 } catch (err) {30 return debug('got error calling window method:', err.stack)31 }32}33const _getAutomation = function (win, options, parent) {34 const sendCommand = Bluebird.method((...args) => {35 return tryToCall(win, () => {36 return win.webContents.debugger.sendCommand37 .apply(win.webContents.debugger, args)38 })39 })40 const on = (eventName, cb) => {41 win.webContents.debugger.on('message', (event, method, params) => {42 if (method === eventName) {43 cb(params)44 }45 })46 }47 const automation = new CdpAutomation(sendCommand, on, parent)48 if (!options.onScreencastFrame) {49 // after upgrading to Electron 8, CDP screenshots can hang if a screencast is not also running50 // workaround: start and stop screencasts between screenshots51 // @see https://github.com/cypress-io/cypress/pull/6555#issuecomment-59674713452 automation.onRequest = _.wrap(automation.onRequest, async (fn, message, data) => {53 if (message !== 'take:screenshot') {54 return fn(message, data)55 }56 await sendCommand('Page.startScreencast', screencastOpts)57 const ret = await fn(message, data)58 await sendCommand('Page.stopScreencast')59 return ret60 })61 }62 return automation63}64const _installExtensions = function (win, extensionPaths = [], options) {65 Windows.removeAllExtensions(win)66 return Bluebird.map(extensionPaths, (extensionPath) => {67 try {68 return Windows.installExtension(win, extensionPath)69 } catch (error) {70 return options.onWarning(errors.get('EXTENSION_NOT_LOADED', 'Electron', extensionPath))71 }72 })73}74const _maybeRecordVideo = function (webContents, options) {75 return async () => {76 const { onScreencastFrame } = options77 debug('maybe recording video %o', { onScreencastFrame })78 if (!onScreencastFrame) {79 return80 }81 webContents.debugger.on('message', (event, method, params) => {82 if (method === 'Page.screencastFrame') {83 onScreencastFrame(params)84 webContents.debugger.sendCommand('Page.screencastFrameAck', { sessionId: params.sessionId })85 }86 })87 await webContents.debugger.sendCommand('Page.startScreencast', screencastOpts)88 }89}90module.exports = {91 _defaultOptions (projectRoot, state, options, automation) {92 const _this = this93 const defaults = {94 x: state.browserX,95 y: state.browserY,96 width: state.browserWidth || 1280,97 height: state.browserHeight || 720,98 devTools: state.isBrowserDevToolsOpen,99 minWidth: 100,100 minHeight: 100,101 contextMenu: true,102 partition: this._getPartition(options),103 trackState: {104 width: 'browserWidth',105 height: 'browserHeight',106 x: 'browserX',107 y: 'browserY',108 devTools: 'isBrowserDevToolsOpen',109 },110 webPreferences: {111 sandbox: true,112 },113 onFocus () {114 if (options.show) {115 return menu.set({ withDevTools: true })116 }117 },118 onNewWindow (e, url) {119 const _win = this120 return _this._launchChild(e, url, _win, projectRoot, state, options, automation)121 .then((child) => {122 // close child on parent close123 _win.on('close', () => {124 if (!child.isDestroyed()) {125 child.destroy()126 }127 })128 // add this pid to list of pids129 tryToCall(child, () => {130 if (instance && instance.pid) {131 instance.pid.push(child.webContents.getOSProcessId())132 }133 })134 })135 },136 }137 if (options.browser.isHeadless) {138 // prevents a tiny 1px padding around the window139 // causing screenshots/videos to be off by 1px140 options.resizable = false141 }142 return _.defaultsDeep({}, options, defaults)143 },144 _getAutomation,145 _render (url, automation, preferences = {}, options = {}) {146 const win = Windows.create(options.projectRoot, preferences)147 if (preferences.browser.isHeadless) {148 // seemingly the only way to force headless to a certain screen size149 // electron BrowserWindow constructor is not respecting width/height preferences150 win.setSize(preferences.width, preferences.height)151 } else if (options.isTextTerminal) {152 // we maximize in headed mode as long as it's run mode153 // this is consistent with chrome+firefox headed154 win.maximize()155 }156 return this._launch(win, url, automation, preferences)157 .tap(_maybeRecordVideo(win.webContents, preferences))158 .tap(() => automation.use(_getAutomation(win, preferences, automation)))159 },160 _launchChild (e, url, parent, projectRoot, state, options, automation) {161 e.preventDefault()162 const [parentX, parentY] = parent.getPosition()163 options = this._defaultOptions(projectRoot, state, options)164 _.extend(options, {165 x: parentX + 100,166 y: parentY + 100,167 trackState: false,168 })169 const win = Windows.create(projectRoot, options)170 // needed by electron since we prevented default and are creating171 // our own BrowserWindow (https://electron.atom.io/docs/api/web-contents/#event-new-window)172 e.newGuest = win173 return this._launch(win, url, automation, options)174 },175 _launch (win, url, automation, options) {176 if (options.show) {177 menu.set({ withDevTools: true })178 }179 ELECTRON_DEBUG_EVENTS.forEach((e) => {180 win.on(e, () => {181 debug('%s fired on the BrowserWindow %o', e, { browserWindowUrl: url })182 })183 })184 return Bluebird.try(() => {185 return this._attachDebugger(win.webContents)186 })187 .then(() => {188 let ua189 ua = options.userAgent190 if (ua) {191 this._setUserAgent(win.webContents, ua)192 }193 const setProxy = () => {194 let ps195 ps = options.proxyServer196 if (ps) {197 return this._setProxy(win.webContents, ps)198 }199 }200 return Bluebird.join(201 setProxy(),202 this._clearCache(win.webContents),203 )204 })205 .then(() => {206 return win.loadURL(url)207 })208 .then(() => {209 // enabling can only happen once the window has loaded210 return this._enableDebugger(win.webContents)211 })212 .then(() => {213 return this._handleDownloads(win, options.downloadsFolder, automation)214 })215 .return(win)216 },217 _attachDebugger (webContents) {218 try {219 webContents.debugger.attach('1.3')220 debug('debugger attached')221 } catch (err) {222 debug('debugger attached failed %o', { err })223 throw err224 }225 const originalSendCommand = webContents.debugger.sendCommand226 webContents.debugger.sendCommand = function (message, data) {227 debug('debugger: sending %s with params %o', message, data)228 return originalSendCommand.call(webContents.debugger, message, data)229 .then((res) => {230 let debugRes = res231 if (debug.enabled && (_.get(debugRes, 'data.length') > 100)) {232 debugRes = _.clone(debugRes)233 debugRes.data = `${debugRes.data.slice(0, 100)} [truncated]`234 }235 debug('debugger: received response to %s: %o', message, debugRes)236 return res237 }).catch((err) => {238 debug('debugger: received error on %s: %o', message, err)239 throw err240 })241 }242 webContents.debugger.sendCommand('Browser.getVersion')243 webContents.debugger.on('detach', (event, reason) => {244 debug('debugger detached due to %o', { reason })245 })246 webContents.debugger.on('message', (event, method, params) => {247 if (method === 'Console.messageAdded') {248 debug('console message: %o', params.message)249 }250 })251 },252 _enableDebugger (webContents) {253 debug('debugger: enable Console and Network')254 return webContents.debugger.sendCommand('Console.enable')255 },256 _handleDownloads (win, dir, automation) {257 const onWillDownload = (event, downloadItem) => {258 const savePath = path.join(dir, downloadItem.getFilename())259 automation.push('create:download', {260 id: downloadItem.getETag(),261 filePath: savePath,262 mime: downloadItem.getMimeType(),263 url: downloadItem.getURL(),264 })265 downloadItem.once('done', () => {266 automation.push('complete:download', {267 id: downloadItem.getETag(),268 })269 })270 }271 const { session } = win.webContents272 session.on('will-download', onWillDownload)273 // avoid adding redundant `will-download` handlers if session is reused for next spec274 win.on('closed', () => session.removeListener('will-download', onWillDownload))275 return win.webContents.debugger.sendCommand('Page.setDownloadBehavior', {276 behavior: 'allow',277 downloadPath: dir,278 })279 },280 _getPartition (options) {281 if (options.isTextTerminal) {282 // create dynamic persisted run283 // to enable parallelization284 return `persist:run-${process.pid}`285 }286 // we're in interactive mode and always287 // use the same session288 return 'persist:interactive'289 },290 _clearCache (webContents) {291 debug('clearing cache')292 return webContents.session.clearCache()293 },294 _setUserAgent (webContents, userAgent) {295 debug('setting user agent to:', userAgent)296 // set both because why not297 webContents.userAgent = userAgent298 return webContents.session.setUserAgent(userAgent)299 },300 _setProxy (webContents, proxyServer) {301 return webContents.session.setProxy({302 proxyRules: proxyServer,303 // this should really only be necessary when304 // running Chromium versions >= 72305 // https://github.com/cypress-io/cypress/issues/1872306 proxyBypassRules: '<-loopback>',307 })308 },309 open (browser, url, options = {}, automation) {310 const { projectRoot, isTextTerminal } = options311 debug('open %o', { browser, url })312 return savedState.create(projectRoot, isTextTerminal)313 .then((state) => {314 return state.get()315 }).then((state) => {316 debug('received saved state %o', state)317 // get our electron default options318 // TODO: this is bad, don't mutate the options object319 options = this._defaultOptions(projectRoot, state, options, automation)320 // get the GUI window defaults now321 options = Windows.defaults(options)322 debug('browser window options %o', _.omitBy(options, _.isFunction))323 const defaultLaunchOptions = utils.getDefaultLaunchOptions({324 preferences: options,325 })326 return utils.executeBeforeBrowserLaunch(browser, defaultLaunchOptions, options)327 }).then((launchOptions) => {328 const { preferences } = launchOptions329 debug('launching browser window to url: %s', url)330 return this._render(url, automation, preferences, {331 projectRoot: options.projectRoot,332 isTextTerminal: options.isTextTerminal,333 })334 .then(async (win) => {335 await _installExtensions(win, launchOptions.extensions, options)336 // cause the webview to receive focus so that337 // native browser focus + blur events fire correctly338 // https://github.com/cypress-io/cypress/issues/1939339 tryToCall(win, 'focusOnWebView')340 const events = new EE341 win.once('closed', () => {342 debug('closed event fired')343 Windows.removeAllExtensions(win)344 return events.emit('exit')345 })346 instance = _.extend(events, {347 pid: [tryToCall(win, () => {348 return win.webContents.getOSProcessId()349 })],350 browserWindow: win,351 kill () {352 if (this.isProcessExit) {353 // if the process is exiting, all BrowserWindows will be destroyed anyways354 return355 }356 return tryToCall(win, 'destroy')357 },358 removeAllListeners () {359 return tryToCall(win, 'removeAllListeners')360 },361 })362 return instance363 })364 })365 },...

Full Screen

Full Screen

cdp_automation.js

Source:cdp_automation.js Github

copy

Full Screen

...7const bluebird_1 = (0, tslib_1.__importDefault)(require("bluebird"));8const network_1 = require("../../../network");9const debug_1 = (0, tslib_1.__importDefault)(require("debug"));10const debugVerbose = (0, debug_1.default)('cypress-verbose:server:browsers:cdp_automation');11function screencastOpts(everyNthFrame = Number(process.env.CYPRESS_EVERY_NTH_FRAME || 5)) {12 return {13 format: 'jpeg',14 everyNthFrame,15 };16}17exports.screencastOpts = screencastOpts;18function convertSameSiteExtensionToCdp(str) {19 return str ? ({20 'no_restriction': 'None',21 'lax': 'Lax',22 'strict': 'Strict',23 })[str] : str;24}25function convertSameSiteCdpToExtension(str) {...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('takeSnapShot', (fileName) => {2 cy.wait(1000);3 cy.matchImageSnapshot(fileName);4});5Cypress.Commands.add('takeSnapShotFullScreen', (fileName) => {6 cy.wait(1000);7 cy.screenshot(fileName, { capture: 'fullPage' });8});9Cypress.Commands.add('takeSnapShotViewport', (fileName) => {10 cy.wait(1000);11 cy.screenshot(fileName, { capture: 'viewport' });12});13Cypress.Commands.add('takeSnapShotElement', (fileName, selector) => {14 cy.wait(1000);15 cy.screenshot(fileName, { capture: 'viewport' });16});17Cypress.Commands.add('takeSnapShotElementFullScreen', (fileName, selector) => {18 cy.wait(1000);19 cy.screenshot(fileName, { capture: 'fullPage' });20});21Cypress.Commands.add('takeSnapShotElementViewport', (fileName, selector) => {22 cy.wait(1000);23 cy.screenshot(fileName, { capture: 'viewport' });24});25Cypress.Commands.add('takeSnapShotElementViewport', (fileName, selector) => {26 cy.wait(1000);27 cy.screenshot(fileName, { capture: 'viewport' });28});29Cypress.Commands.add('takeSnapShotElementViewport', (fileName, selector

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.screencastOpts({4 dimensions: {5 },6 })7 cy.contains('type').click()8 cy.url().should('include', '/commands/actions')9 cy.get('.action-email')10 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 videoOptions: {4 },5 })6 })7})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Screenshot.defaults({2 videoOptions: {3 },4})5{6 "videoOptions": {7 },8}

Full Screen

Using AI Code Generation

copy

Full Screen

1{2}3describe('test', () => {4 it('test', () => {5 cy.screencastOpts({6 })7 })8})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Cypress Screen Cast', function () {2 it('Cypress Screen Cast', function () {3 cy.screencastOpts({4 })5 })6})7{8}

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add("screencastOpts", (options) => {2 Cypress._.defaults(options, {3 });4 cy.task("screencast:start", options);5});6Cypress.Commands.add("screenshot", (name, options) => {7 Cypress._.defaults(options, {8 });9 cy.task("screencast:screenshot", {10 });11});12module.exports = (on, config) => {13 on("task", {14 "screencast:start"(options) {15 require("screencast").start(options);16 },17 "screencast:screenshot"({ name, options }) {18 require("screencast").screenshot(name, options);19 },20 });21};22import "./commands";23describe("My First Test", () => {24 it("Does not do much!", () => {25 cy.contains("type").click();26 cy.get(".action-email")27 .type("

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', () => {2 it('Visits the Kitchen Sink', () => {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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