How to use chrome.open method in Cypress

Best JavaScript code snippet using cypress

qmChrome.js

Source:qmChrome.js Github

copy

Full Screen

1/** @namespace window.qmLog */2/** @namespace window.qm */3window.qm.chrome = {4 debugEnabled: true,5 chromeDebug: function () {6 function checkAlarm() {7 chrome.alarms.getAll(function(alarms) {8 console.log("all alarms", alarms);9 })10 }11 if (qm.chrome.debugEnabled) {12 checkAlarm();13 chrome.windows.getLastFocused(function (window) {14 console.log("last focused", window);15 });16 chrome.windows.getAll(function (windows) {17 console.log("all windows", windows);18 });19 chrome.windows.getCurrent(function (window) {20 console.log("current window", window);21 });22 }23 },24 checkTimePastNotificationsAndExistingPopupAndShowPopupIfNecessary: function(alarm) {25 if(!qm.platform.isChromeExtension()){return;}26 window.qmLog.debug('showNotificationOrPopupForAlarm alarm: ', null, alarm);27 if(!qm.userHelper.withinAllowedNotificationTimes()){return false;}28 if(qm.notifications.getNumberInGlobalsOrLocalStorage()){29 qm.chrome.createSmallInboxNotification();30 } else {31 qm.notifications.refreshAndShowPopupIfNecessary();32 }33 },34 createSmallInboxNotification: function (){35 var notificationId = "inbox";36 chrome.notifications.create(notificationId, qm.chrome.windowParams.inboxNotificationParams, function (id) {});37 },38 createSmallNotificationAndOpenInboxInBackground: function(){39 qm.chrome.createSmallInboxNotification();40 var windowParams = qm.chrome.windowParams.fullInboxWindowParams;41 windowParams.focused = false;42 qm.chrome.openOrFocusChromePopupWindow(windowParams);43 },44 createPopup: function(windowParams){45 function createPopup(windowParams) {46 windowParams.url = qm.api.addGlobalParams(windowParams.url);47 qmLog.info("creating popup window", null, windowParams);48 chrome.windows.create(windowParams, function (chromeWindow) {49 qm.storage.setItem('chromeWindowId', chromeWindow.id);50 chrome.windows.update(chromeWindow.id, { focused: windowParams.focused });51 });52 }53 if(windowParams.url.indexOf('.quantimo.do') !== -1 || windowParams.url.indexOf('popup.html') !== -1){54 createPopup(windowParams);55 } else {56 qm.client.getClientWebsiteUrl(function (fullWebsiteUrl) {57 windowParams.url = fullWebsiteUrl + windowParams.url;58 createPopup(windowParams);59 })60 }61 },62 canShowChromePopups: function(){63 if(typeof chrome === "undefined" || typeof chrome.windows === "undefined" || typeof chrome.windows.create === "undefined"){64 qmLog.info("Cannot show chrome popups");65 return false;66 }67 if(qm.getUser() && !qm.getUser().pushNotificationsEnabled){68 qmLog.info("User has disabled notifications");69 return false;70 }71 return true;72 },73 getChromeManifest: function() {if(qm.platform.isChromeExtension()){return chrome.runtime.getManifest();}},74 getWindowByIdAndFocusOrCreateNewPopup: function(chromeWindowId, windowParams){75 chrome.windows.get(chromeWindowId, function (chromeWindow) {76 if (!chrome.runtime.lastError && chromeWindow){77 if(windowParams.focused){78 window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: Window already open. Focusing...', windowParams );79 chrome.windows.update(chromeWindowId, {focused: true});80 } else {81 window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: Window already open. NOT focusing...', windowParams );82 }83 } else {84 window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: Window NOT already open. Creating one...', windowParams );85 qm.chrome.createPopup(windowParams);86 }87 });88 },89 createPopupIfNoWindowIdInLocalStorage: function(windowParams){90 window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow checking if a window is already open. new window params: ', null, windowParams );91 var chromeWindowId = parseInt(qm.storage.getItem(qm.items.chromeWindowId), null);92 if(!chromeWindowId){93 window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: No window id from localStorage. Creating one...', windowParams );94 qm.chrome.createPopup(windowParams);95 return false;96 }97 window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: window id from localStorage: ' + chromeWindowId, windowParams );98 return chromeWindowId;99 },100 getCurrentWindowAndFocusOrCreateNewPopup: function (windowParams) {101 chrome.windows.getCurrent(function (window) {102 console.log("current window", window);103 if(window && window.type === "popup"){104 chrome.windows.update(window.id, {focused: true});105 } else {106 qm.chrome.createPopup(windowParams);107 }108 });109 },110 getAllWindowsFocusOrCreateNewPopup: function (windowParams) {111 qm.userHelper.getUserFromLocalStorageOrApi(function (user) {112 if(!user.pushNotificationsEnabled){113 qmLog.pushDebug("Not showing chrome popup because notifications are disabled");114 return;115 }116 console.log("getAllWindowsFocusOrCreateNewPopup");117 chrome.windows.getAll(function (windows) {118 for (var i = 0; i < windows.length; i++) {119 var window = windows[i];120 console.log("current window", window);121 if(window.type === "popup"){122 console.log("Focusing existing popup", window);123 chrome.windows.update(window.id, {focused: true});124 return;125 }126 }127 qm.chrome.createPopup(windowParams);128 });129 })130 },131 handleNotificationClick: function(notificationId) {132 window.qmLog.debug('onClicked: notificationId:' + notificationId);133 var focusWindow = true;134 if(!qm.platform.isChromeExtension()){return;}135 if(!notificationId){notificationId = null;}136 qm.chrome.updateChromeBadge(0);137 qmLog.info("notificationId: "+ notificationId);138 /**139 * @return {boolean}140 */141 function IsJsonString(str) {142 try {143 JSON.parse(str);144 } catch (exception) {145 return false;146 }147 return true;148 }149 if(notificationId === "moodReportNotification") {150 qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.facesWindowParams);151 } else if (notificationId === "signin") {152 qm.chrome.openLoginWindow();153 } else if (notificationId && IsJsonString(notificationId)) {154 qm.chrome.openMeasurementAddWindow(focusWindow, notificationId);155 } else {156 qm.chrome.openFullInbox(focusWindow, notificationId);157 }158 if(notificationId){chrome.notifications.clear(notificationId);}159 },160 initialize: function () {161 //return;162 chrome.notifications.onClicked.addListener(function(notificationId) { // Called when the notification is clicked163 qm.chrome.handleNotificationClick(notificationId);164 });165 /** @namespace chrome.extension.onMessage */166 chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {167 // Handles extension-specific requests that come in, such as a request to upload a new measurement168 window.qmLog.debug('Received request: ' + request.message, null);169 if(request.message === "uploadMeasurements") {qm.api.postMeasurements(request.payload, null);}170 });171 chrome.runtime.onInstalled.addListener(function () { // Called when the extension is installed172 qm.chrome.scheduleGenericChromeExtensionNotification();173 if(!localStorage.getItem(qm.items.introSeen)){qm.chrome.openIntroWindowPopup();}174 });175 chrome.alarms.onAlarm.addListener(function (alarm) { // Called when an alarm goes off (we only have one)176 qmLog.info('onAlarm Listener heard this alarm ', null, alarm);177 qm.userHelper.getUserFromLocalStorageOrApi(function () {178 qm.notifications.refreshIfEmptyOrStale(qm.chrome.showRatingOrInboxPopup());179 });180 });181 qm.userHelper.getUserFromLocalStorageOrApi(function () {182 qm.chrome.showRatingOrInboxPopup();183 }, function () {184 qm.chrome.showSignInNotification();185 });186 },187 openIntroWindowPopup: function(){188 qm.storage.setItem('introSeen', true);189 qm.chrome.createPopup(qm.chrome.windowParams.introWindowParams);190 },191 openOrFocusChromePopupWindow: function (windowParams) {192 //qm.chrome.chromeDebug();193 if(!window.qm.chrome.canShowChromePopups()){return;}194 // var chromeWindowId = qm.chrome.createPopupIfNoWindowIdInLocalStorage(windowParams);195 // if(!chromeWindowId){return;}196 //qm.chrome.getCurrentWindowAndFocusOrCreateNewPopup(windowParams);197 qm.chrome.getAllWindowsFocusOrCreateNewPopup(windowParams);198 //qm.chrome.getWindowByIdAndFocusOrCreateNewPopup(chromeWindowId, windowParams);199 },200 openFullInbox: function (focusWindow, notificationId) {201 var windowParams = qm.chrome.windowParams.fullInboxWindowParams;202 if(focusWindow){windowParams.focused = true;}203 qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.fullInboxWindowParams);204 console.error('notificationId is not a json object and is not moodReportNotification. Opening Reminder Inbox', notificationId);205 },206 openLoginWindow: function(){207 var windowParams = qm.chrome.windowParams.loginWindowParams;208 windowParams.focused = true;209 qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.loginWindowParams);210 },211 openMeasurementAddWindow: function (focusWindow, notificationId) {212 var windowParams = qm.chrome.windowParams.fullInboxWindowParams;213 if(focusWindow){windowParams.focused = true;}214 qm.chrome.windowParams.fullInboxWindowParams.url = "index.html#/app/measurement-add/?trackingReminderObject=" + notificationId;215 qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.fullInboxWindowParams);216 },217 scheduleGenericChromeExtensionNotification: function() {218 var intervalInMinutes = parseInt(qm.storage.getItem(qm.items.notificationInterval) || "60");219 qmLog.info('scheduleGenericChromeExtensionNotification: Reminder notification interval is ' + intervalInMinutes + ' minutes');220 var alarmInfo = {periodInMinutes: intervalInMinutes};221 qmLog.info('scheduleGenericChromeExtensionNotification: clear genericTrackingReminderNotificationAlarm');222 chrome.alarms.clear("genericTrackingReminderNotificationAlarm");223 qmLog.info('scheduleGenericChromeExtensionNotification: create genericTrackingReminderNotificationAlarm', null, alarmInfo);224 chrome.alarms.create("genericTrackingReminderNotificationAlarm", alarmInfo);225 qmLog.info('Alarm set, every ' + intervalInMinutes + ' minutes');226 },227 scheduleChromeExtensionNotificationWithTrackingReminder: function(trackingReminder) {228 var alarmInfo = {};229 alarmInfo.when = trackingReminder.nextReminderTimeEpochSeconds * 1000;230 alarmInfo.periodInMinutes = trackingReminder.reminderFrequency / 60;231 var alarmName = qm.chrome.createChromeAlarmNameFromTrackingReminder(trackingReminder);232 alarmName = JSON.stringify(alarmName);233 chrome.alarms.getAll(function(alarms) {234 var hasAlarm = alarms.some(function(oneAlarm) {return oneAlarm.name === alarmName;});235 if (hasAlarm) {qmLog.info(null, 'Already have an alarm for ' + alarmName, null);}236 if (!hasAlarm) {237 chrome.alarms.create(alarmName, alarmInfo);238 qmLog.info(null, 'Created alarm for alarmName ' + alarmName, null, alarmInfo);239 }240 });241 },242 createChromeAlarmNameFromTrackingReminder: function (trackingReminder) {243 return {244 trackingReminderId: trackingReminder.id,245 variableName: trackingReminder.variableName,246 defaultValue: trackingReminder.defaultValue,247 unitAbbreviatedName: trackingReminder.unitAbbreviatedName,248 periodInMinutes: trackingReminder.reminderFrequency / 60,249 reminderStartTime: trackingReminder.reminderStartTime,250 startTrackingDate: trackingReminder.startTrackingDate,251 variableCategoryName: trackingReminder.variableCategoryName,252 valence: trackingReminder.valence,253 reminderEndTime: trackingReminder.reminderEndTime254 };255 },256 showRatingOrInboxPopup: function () {257 qm.userHelper.getUserFromLocalStorageOrApi(function (user) {258 if(!user.pushNotificationsEnabled){259 qmLog.pushDebug("Not showing chrome popup because notifications are disabled");260 return;261 }262 qm.notifications.refreshIfEmptyOrStale(function () {263 if(!qm.notifications.getNumberInGlobalsOrLocalStorage()){264 qmLog.info("No notifications not opening popup");265 return false;266 }267 if(qm.getUser().combineNotifications){268 qm.chrome.createSmallInboxNotification();269 return;270 }271 window.trackingReminderNotification = window.qm.notifications.getMostRecentRatingNotificationNotInSyncQueue();272 if(window.trackingReminderNotification){273 qm.chrome.showRatingPopup(window.trackingReminderNotification);274 } else if (qm.storage.getItem(qm.items.useSmallInbox)) {275 qmLog.info("No rating notifications so opening compactInboxWindow popup");276 qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.compactInboxWindowParams);277 } else if (qm.notifications.getNumberInGlobalsOrLocalStorage()) {278 qmLog.info("Got an alarm so checkTimePastNotificationsAndExistingPopupAndShowPopupIfNecessary(alarm)");279 qm.chrome.createSmallInboxNotification();280 }281 }, function (err) {282 qmLog.error("Not showing popup because of notification refresh error: "+ err);283 });284 });285 },286 showRatingPopup: function(trackingReminderNotification){287 qmLog.info("Opening rating notification popup");288 var getChromeRatingNotificationParams = function(trackingReminderNotification){289 if(!trackingReminderNotification){trackingReminderNotification = qm.notifications.getMostRecentRatingNotificationNotInSyncQueue();}290 return { url: qm.notifications.getRatingNotificationPath(trackingReminderNotification), type: 'panel', top: screen.height - 150,291 left: screen.width - 380, width: 390, height: 110, focused: true};292 };293 if(trackingReminderNotification){294 window.trackingReminderNotification = trackingReminderNotification;295 } else {296 window.trackingReminderNotification = qm.notifications.getMostRecentRatingNotificationNotInSyncQueue();297 }298 if(window.trackingReminderNotification){299 qm.getClientId(function (clientId) {300 qm.chrome.openOrFocusChromePopupWindow(getChromeRatingNotificationParams(window.trackingReminderNotification));301 });302 }303 window.qm.chrome.updateChromeBadge(0);304 },305 showSignInNotification: function() {306 if(!qm.platform.isChromeExtension()){return;}307 var notificationId = 'signin';308 chrome.notifications.create(notificationId, qm.chrome.windowParams.signInNotificationParams, function (id) {});309 },310 updateChromeBadge: function(numberOfNotifications){311 var text = "";312 if(qm.platform.isChromeExtension() && typeof chrome.browserAction !== "undefined"){313 if(numberOfNotifications){text = numberOfNotifications.toString();}314 if(numberOfNotifications > 9){text = "?";}315 chrome.browserAction.setBadgeText({text: text});316 }317 }318};319if(typeof screen !== "undefined"){320 function multiplyScreenHeight(factor) {321 if(typeof screen === "undefined"){return false;}322 return parseInt(factor * screen.height);323 }324 function multiplyScreenWidth(factor) {325 if(typeof screen === "undefined"){return false;}326 return parseInt(factor * screen.height);327 }328 qm.chrome.windowParams = {329 introWindowParams: { url: "index.html#/app/intro", type: 'panel', top: multiplyScreenHeight(0.2), left: multiplyScreenWidth(0.4), width: 450, height: 750, focused: true},330 facesWindowParams: { url: "android_popup.html", type: 'panel', top: screen.height - 150, left: screen.width - 380, width: 390, height: 110, focused: true},331 loginWindowParams: { url: "index.html#/app/login", type: 'panel', top: multiplyScreenHeight(0.2), left: multiplyScreenWidth(0.4), width: 450, height: 750, focused: true},332 fullInboxWindowParams: { url: "index.html#/app/reminders-inbox", type: 'panel', top: screen.height - 800, left: screen.width - 455, width: 450, height: 750},333 compactInboxWindowParams: { url: "index.html#/app/reminders-inbox-compact", type: 'panel', top: screen.height - 360 - 30, left: screen.width - 350, width: 350, height: 360},334 inboxNotificationParams: { type: "basic", title: "How are you?", message: "Click to open reminder inbox", iconUrl: "img/icons/icon_700.png", priority: 2},335 signInNotificationParams: { type: "basic", title: "How are you?", message: "Click to sign in and record a measurement", iconUrl: "img/icons/icon_700.png", priority: 2},336 };337}338if(qm.platform.isChromeExtension()){339 qm.chrome.initialize();...

Full Screen

Full Screen

chrome_spec.js

Source:chrome_spec.js Github

copy

Full Screen

...27 kill: sinon.stub().returns(),28 }29 this.onCriEvent = (event, data, options) => {30 this.criClient.on.withArgs(event).yieldsAsync(data)31 return chrome.open('chrome', 'http://', options, this.automation)32 .then(() => {33 this.criClient.on = undefined34 })35 }36 sinon.stub(chrome, '_writeExtension').resolves('/path/to/ext')37 sinon.stub(chrome, '_connectToChromeRemoteInterface').resolves(this.criClient)38 sinon.stub(plugins, 'execute').callThrough()39 sinon.stub(utils, 'launch').resolves(this.launchedBrowser)40 sinon.stub(utils, 'getProfileDir').returns('/profile/dir')41 sinon.stub(utils, 'ensureCleanCache').resolves('/profile/dir/CypressCache')42 this.readJson = sinon.stub(fs, 'readJson')43 this.readJson.withArgs('/profile/dir/Default/Preferences').rejects({ code: 'ENOENT' })44 this.readJson.withArgs('/profile/dir/Default/Secure Preferences').rejects({ code: 'ENOENT' })45 this.readJson.withArgs('/profile/dir/Local State').rejects({ code: 'ENOENT' })46 // port for Chrome remote interface communication47 sinon.stub(utils, 'getPort').resolves(50505)48 })49 afterEach(function () {50 expect(this.criClient.ensureMinimumProtocolVersion).to.be.calledOnce51 })52 it('focuses on the page, calls CRI Page.visit, enables Page events, and sets download behavior', function () {53 return chrome.open('chrome', 'http://', {}, this.automation)54 .then(() => {55 expect(utils.getPort).to.have.been.calledOnce // to get remote interface port56 expect(this.criClient.send.callCount).to.equal(4)57 expect(this.criClient.send).to.have.been.calledWith('Page.bringToFront')58 expect(this.criClient.send).to.have.been.calledWith('Page.navigate')59 expect(this.criClient.send).to.have.been.calledWith('Page.enable')60 expect(this.criClient.send).to.have.been.calledWith('Page.setDownloadBehavior')61 })62 })63 it('is noop without before:browser:launch', function () {64 return chrome.open('chrome', 'http://', {}, this.automation)65 .then(() => {66 expect(plugins.execute).not.to.be.called67 })68 })69 it('is noop if newArgs are not returned', function () {70 const args = []71 sinon.stub(chrome, '_getArgs').returns(args)72 sinon.stub(plugins, 'has').returns(true)73 plugins.execute.resolves(null)74 return chrome.open('chrome', 'http://', {}, this.automation)75 .then(() => {76 // to initialize remote interface client and prepare for true tests77 // we load the browser with blank page first78 expect(utils.launch).to.be.calledWith('chrome', 'about:blank', args)79 })80 })81 it('sets default window size in headless mode', function () {82 chrome._writeExtension.restore()83 return chrome.open({ isHeadless: true, isHeaded: false }, 'http://', {}, this.automation)84 .then(() => {85 const args = utils.launch.firstCall.args[2]86 expect(args).to.include.members([87 '--headless',88 '--window-size=1280,720',89 ])90 })91 })92 it('does not load extension in headless mode', function () {93 chrome._writeExtension.restore()94 return chrome.open({ isHeadless: true, isHeaded: false }, 'http://', {}, this.automation)95 .then(() => {96 const args = utils.launch.firstCall.args[2]97 expect(args).to.include.members([98 '--headless',99 '--remote-debugging-port=50505',100 '--remote-debugging-address=127.0.0.1',101 '--user-data-dir=/profile/dir',102 '--disk-cache-dir=/profile/dir/CypressCache',103 ])104 })105 })106 it('uses a custom profilePath if supplied', function () {107 chrome._writeExtension.restore()108 utils.getProfileDir.restore()109 const profilePath = '/home/foo/snap/chromium/current'110 const fullPath = `${profilePath}/Cypress/chromium-stable/interactive`111 this.readJson.withArgs(`${fullPath}/Default/Preferences`).rejects({ code: 'ENOENT' })112 this.readJson.withArgs(`${fullPath}/Default/Secure Preferences`).rejects({ code: 'ENOENT' })113 this.readJson.withArgs(`${fullPath}/Local State`).rejects({ code: 'ENOENT' })114 return chrome.open({115 isHeadless: true,116 isHeaded: false,117 profilePath,118 name: 'chromium',119 channel: 'stable',120 }, 'http://', {}, this.automation)121 .then(() => {122 const args = utils.launch.firstCall.args[2]123 expect(args).to.include.members([124 `--user-data-dir=${fullPath}`,125 ])126 })127 })128 it('DEPRECATED: normalizes --load-extension if provided in plugin', function () {129 plugins.register('before:browser:launch', (browser, config) => {130 return Promise.resolve(['--foo=bar', '--load-extension=/foo/bar/baz.js'])131 })132 const pathToTheme = extension.getPathToTheme()133 const onWarning = sinon.stub()134 return chrome.open('chrome', 'http://', { onWarning }, this.automation)135 .then(() => {136 const args = utils.launch.firstCall.args[2]137 expect(args).to.deep.eq([138 '--foo=bar',139 `--load-extension=/foo/bar/baz.js,/path/to/ext,${pathToTheme}`,140 '--user-data-dir=/profile/dir',141 '--disk-cache-dir=/profile/dir/CypressCache',142 ])143 expect(onWarning).calledOnce144 })145 })146 it('normalizes --load-extension if provided in plugin', function () {147 plugins.register('before:browser:launch', (browser, config) => {148 return Promise.resolve({149 args: ['--foo=bar', '--load-extension=/foo/bar/baz.js'],150 })151 })152 const pathToTheme = extension.getPathToTheme()153 return chrome.open('chrome', 'http://', {}, this.automation)154 .then(() => {155 const args = utils.launch.firstCall.args[2]156 expect(args).to.include.members([157 '--foo=bar',158 `--load-extension=/foo/bar/baz.js,/path/to/ext,${pathToTheme}`,159 '--user-data-dir=/profile/dir',160 '--disk-cache-dir=/profile/dir/CypressCache',161 ])162 })163 })164 it('normalizes multiple extensions from plugins', function () {165 plugins.register('before:browser:launch', (browser, config) => {166 return Promise.resolve({ args: ['--foo=bar', '--load-extension=/foo/bar/baz.js,/quux.js'] })167 })168 const pathToTheme = extension.getPathToTheme()169 const onWarning = sinon.stub()170 return chrome.open('chrome', 'http://', { onWarning }, this.automation)171 .then(() => {172 const args = utils.launch.firstCall.args[2]173 expect(args).to.include.members([174 '--foo=bar',175 `--load-extension=/foo/bar/baz.js,/quux.js,/path/to/ext,${pathToTheme}`,176 '--user-data-dir=/profile/dir',177 '--disk-cache-dir=/profile/dir/CypressCache',178 ])179 expect(onWarning).not.calledOnce180 })181 })182 it('cleans up an unclean browser profile exit status', function () {183 this.readJson.withArgs('/profile/dir/Default/Preferences').resolves({184 profile: {185 exit_type: 'Abnormal',186 exited_cleanly: false,187 },188 })189 sinon.stub(fs, 'outputJson').resolves()190 return chrome.open('chrome', 'http://', {}, this.automation)191 .then(() => {192 expect(fs.outputJson).to.be.calledWith('/profile/dir/Default/Preferences', {193 profile: {194 exit_type: 'Normal',195 exited_cleanly: true,196 },197 })198 })199 })200 it('calls cri client close on kill', function () {201 // need a reference here since the stub will be monkey-patched202 const {203 kill,204 } = this.launchedBrowser205 return chrome.open('chrome', 'http://', {}, this.automation)206 .then(() => {207 expect(this.launchedBrowser.kill).to.be.a('function')208 return this.launchedBrowser.kill()209 }).then(() => {210 expect(this.criClient.close).to.be.calledOnce211 expect(kill).to.be.calledOnce212 })213 })214 it('rejects if CDP version check fails', function () {215 this.criClient.ensureMinimumProtocolVersion.rejects()216 return expect(chrome.open('chrome', 'http://', {}, this.automation)).to.be.rejectedWith('Cypress requires at least Chrome 64.')217 })218 // https://github.com/cypress-io/cypress/issues/9265219 it('respond ACK after receiving new screenshot frame', function () {220 const frameMeta = { data: Buffer.from(''), sessionId: '1' }221 const write = sinon.stub()222 const options = { onScreencastFrame: write }223 return this.onCriEvent('Page.screencastFrame', frameMeta, options)224 .then(() => {225 expect(this.criClient.send).to.have.been.calledWith('Page.startScreencast')226 expect(write).to.have.been.calledWith(frameMeta)227 expect(this.criClient.send).to.have.been.calledWith('Page.screencastFrameAck', { sessionId: frameMeta.sessionId })228 })229 })230 describe('downloads', function () {...

Full Screen

Full Screen

runOpen.test.js

Source:runOpen.test.js Github

copy

Full Screen

1'use strict';2const opn = require('opn');3const runOpen = require('../../../lib/utils/runOpen');4jest.mock('opn');5describe('runOpen util', () => {6 afterEach(() => {7 opn.mockClear();8 });9 describe('should open browser', () => {10 beforeEach(() => {11 opn.mockImplementation(() => Promise.resolve());12 });13 it('on specify URL', () => {14 return runOpen('https://example.com', {}, console).then(() => {15 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`16 Array [17 "https://example.com",18 Object {19 "wait": false,20 },21 ]22 `);23 });24 });25 it('on specify URL with page', () => {26 return runOpen(27 'https://example.com',28 { openPage: '/index.html' },29 console30 ).then(() => {31 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`32 Array [33 "https://example.com/index.html",34 Object {35 "wait": false,36 },37 ]38 `);39 });40 });41 it('on specify URL with page inside array', () => {42 return runOpen(43 'https://example.com',44 { openPage: ['/index.html'] },45 console46 ).then(() => {47 expect(opn.mock.calls[0]).toMatchSnapshot();48 });49 });50 it('on specify URL with multiple pages inside array', () => {51 return runOpen(52 'https://example.com',53 { openPage: ['/index.html', '/index2.html'] },54 console55 ).then(() => {56 expect(opn.mock.calls[0]).toMatchSnapshot();57 expect(opn.mock.calls[1]).toMatchSnapshot();58 });59 });60 it('on specify URL in Google Chrome', () => {61 return runOpen(62 'https://example.com',63 { open: 'Google Chrome' },64 console65 ).then(() => {66 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`67 Array [68 "https://example.com",69 Object {70 "app": "Google Chrome",71 "wait": false,72 },73 ]74 `);75 });76 });77 it('on specify URL with page in Google Chrome ', () => {78 return runOpen(79 'https://example.com',80 { open: 'Google Chrome', openPage: '/index.html' },81 console82 ).then(() => {83 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`84 Array [85 "https://example.com/index.html",86 Object {87 "app": "Google Chrome",88 "wait": false,89 },90 ]91 `);92 });93 });94 it('on specify absolute https URL with page in Google Chrome ', () => {95 return runOpen(96 'https://example.com',97 { open: 'Google Chrome', openPage: 'https://example2.com' },98 console99 ).then(() => {100 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`101 Array [102 "https://example2.com",103 Object {104 "app": "Google Chrome",105 "wait": false,106 },107 ]108 `);109 });110 });111 it('on specify absolute http URL with page in Google Chrome ', () => {112 return runOpen(113 'https://example.com',114 { open: 'Google Chrome', openPage: 'http://example2.com' },115 console116 ).then(() => {117 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`118 Array [119 "http://example2.com",120 Object {121 "app": "Google Chrome",122 "wait": false,123 },124 ]125 `);126 });127 });128 });129 it('on specify multiple absolute https URLs with pages in Google Chrome ', () => {130 return runOpen(131 'https://example.com',132 {133 open: 'Google Chrome',134 openPage: ['https://example2.com', 'https://example3.com'],135 },136 console137 ).then(() => {138 expect(opn.mock.calls[0]).toMatchSnapshot();139 expect(opn.mock.calls[1]).toMatchSnapshot();140 });141 });142 it('on specify one relative URL and one absolute URL with pages in Google Chrome ', () => {143 return runOpen(144 'https://example.com',145 {146 open: 'Google Chrome',147 openPage: ['/index.html', 'https://example2.com'],148 },149 console150 ).then(() => {151 expect(opn.mock.calls[0]).toMatchSnapshot();152 expect(opn.mock.calls[1]).toMatchSnapshot();153 });154 });155 describe('should not open browser', () => {156 const logMock = { warn: jest.fn() };157 beforeEach(() => {158 opn.mockImplementation(() => Promise.reject());159 });160 afterEach(() => {161 logMock.warn.mockClear();162 });163 it('on specify URL and log error', () => {164 return runOpen('https://example.com', {}, logMock).then(() => {165 expect(logMock.warn.mock.calls[0][0]).toMatchInlineSnapshot(166 `"Unable to open \\"https://example.com\\" in browser. If you are running in a headless environment, please do not use the --open flag"`167 );168 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`169 Array [170 "https://example.com",171 Object {172 "wait": false,173 },174 ]175 `);176 });177 });178 it('on specify URL with page and log error', () => {179 return runOpen(180 'https://example.com',181 { openPage: '/index.html' },182 logMock183 ).then(() => {184 expect(logMock.warn.mock.calls[0][0]).toMatchInlineSnapshot(185 `"Unable to open \\"https://example.com/index.html\\" in browser. If you are running in a headless environment, please do not use the --open flag"`186 );187 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`188 Array [189 "https://example.com/index.html",190 Object {191 "wait": false,192 },193 ]194 `);195 });196 });197 it('on specify URL in Google Chrome and log error', () => {198 return runOpen(199 'https://example.com',200 { open: 'Google Chrome' },201 logMock202 ).then(() => {203 expect(logMock.warn.mock.calls[0][0]).toMatchInlineSnapshot(204 `"Unable to open \\"https://example.com\\" in browser: \\"Google Chrome\\". If you are running in a headless environment, please do not use the --open flag"`205 );206 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`207 Array [208 "https://example.com",209 Object {210 "app": "Google Chrome",211 "wait": false,212 },213 ]214 `);215 });216 });217 it('on specify URL with page in Google Chrome and log error ', () => {218 return runOpen(219 'https://example.com',220 { open: 'Google Chrome', openPage: '/index.html' },221 logMock222 ).then(() => {223 expect(logMock.warn.mock.calls[0][0]).toMatchInlineSnapshot(224 `"Unable to open \\"https://example.com/index.html\\" in browser: \\"Google Chrome\\". If you are running in a headless environment, please do not use the --open flag"`225 );226 expect(opn.mock.calls[0]).toMatchInlineSnapshot(`227 Array [228 "https://example.com/index.html",229 Object {230 "app": "Google Chrome",231 "wait": false,232 },233 ]234 `);235 });236 });237 });...

Full Screen

Full Screen

embed_value.js

Source:embed_value.js Github

copy

Full Screen

1describe("embed links", function(){2 var objectify = function (str)3 {4 var hash = {};5 var parts = str.split('&');6 for(var i = 0; i < parts.length; i++)7 {8 var keyValue = parts[i].split('=');9 hash[keyValue[0]] = keyValue[1];10 }11 return hash;12 }13 var checkiFrameCode = function(embedCode, readonly){14 //turn the code into an html element15 var $embediFrame = $(embedCode);16 //read and check the frame attributes17 var width = $embediFrame.attr("width"); 18 var height = $embediFrame.attr("height"); 19 var name = $embediFrame.attr("name"); 20 expect(width).to.be('600');21 expect(height).to.be('400');22 expect(name).to.be(readonly ? "embed_readonly" : "embed_readwrite");23 //parse the url24 var src = $embediFrame.attr("src");25 var questionMark = src.indexOf("?");26 var url = src.substr(0,questionMark);27 var paramsStr = src.substr(questionMark+1);28 var params = objectify(paramsStr);29 var expectedParams = {30 showControls: 'true'31 , showChat: 'true'32 , showLineNumbers: 'true'33 , useMonospaceFont: 'false'34 }35 //check the url36 if(readonly){37 expect(url.indexOf("r.") > 0).to.be(true);38 } else {39 expect(url).to.be(helper.padChrome$.window.location.href);40 }41 42 //check if all parts of the url are like expected43 expect(params).to.eql(expectedParams);44 }45 describe("read and write", function(){46 //create a new pad before each test run47 beforeEach(function(cb){48 helper.newPad(cb);49 this.timeout(60000);50 });51 describe("the share link", function(){52 it("is the actual pad url", function(done){53 var chrome$ = helper.padChrome$; 54 //open share dropdown55 chrome$(".buttonicon-embed").click();56 //get the link of the share field + the actual pad url and compare them57 var shareLink = chrome$("#linkinput").val();58 var padURL = chrome$.window.location.href;59 expect(shareLink).to.be(padURL);60 done();61 });62 });63 describe("the embed as iframe code", function(){64 it("is an iframe with the the correct url parameters and correct size", function(done){65 var chrome$ = helper.padChrome$; 66 //open share dropdown67 chrome$(".buttonicon-embed").click();68 //get the link of the share field + the actual pad url and compare them69 var embedCode = chrome$("#embedinput").val();70 71 checkiFrameCode(embedCode, false)72 done();73 });74 });75 });76 describe("when read only option is set", function(){77 beforeEach(function(cb){78 helper.newPad(cb);79 this.timeout(60000);80 });81 describe("the share link", function(){82 it("shows a read only url", function(done){83 var chrome$ = helper.padChrome$; 84 //open share dropdown85 chrome$(".buttonicon-embed").click();86 chrome$('#readonlyinput').click();87 chrome$('#readonlyinput:checkbox:not(:checked)').attr('checked', 'checked');88 //get the link of the share field + the actual pad url and compare them89 var shareLink = chrome$("#linkinput").val();90 var containsReadOnlyLink = shareLink.indexOf("r.") > 091 expect(containsReadOnlyLink).to.be(true);92 done();93 });94 });95 describe("the embed as iframe code", function(){96 it("is an iframe with the the correct url parameters and correct size", function(done){97 var chrome$ = helper.padChrome$; 98 //open share dropdown99 chrome$(".buttonicon-embed").click();100 //check read only checkbox, a bit hacky101 chrome$('#readonlyinput').click();102 chrome$('#readonlyinput:checkbox:not(:checked)').attr('checked', 'checked');103 //get the link of the share field + the actual pad url and compare them104 var embedCode = chrome$("#embedinput").val();105 106 checkiFrameCode(embedCode, true);107 108 done();109 });110 });111 });...

Full Screen

Full Screen

chrome.ulti.bybsquochoai.js

Source:chrome.ulti.bybsquochoai.js Github

copy

Full Screen

1bschrome = {2 init: function(){3 //Cài đặt openLinkInNewTab cho Chrome <p>Em có thể <a data-href="chrome://extensions/configureCommands" target="_blank" data-chrome="openLinkInNewTab">bấm vào đây để <b>cài đặt phím tắt</b> cho phần mềm</a></p>4 $("[data-chrome='openLinkInNewTab']").click(function(){5 chrome.tabs.create({url: $(this).data('href')}, function(){})6 return false;7 })8 //<button class="btn btn-warning" data-chrome-openExtensionLink data-href="/bsquochoai_plugins/Chromedothi_by_hoai/index.html">Mở và thử ngay</button>9 $("[data-chrome-openExtensionLink]").click(function(){10 chrome.tabs.create({url: chrome.runtime.getURL($(this).data('href'))}, function(){})11 return false;12 })13 }14}15function bscopy(b){16 var input = document.createElement('textarea');17 document.body.appendChild(input);18 input.value = b;19 input.focus();20 input.select();21 document.execCommand('Copy');22 input.remove();...

Full Screen

Full Screen

local-chrome.js

Source:local-chrome.js Github

copy

Full Screen

1import browserTools from 'testcafe-browser-tools';2import { killBrowserProcess } from '../../../../../utils/process';3import BrowserStarter from '../../../utils/browser-starter';4import { buildChromeArgs } from './build-chrome-args';5const browserStarter = new BrowserStarter();6export async function start (pageUrl, { browserName, config, cdpPort, tempProfileDir, inDocker }) {7 const chromeInfo = await browserTools.getBrowserInfo(config.path || browserName);8 const chromeOpenParameters = Object.assign({}, chromeInfo);9 chromeOpenParameters.cmd = buildChromeArgs({ config, cdpPort, platformArgs: chromeOpenParameters.cmd, tempProfileDir, inDocker });10 await browserStarter.startBrowser(chromeOpenParameters, pageUrl);11}12export async function stop ({ browserId }) {13 // NOTE: Chrome on Linux closes only after the second SIGTERM signall14 if (!await killBrowserProcess(browserId))15 await killBrowserProcess(browserId);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Visits the Kitchen Sink', function() {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', () => {2 it('Does not do much!', () => {3 expect(true).to.equal(true)4 })5 it('Visit the Kitchen Sink', () => {6 })7 it('Finds an element', () => {8 cy.contains('type').click()9 cy.url().should('include', '/commands/actions')10 })11 it('clicks the link "type"', () => {12 cy.contains('type').click()13 cy.url().should('include', '/commands/actions')14 })15 it('clicks the link "type"', () => {16 cy.contains('type').click()17 cy.url().should('include', '/commands/actions')18 })19 it('clicks the link "type"', () => {20 cy.contains('type').click()21 cy.url().should('include', '/commands/actions')22 })23 it('clicks the link "type"', () => {24 cy.contains('type').click()25 cy.url().should('include', '/commands/actions')26 })27 it('clicks the link "type"', () => {28 cy.contains('type').click()29 cy.url().should('include', '/commands/actions')30 })31 it('clicks the link "type"', () => {32 cy.contains('type').click()

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 })6})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.get('.gLFyf').type('Cypress')4 cy.get('.gNO89b').click()5 cy.get('.LC20lb').click()6 cy.get('.header-nav-link').eq(1).click()7 cy.get('.header-nav-link').eq(2).click()8 cy.get('.header-nav-link').eq(3).click()9 cy.get('.header-nav-link').eq(4).click()10 cy.get('.header-nav-link').eq(5).click()11 cy.get('.header-nav-link').eq(6).click()12 cy.get('.header-nav-link').eq(7).click()13 cy.get('.header-nav-link').eq(8).click()14 cy.get('.header-nav-link').eq(9).click()15 cy.get('.header-nav-link').eq(10).click()16 cy.get('.header-nav-link').eq(11).click()17 cy.get('.header-nav-link').eq(12).click()18 cy.get('.header-nav-link').eq(13).click()19 cy.get('.header-nav-link').eq(14).click()20 cy.get('.header-nav-link').eq(15).click()21 cy.get('.header-nav-link').eq(16).click()22 cy.get('.header-nav-link').eq(17).click()23 cy.get('.header-nav-link').eq(18).click()24 cy.get('.header-nav-link').eq(19).click()25 cy.get('.header-nav-link').eq(20).click()26 cy.get('.header-nav-link').eq(21).click()27 cy.get('.header-nav-link').eq(22).click()28 cy.get('.header-nav-link').eq(23).click()29 cy.get('.header-nav-link').eq(24).click()30 cy.get('.header-nav-link').eq(25).click()31 cy.get('.header-nav-link').eq(26).click()32 cy.get('.header-nav-link').eq(27).click()33 cy.get('.header-nav-link').eq(28).click()34 cy.get('.header-nav-link').eq(29).click()35 cy.get('.header-nav-link').eq(30).click()36 cy.get('.header-nav-link').eq(31).click()

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

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