Best JavaScript code snippet using cypress
runtime-checks.test.js
Source: runtime-checks.test.js
1'use strict'2/* eslint-env browser, webextensions */3const { describe, it, before, beforeEach, after } = require('mocha')4const { expect } = require('chai')5const browser = require('sinon-chrome')6const { createRuntimeChecks } = require('../../../add-on/src/lib/runtime-checks')7const promiseStub = (result) => () => Promise.resolve(result)8describe('runtime-checks.js', function () {9 before(() => {10 global.browser = browser11 global.chrome = {}12 })13 beforeEach(function () {14 browser.flush()15 })16 describe('isFirefox', function () {17 beforeEach(function () {18 browser.flush()19 })20 it('should return true when in Firefox runtime', async function () {21 browser.runtime.getBrowserInfo = promiseStub({ name: 'Firefox' })22 const runtime = await createRuntimeChecks(browser)23 expect(runtime.isFirefox).to.equal(true)24 })25 it('should return false when not in Firefox runtime', async function () {26 browser.runtime.getBrowserInfo = promiseStub({ name: 'SomethingElse' })27 const runtime = await createRuntimeChecks(browser)28 expect(runtime.isFirefox).to.equal(false)29 })30 })31 describe('requiresXHRCORSfix', function () {32 beforeEach(function () {33 browser.flush()34 })35 it('should return true when in Firefox runtime < 69', async function () {36 browser.runtime.getBrowserInfo = promiseStub({ name: 'Firefox', version: '68.0.0' })37 const runtime = await createRuntimeChecks(browser)38 expect(runtime.requiresXHRCORSfix).to.equal(true)39 })40 it('should return false when in Firefox runtime >= 69', async function () {41 browser.runtime.getBrowserInfo = promiseStub({ name: 'Firefox', version: '69.0.0' })42 const runtime = await createRuntimeChecks(browser)43 expect(runtime.requiresXHRCORSfix).to.equal(false)44 })45 it('should return false when if getBrowserInfo is not present', async function () {46 browser.runtime.getBrowserInfo = undefined47 const runtime = await createRuntimeChecks(browser)48 expect(runtime.requiresXHRCORSfix).to.equal(false)49 })50 })51 describe('isAndroid', function () {52 beforeEach(function () {53 browser.flush()54 })55 it('should return true when in Android runtime', async function () {56 browser.runtime.getPlatformInfo.returns({ os: 'android' })57 const runtime = await createRuntimeChecks(browser)58 expect(runtime.isAndroid).to.equal(true)59 })60 it('should return false when not in Android runtime', async function () {61 browser.runtime.getPlatformInfo.returns({ name: 'SomethingElse' })62 const runtime = await createRuntimeChecks(browser)63 expect(runtime.isAndroid).to.equal(false)64 })65 })66 describe('hasNativeProtocolHandler', function () {67 beforeEach(function () {68 browser.flush()69 })70 it('should return true when browser.protocol namespace is present', async function () {71 // pretend API is in place72 browser.protocol = {}73 browser.protocol.registerStringProtocol = () => Promise.resolve({})74 const runtime = await createRuntimeChecks(browser)75 expect(runtime.hasNativeProtocolHandler).to.equal(true)76 })77 it('should return false browser.protocol APIs are missing', async function () {78 // API is missing79 browser.protocol = undefined80 const runtime = await createRuntimeChecks(browser)81 expect(runtime.hasNativeProtocolHandler).to.equal(false)82 })83 })84 after(function () {85 delete global.browser86 browser.flush()87 })...
background.js
Source: background.js
2// https://ccsearch.creativecommons.org/photos/de53a802-3342-4886-881d-59cb7f50d0eb3// https://www.flickr.com/photos/89978190@N00/31515985384// Init5let browserName = "NonFirefox"; // Default value6// browser.runtime.getBrowserInfo() is not available7// https://github.com/mozilla/webextension-polyfill/issues/1168async function init(){9 // Get the browserName (likely will only work in case it's Firefox)10 if(browser.runtime.getBrowserInfo !== undefined){11 let info = await browser.runtime.getBrowserInfo();12 browserName = info.name;13 }14 15 // Events16 browser.browserAction.onClicked.addListener(async (tab) => {17 await deleteCookies(tab);18 await browser.tabs.reload();19 // Page was reloaded20 });21}22init();23// Functionality24async function deleteCookies(tab){ 25 let cookies = await browser.cookies.getAll(...
chrome-detector.js
Source: chrome-detector.js
1const BROWSERS = {2 CHROME: "CHROME",3 FIREFOX: "FIREFOX",4};5let BROWSER_FEATURES; // eslint-disable-line6let CURRENT_BROWSER = BROWSERS.CHROME;7let CURRENT_BROWSER_VERSION;8const setFeatures = (browser, version) => {9 // defaults10 const features = {11 multitab: false,12 accessKeys: true,13 };14 if (browser === BROWSERS.FIREFOX && version >= 63) {15 features.multitab = true;16 }17 if (browser === BROWSERS.FIREFOX && version < 63) {18 features.accessKeys = false;19 }20 return features;21};22if (typeof browser === "undefined") {23 if (chrome) {24 CURRENT_BROWSER = BROWSERS.CHROME; // eslint-disable-line25 }26} else if (browser.runtime.getBrowserInfo) {27 browser.runtime28 .getBrowserInfo()29 .then((res) => {30 if (res.name === "Firefox") {31 CURRENT_BROWSER = BROWSERS.FIREFOX; // eslint-disable-line32 CURRENT_BROWSER_VERSION = parseFloat(res.version);33 } else {34 CURRENT_BROWSER = BROWSERS.CHROME;35 }36 BROWSER_FEATURES = setFeatures(CURRENT_BROWSER, CURRENT_BROWSER_VERSION);37 })38 .catch((e) => {39 console.log("Failed to get browser version", e); // eslint-disable-line40 CURRENT_BROWSER = BROWSERS.CHROME;41 BROWSER_FEATURES = setFeatures(CURRENT_BROWSER, CURRENT_BROWSER_VERSION);42 });43} else {44 // If we don't have browser.runtime.getBrowserInfo, assume it's Chrome45 // Big assumption, but browser.runtime.getBrowserInfo is not well supported46 CURRENT_BROWSER = BROWSERS.CHROME; // eslint-disable-line47 BROWSER_FEATURES = setFeatures(CURRENT_BROWSER, CURRENT_BROWSER_VERSION); // eslint-disable-line...
ua.js
Source: ua.js
1// UA can be overridden by about:config in FF or devtools in Chrome2// so we'll test for window.chrome.app which is only defined in Chrome3// and for browser.runtime.getBrowserInfo in Firefox 51+4/** @typedef UAExtras5 * @property {false | number} isChrome - Chrome/ium version number or `false`6 * @property {Boolean | number} isFirefox - boolean initially, Firefox version number when ready7 */8/** @typedef UAInjected9 * @property {chrome.runtime.PlatformInfo.arch} arch10 * @property {chrome.runtime.PlatformInfo.os} os11 * @property {string} browserName12 * @property {string} browserVersion13 */14/** @type {UAInjected & UAExtras} */15const ua = {};16export default ua;17// using non-enumerable properties that won't be sent to content scripts via GetInjected18Object.defineProperties(ua, {19 isChrome: {20 value: global.chrome?.app && +navigator.userAgent.match(/Chrom\S+?\/(\d+)|$/)[1] || false,21 },22 isFirefox: {23 // will be replaced with the version number in ready()24 value: !!browser.runtime.getBrowserInfo,25 configurable: true,26 },27 ready: {28 value: Promise.all([29 browser.runtime.getPlatformInfo(),30 browser.runtime.getBrowserInfo?.(),31 ]).then(([{ os, arch }, { name, version } = {}]) => {32 Object.assign(ua, {33 arch,34 os,35 browserName: name?.toLowerCase() || 'chrome',36 browserVersion: version || navigator.userAgent.match(/Chrom\S+?\/(\S+)|$/)[1],37 });38 if (ua.isFirefox) {39 Object.defineProperty(ua, 'isFirefox', {40 value: parseFloat(version),41 });42 }43 }),44 },...
url.test.js
Source: url.test.js
1import test from 'ava';2import nisemono from 'nisemono';3import { init, extractDomain, getFaviconUrl } from '../../src/utils/url';4const validUrl = 'http://example.com/test/index.html';5const fileUrl = 'file:///test/test.html';6const extensionUrl = 'moz-extension://12345/popup/index.html';7const invalidUrl = 'aaaa';8test('extractDomain returns domain of a url', (t) => {9 t.is(extractDomain(validUrl), 'example.com');10 t.is(extractDomain(invalidUrl), null);11});12const { browser } = global;13const { getBrowserInfo } = browser.runtime;14function setupBrowserInfo(name) {15 browser.runtime.getBrowserInfo = nisemono.func();16 nisemono.expects(browser.runtime.getBrowserInfo).resolves({ name });17}18function restoreBrowserInfo() {19 browser.runtime.getBrowserInfo = getBrowserInfo;20}21test('getFaviconUrl returns favison url from web page url', async (t) => {22 setupBrowserInfo('Firefox');23 await init();24 const faviconUrl = 'https://s2.googleusercontent.com/s2/favicons?domain=example.com';25 t.is(getFaviconUrl(validUrl), faviconUrl);26 t.is(getFaviconUrl(fileUrl), null);27 t.is(getFaviconUrl(extensionUrl), null);28 t.is(getFaviconUrl(invalidUrl), null);29 t.is(getFaviconUrl(null), null);30 setupBrowserInfo('chrome');31 await init();32 t.is(getFaviconUrl(validUrl), `chrome://favicon/${validUrl}`);33 t.is(getFaviconUrl(fileUrl), `chrome://favicon/${fileUrl}`);34 t.is(getFaviconUrl(extensionUrl), `chrome://favicon/${extensionUrl}`);35 t.is(getFaviconUrl(invalidUrl), `chrome://favicon/${invalidUrl}`);36 restoreBrowserInfo();...
runtime-checks.js
Source: runtime-checks.js
...4// this is our kitchen sink for runtime detection5function getBrowserInfo (browser) {6 // browser.runtime.getBrowserInfo is not available in Chromium-based browsers7 if (browser && browser.runtime && browser.runtime.getBrowserInfo) {8 return browser.runtime.getBrowserInfo()9 }10 return Promise.resolve({})11}12function getPlatformInfo (browser) {13 if (browser && browser.runtime && browser.runtime.getPlatformInfo) {14 return browser.runtime.getPlatformInfo()15 }16 return Promise.resolve()17}18async function createRuntimeChecks (browser) {19 // browser20 const { name, version } = await getBrowserInfo(browser)21 const isFirefox = name && (name.includes('Firefox') || name.includes('Fennec'))22 const hasNativeProtocolHandler = !!(browser && browser.protocol && browser.protocol.registerStringProtocol) // TODO: chrome.ipfs support...
url.js
Source: url.js
...3const faviconUrl = 'https://s2.googleusercontent.com/s2/favicons';4let browserInfo = { name: 'chrome' };5export function init() {6 if (browser.runtime.getBrowserInfo) {7 return browser.runtime.getBrowserInfo().then((info) => {8 browserInfo = info;9 });10 }11 return Promise.resolve();12}13export function extractDomain(url) {14 if (!url || url.startsWith('moz-extension:') || url.startsWith('file:')) {15 return null;16 }17 try {18 return new URL(url).hostname;19 } catch (e) {20 return null;21 }...
env.js
Source: env.js
1/* global browser chrome */2export const IS_CHROME = typeof chrome !== "undefined" && Boolean(chrome.app);3export function getBrowserInfo() {4 if (typeof browser !== "undefined" && browser.runtime.getBrowserInfo) {5 return browser.runtime.getBrowserInfo();6 }7 return new Promise(resolve => {8 const match = navigator.userAgent.match(/(firefox|chrome)\/([\d.]+)/i);9 if (match) {10 resolve({11 name: match[1],12 version: match[2]13 });14 } else {15 resolve(null);16 }17 });...
Using AI Code Generation
1const getBrowserInfo = () => {2 return new Promise((resolve, reject) => {3 try {4 browser.runtime.getBrowserInfo((info) => {5 resolve(info);6 });7 } catch (e) {8 reject(e);9 }10 });11};12const getBrowserInfo = () => {13 return new Promise((resolve, reject) => {14 try {15 browser.runtime.getBrowserInfo((info) => {16 resolve(info);17 });18 } catch (e) {19 reject(e);20 }21 });22};23const getBrowserInfo = () => {24 return new Promise((resolve, reject) => {25 try {26 browser.runtime.getBrowserInfo((info) => {27 resolve(info);28 });29 } catch (e) {30 reject(e);31 }32 });33};34const getBrowserInfo = () => {35 return new Promise((resolve, reject) => {36 try {37 browser.runtime.getBrowserInfo((info) => {38 resolve(info);39 });40 } catch (e) {41 reject(e);42 }43 });44};45const getBrowserInfo = () => {46 return new Promise((resolve, reject) => {47 try {48 browser.runtime.getBrowserInfo((info) => {49 resolve(info);50 });51 } catch (e) {52 reject(e);53 }54 });55};56const getBrowserInfo = () => {57 return new Promise((resolve, reject) => {58 try {59 browser.runtime.getBrowserInfo((info) => {60 resolve(info);61 });62 } catch (e) {63 reject(e);64 }65 });66};
Using AI Code Generation
1const getBrowserInfo = () => {2 return cy.window().then((win) => {3 return win.browser.runtime.getBrowserInfo();4 });5};6const getManifest = () => {7 return cy.window().then((win) => {8 return win.browser.runtime.getManifest();9 });10};11const getURL = (path) => {12 return cy.window().then((win) => {13 return win.browser.runtime.getURL(path);14 });15};16const reload = () => {17 return cy.window().then((win) => {18 return win.browser.runtime.reload();19 });20};21const requestUpdateCheck = () => {22 return cy.window().then((win) => {23 return win.browser.runtime.requestUpdateCheck();24 });25};26const sendMessage = (message) => {27 return cy.window().then((win) => {28 return win.browser.runtime.sendMessage(message);29 });30};31const sendNativeMessage = (nativeApp, message) => {32 return cy.window().then((win) => {33 return win.browser.runtime.sendNativeMessage(nativeApp, message);34 });35};36const setUninstallURL = (url) => {37 return cy.window().then((win) => {38 return win.browser.runtime.setUninstallURL(url);39 });40};41const onBrowserUpdateAvailable = () => {42 return cy.window().then((win) => {43 return win.browser.runtime.onBrowserUpdateAvailable;44 });45};46const onConnect = () => {47 return cy.window().then((win) => {48 return win.browser.runtime.onConnect;49 });50};51const onConnectExternal = () => {52 return cy.window().then((win) => {53 return win.browser.runtime.onConnectExternal;54 });55};56const onInstalled = () => {
Using AI Code Generation
1describe('browser.runtime.getBrowserInfo', () => {2 it('can get browser info', () => {3 cy.window().then((win) => {4 win.browser.runtime.getBrowserInfo().then((info) => {5 expect(info).to.have.property('name')6 })7 })8 })9})10[MIT](LICENSE)
Using AI Code Generation
1describe('browser.runtime.getBrowserInfo', () => {2 it('returns browser info', () => {3 cy.window().then(win => {4 win.browser.runtime.getBrowserInfo().then(info => {5 expect(info).to.have.property('name', 'Firefox')6 })7 })8 })9})10- [cypress-example-kitchensink](
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 cy.window().then(win => {4 win.browser.runtime.getBrowserInfo().then(info => {5 expect(info.name).to.equal('Firefox')6 })7 })8 })9})10const browserRuntimePlugin = require('cypress-browser-runtime-plugin')11module.exports = (on, config) => {12 browserRuntimePlugin(on, config)13}14cy.window().then(win => {15 win.browser.runtime.getBrowserInfo().then(info => {16 expect(info.name).to.equal('Firefox')17 })18})19[MIT](
Cypress does not always executes click on element
How to get current date using cy.clock()
.type() method in cypress when string is empty
Cypress route function not detecting the network request
How to pass files name in array and then iterating for the file upload functionality in cypress
confused with cy.log in cypress
why is drag drop not working as per expectation in cypress.io?
Failing wait for request in Cypress
How to Populate Input Text Field with Javascript
Is there a reliable way to have Cypress exit as soon as a test fails?
2022 here and tested with cypress version: "6.x.x"
until "10.x.x"
You could use { force: true }
like:
cy.get("YOUR_SELECTOR").click({ force: true });
but this might not solve it ! The problem might be more complex, that's why check below
My solution:
cy.get("YOUR_SELECTOR").trigger("click");
Explanation:
In my case, I needed to watch a bit deeper what's going on. I started by pin the click
action like this:
Then watch the console, and you should see something like:
Now click on line Mouse Events
, it should display a table:
So basically, when Cypress executes the click
function, it triggers all those events but somehow my component behave the way that it is detached the moment where click event
is triggered.
So I just simplified the click by doing:
cy.get("YOUR_SELECTOR").trigger("click");
And it worked ????
Hope this will fix your issue or at least help you debug and understand what's wrong.
Check out the latest blogs from LambdaTest on this topic:
When it comes to web automation testing, the first automation testing framework that comes to mind undoubtedly has to be the Selenium framework. Selenium automation testing has picked up a significant pace since the creation of the framework way back in 2004.
We just raised $45 million in a venture round led by Premji Invest with participation from existing investors. Here’s what we intend to do with the money.
Find element by Text in Selenium is used to locate a web element using its text attribute. The text value is used mostly when the basic element identification properties such as ID or Class are dynamic in nature, making it hard to locate the web element.
We are nearing towards the end of 2019, where we are witnessing the introduction of more aligned JavaScript engines from major browser vendors. Which often strikes a major question in the back of our heads as web-developers or web-testers, and that is, whether cross browser testing is still relevant? If all the major browser would move towards a standardized process while configuring their JavaScript engines or browser engines then the chances of browser compatibility issues are bound to decrease right? But does that mean that we can simply ignore cross browser testing?
Web products of top-notch quality can only be realized when the emphasis is laid on every aspect of the product. This is where web automation testing plays a major role in testing the features of the product inside-out. A majority of the web testing community (including myself) have been using the Selenium test automation framework for realizing different forms of web testing (e.g., cross browser testing, functional testing, etc.).
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.
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.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!