Best JavaScript code snippet using cypress
latest_version.js
Source: latest_version.js
1import { spawn, sync } from 'cross-spawn';2import { satisfies } from 'semver';3/**4 * Get latest version of the package available on npmjs.com.5 * If constraint is set then it returns a version satisfying it, otherwise the latest version available is returned.6 *7 * @param {Object} npmOptions Object containing a `useYarn: boolean` attribute8 * @param {string} packageName Name of the package9 * @param {Object} constraint Version range to use to constraint the returned version10 * @return {Promise<string>} Promise resolved with a version11 */12export function latestVersion(npmOptions, packageName, constraint) {13 let getPackageVersions;14 // TODO: Refactor things to hide the package manager details:15 // Create a `PackageManager` interface that expose some functions like `version`, `add` etc16 // and then create classes that handle the npm/yarn/yarn2 specific behavior17 if (npmOptions.useYarn) {18 const yarnVersion = sync('yarn', ['--version'], { silent: true })19 .output.toString('utf8')20 .replace(/,/g, '')21 .replace(/"/g, '');22 if (/^1\.+/.test(yarnVersion)) {23 getPackageVersions = spawnVersionsWithYarn(packageName, constraint);24 } else {25 getPackageVersions = spawnVersionsWithYarn2(packageName, constraint);26 }27 } else {28 getPackageVersions = spawnVersionsWithNpm(packageName, constraint);29 }30 return getPackageVersions.then(versions => {31 if (!constraint) return versions;32 return versions.reverse().find(version => satisfies(version, constraint));33 });34}35/**36 * Get latest version(s) of the package available on npmjs.com using NPM37 *38 * @param {string} packageName Name of the package39 * @param {Object} constraint Version range to use to constraint the returned version40 * @returns {Promise<string|Array<string>>} versions Promise resolved with a version or an array of versions41 */42function spawnVersionsWithNpm(packageName, constraint) {43 return new Promise((resolve, reject) => {44 const command = spawn(45 'npm',46 ['info', packageName, constraint ? 'versions' : 'version', '--json', '--silent'],47 {48 cwd: process.cwd(),49 env: process.env,50 stdio: 'pipe',51 encoding: 'utf-8',52 silent: true,53 }54 );55 command.stdout.on('data', data => {56 try {57 const info = JSON.parse(data);58 if (info.error) {59 reject(new Error(info.error.summary));60 } else {61 resolve(info);62 }63 } catch (e) {64 reject(new Error(`Unable to find versions of ${packageName} using npm`));65 }66 });67 });68}69/**70 * Get latest version(s) of the package available on npmjs.com using Yarn71 *72 * @param {string} packageName Name of the package73 * @param {Object} constraint Version range to use to constraint the returned version74 * @returns {Promise<string|Array<string>>} versions Promise resolved with a version or an array of versions75 */76function spawnVersionsWithYarn(packageName, constraint) {77 return new Promise((resolve, reject) => {78 const command = spawn(79 'yarn',80 ['info', packageName, constraint ? 'versions' : 'version', '--json', '--silent'],81 {82 cwd: process.cwd(),83 env: process.env,84 stdio: 'pipe',85 encoding: 'utf-8',86 silent: true,87 }88 );89 command.stdout.on('data', data => {90 try {91 const info = JSON.parse(data);92 if (info.type === 'inspect') {93 resolve(info.data);94 }95 } catch (e) {96 reject(new Error(`Unable to find versions of ${packageName} using yarn`));97 }98 });99 command.stderr.on('data', data => {100 const info = JSON.parse(data);101 if (info.type === 'error') {102 reject(new Error(info.data));103 }104 });105 });106}107/**108 * Get latest version(s) of the package available on npmjs.com using Yarn 2 a.k.a Berry109 *110 * @param {string} packageName Name of the package111 * @param {Object} constraint Version range to use to constraint the returned version112 * @returns {Promise<string|Array<string>>} versions Promise resolved with a version or an array of versions113 */114function spawnVersionsWithYarn2(packageName, constraint) {115 const field = constraint ? 'versions' : 'version';116 return new Promise((resolve, reject) => {117 const command = spawn('yarn', ['npm', 'info', packageName, '--fields', field, '--json'], {118 cwd: process.cwd(),119 env: process.env,120 stdio: 'pipe',121 encoding: 'utf-8',122 silent: true,123 });124 command.stdout.on('data', data => {125 try {126 const info = JSON.parse(data);127 resolve(info[field]);128 } catch (e) {129 reject(new Error(`Unable to find versions of ${packageName} using yarn 2`));130 }131 });132 command.stderr.on('data', data => {133 const info = JSON.parse(data);134 reject(new Error(info));135 });136 });...
npm-registry.js
Source: npm-registry.js
...41 regClient.get(packageUrl(registry, packageName), requestOptions(token))42 .then(response => Object.keys(response.versions))43 .catch(() => []);44const ensurePackageVersionNotAvailable = async (registry, token, packageName, packageVersion) =>45 getPackageVersions(registry, token, packageName)46 .then(versions => versions.filter(version => version === packageVersion))47 .then(versions => versions.map(async version => unpublish(registry, token, packageName, version)))48 .then(promises => Promise.all(promises))49const unpublishReal = async (registry, token, packageName, version) =>50 regClient.unpublish(51 packageUrl(registry, packageName),52 { version, ...requestOptions(token) });53const getNexusRequestOptions = (url, token) =>54 ({ url, headers: { Authorization: `Bearer ${token}` } });55const unpublishNexusWorkaround_tooWrong = async (registry, token, packageName, version) =>56 request.delete(getNexusRequestOptions(`${packageUrl(registry, packageName)}/-/${packageName}-${version}.tgz`, token))57 .then(result => {58 if ((result.statusCode >= 200 && result.statusCode < 300) || result.statusCode === 404)59 return result;60 throw `${result.statusCode} - ${result.body}`;61 });62const unpublishNexusWorkaround = async (registry, token, packageName, version) =>63 request.delete(getNexusRequestOptions(`${packageUrl(registry, packageName)}`, token))64 .then(result => {65 console.log(`Workaround for Sonatype Nexus 3.12 problems when unpublishing npm packages deleting ALL versions has status ${result.statusCode}`);66 if ((result.statusCode >= 200 && result.statusCode < 300) || result.statusCode === 404)67 return result;68 throw `${result.statusCode} - ${result.body}`;69 });70const unpublish = process.env['NEXUS_WORKAROUND'] === 'true'71 ? unpublishNexusWorkaround72 : unpublishReal;73const ensurePackageVersionAvailable = async (tempDirectory, registry, token, packageName, version) =>74 getPackageVersions(registry, token, packageName)75 .then(versions => versions.filter(v => v === version).length > 0)76 .then(async packagePresent => packagePresent ? true :77 publishInventedPackage(tempDirectory, registry, token, packageName, version));...
PackageVersionsCommand.spec.js
Source: PackageVersionsCommand.spec.js
1const chai = require('chai');2const expect = chai.expect;3const sinon = require('sinon');4const sinonChai = require('sinon-chai');5const chaiAsPromised = require('chai-as-promised');6const PackageVersionsCommand = require('../../../src/commands/package/PackageVersionsCommand');7const PageableStream = require('../../../src/clients/PageableStream');8chai.use(chaiAsPromised);9chai.use(sinonChai);10describe('packageVersionsCommand', () => {11 let packageVersionsCommand;12 const token = 'i8uhkj.token.65ryft';13 const packageReference = 'my.package.ref';14 const validProgram = { args: [15 packageReference16 ]};17 before(() => {18 packageVersionsCommand = new PackageVersionsCommand();19 packageVersionsCommand.barracks = {};20 packageVersionsCommand.userConfiguration = {};21 });22 describe('#validateCommand(program)', () => {23 it('should return false when no argument given', () => {24 // Given25 const program = { args: [] };26 // When27 const result = packageVersionsCommand.validateCommand(program);28 // Then29 expect(result).to.be.false;30 });31 it('should return true when valid reference given', () => {32 // Given33 const program = validProgram;34 // When35 const result = packageVersionsCommand.validateCommand(program);36 // Then37 expect(result).to.be.true;38 });39 });40 describe('#execute(program)', () => {41 it('should return an error when the client request fail', done => {42 // Given43 const error = 'error';44 const program = validProgram;45 packageVersionsCommand.getAuthenticationToken = sinon.stub().returns(Promise.resolve(token));46 packageVersionsCommand.barracks.getPackageVersions = sinon.stub().returns(Promise.reject(error));47 // When / Then48 packageVersionsCommand.execute(program).then(result => {49 done('Should have failed');50 }).catch(err => {51 expect(err).to.be.equals(error);52 expect(packageVersionsCommand.getAuthenticationToken).to.have.been.calledOnce;53 expect(packageVersionsCommand.getAuthenticationToken).to.have.been.calledWithExactly();54 expect(packageVersionsCommand.barracks.getPackageVersions).to.have.been.calledOnce;55 expect(packageVersionsCommand.barracks.getPackageVersions).to.have.been.calledWithExactly(token, packageReference);56 done();57 });58 });59 it('should forward the client response when all is ok', done => {60 // Given61 const response = [ 'aversion', 'anotherversion', 'andonemoreversion' ];62 const program = validProgram;63 packageVersionsCommand.getAuthenticationToken = sinon.stub().returns(Promise.resolve(token));64 packageVersionsCommand.barracks.getPackageVersions = sinon.stub().returns(Promise.resolve(response));65 // When / Then66 packageVersionsCommand.execute(program).then(result => {67 expect(result).to.be.equals(response);68 expect(packageVersionsCommand.getAuthenticationToken).to.have.been.calledOnce;69 expect(packageVersionsCommand.getAuthenticationToken).to.have.been.calledWithExactly();70 expect(packageVersionsCommand.barracks.getPackageVersions).to.have.been.calledOnce;71 expect(packageVersionsCommand.barracks.getPackageVersions).to.have.been.calledWithExactly(token, packageReference);72 done();73 }).catch(err => {74 done(err);75 });76 });77 });...
package-versions.js
Source: package-versions.js
...56 return function (json) {57 return JSON.stringify(json, null, 2).replace(tailOp, leadOp).replace(cuddle, '$1');58 };59 }();60 getPackageVersions(glob.sync('node_modules/*/package.json'), function (e, allVersions) {61 var assertFreshness, error, exitCode, name, used, ver;62 used = {};63 exitCode = 0;64 try {65 assertFreshness = assertVersionMatch.bind(this, allVersions, used);66 for (name in null != pkg.dependencies ? pkg.dependencies : {}) {67 ver = (null != pkg.dependencies ? pkg.dependencies : {})[name];68 assertFreshness(name, ver);69 }70 for (name in null != pkg.devDependencies ? pkg.devDependencies : {}) {71 ver = (null != pkg.devDependencies ? pkg.devDependencies : {})[name];72 assertFreshness(name, ver);73 }74 if (process.argv.indexOf('--dump') >= 0)...
catalog-cache-tests.js
Source: catalog-cache-tests.js
...44 return true; // stop45 });46 test.equal(oneVersion.length, 1); // don't know which it is47 var foos = [];48 _.each(cache.getPackageVersions('foo'), function (v) {49 var depMap = cache.getDependencyMap('foo', v);50 foos.push([v, _.map(depMap, String).sort()]);51 });52 // versions should come out sorted, just like this.53 test.equal(foos,54 [['1.0.0', ['bar@=2.0.0']],55 ['1.0.1', ['?weakly1@1.0.0', '?weakly2',56 'bar@=2.0.0 || =2.0.1', 'bzzz']]]);57 test.throws(function () {58 // package version doesn't exist59 cache.getDependencyMap('foo', '7.0.0');60 });61 var versions = [];62 cache.eachPackage(function (p, vv) {...
applyAndTagVersions.mjs
Source: applyAndTagVersions.mjs
1import fs from 'fs/promises';2import chalk from 'chalk';3import { exec } from '../helpers.mjs';4async function getPackageVersions() {5 const files = await fs.readdir('./packages');6 const versions = {};7 await Promise.all(8 files.map(async (file) => {9 const pkg = JSON.parse(await fs.readFile(`./packages/${file}/package.json`, 'utf8'));10 versions[pkg.name] = pkg.version;11 }),12 );13 return versions;14}15function logDiff(diff) {16 console.log(`Found ${diff.length} packages to release`);17 diff.forEach((row) => {18 console.log(chalk.gray(` - ${row}`));19 });20}21async function createCommit(versions) {22 console.log('Creating git commit');23 let commit = 'Release';24 versions.forEach((version) => {25 commit += `\n- ${version}`;26 });27 await exec('git', ['add', '--all']);28 await exec('git', ['commit', '-m', `'${commit}'`]);29}30async function createTags(versions) {31 console.log('Creating git tags');32 await Promise.all(33 versions.map(async (version) => {34 await exec('git', ['tag', version]);35 }),36 );37}38async function run() {39 // Gather the versions before we apply the new ones40 const prevVersions = await getPackageVersions();41 // Apply them via yarn42 await exec('yarn', ['version', 'apply', '--all']);43 // Now gather the versions again so we can diff44 const nextVersions = await getPackageVersions();45 console.log(prevVersions, nextVersions);46 // Diff the versions and find the new ones47 const diff = [];48 Object.entries(nextVersions).forEach(([name, version]) => {49 if (version !== prevVersions[name]) {50 diff.push(`${name}@${version}`);51 }52 });53 if (diff.length === 0) {54 console.log(chalk.yellow('No packages to release'));55 return;56 }57 logDiff(diff);58 // Create git commit and tags...
index.js
Source: index.js
...6 console.log('no args given')7 console.log('example express')8 process.exit()9}10getPackageVersions(argv._[0], argv._[1], argv.r)11 .then(versions => {12 versions.mainRegVers.forEach(function (v) {13 console.log(v)14 })15 if (versions && argv.r) {16 if (versions.mainOnly && versions.mainOnly instanceof Array && versions.mainOnly.length > 0) {17 console.log(`${Array(25).join('=')} in main reg only ${Array(25).join('=')}`)18 versions.mainOnly.forEach(v => console.log(v))19 }20 if (versions.altOnly && versions.altOnly instanceof Array && versions.altOnly.length > 0) {21 console.log(`${Array(25).join('=')} in ${argv.r} only ${Array(25).join('=')}`)22 versions.altOnly.forEach(v => console.log(v))23 }24 }...
index.test.js
Source: index.test.js
...12 const data = await cnpm.getPackage('cnpm', '1.0.0');13 expect(data.version).toBe('1.0.0');14});15test('getPackageVersions', async () => {16 const data = await cnpm.getPackageVersions('cnpm');17 expect(data['1.0.0']).toBeTruthy();...
Using AI Code Generation
1const getPackageVersions = require('./getPackageVersions');2getPackageVersions().then((versions) => {3 console.log(versions);4});5const { exec } = require('child_process');6const getPackageVersions = () => {7 return new Promise((resolve, reject) => {8 exec('npm list --depth=0', (error, stdout, stderr) => {9 if (error) {10 reject(error);11 return;12 }13 if (stderr) {14 reject(stderr);15 return;16 }17 resolve(stdout);18 });19 });20};21module.exports = getPackageVersions;
Using AI Code Generation
1const { getPackageVersions } = require('@packages/server/lib/util/versions')2getPackageVersions()3.then((versions) => {4 console.log(versions)5})6{7}8{9 "scripts": {10 },11 "devDependencies": {12 }13}14describe('My First Test', () => {15 it('Does not do much!', () => {16 expect(true).to.equal(true)17 })18})
Using AI Code Generation
1describe('Cypress test', () => {2 it('getPackageVersions', () => {3 cy.getPackageVersions('cypress').then((versions) => {4 console.log('Versions:', versions)5 })6 })7})8Cypress.Commands.add('getPackageVersions', (packageName) => {9 return cy.exec(`npm view ${packageName} versions --json`).then((result) => {10 return JSON.parse(result.stdout)11 })12})13declare namespace Cypress {14 interface Chainable {15 getPackageVersions(packageName: string): Cypress.Chainable<any>16 }17}
Using AI Code Generation
1const cypress = require('cypress')2cypress.getPackageVersion().then((version) => {3 console.log(version)4})5{6 "scripts": {7 }8}9const cypress = require('cypress')10cypress.getPackageVersion().then((version) => {11 console.log(version)12})13{14 "scripts": {15 }16}17const cypress = require('cypress')18cypress.getPackageVersion().then((version) => {19 console.log(version)20})21{22 "scripts": {23 }24}25const cypress = require('cypress')26cypress.getPackageVersion().then((version) => {27 console.log(version)28})29{30 "scripts": {31 }32}33const cypress = require('cypress')34cypress.getPackageVersion().then((version) => {35 console.log(version)36})37{38 "scripts": {39 }40}41const cypress = require('cypress')42cypress.getPackageVersion().then((version) => {43 console.log(version)44})45{46 "scripts": {47 }48}49const cypress = require('cypress')50cypress.getPackageVersion().then((version) => {
Using AI Code Generation
1const cypress = require("cypress");2const fs = require("fs");3(async () => {4 const cypressConfig = JSON.parse(5 fs.readFileSync("./cypress.json", "utf-8")6 );7 const latestVersion = await cypress.getPackageVersion(8 );9 console.log("latest version is " + latestVersion);10})();11{12 "scripts": {13 },14 "dependencies": {15 }16}17{18}19const cypress = require("cypress");20const fs = require("fs");21(async () => {22 const cypressConfig = JSON.parse(23 fs.readFileSync("./cypress.json", "utf-8")24 );25 const latestVersion = await cypress.getPackageVersion(26 );27 console.log("latest version is " + latestVersion);28})();29{30 "scripts": {31 },32 "dependencies": {33 }34}
Using AI Code Generation
1const cypress = require('cypress')2const { getPackageVersions } = require('@packages/server/lib/util/versions')3const currentVersion = getPackageVersions().cypress4cypress.getUpdates()5.then((updates) => {6 console.log(updates)7})8{9}10const cypress = require('cypress')11cypress.getUpdates()12.then((updates) => {13 console.log(updates)14})15{16}
Using AI Code Generation
1const getPackageVersions = require('cypress-package-version');2const {expect} = require('chai');3describe('Test package versions', () => {4 it('Check the version of the package you want to check', () => {5 getPackageVersions('package-name').then(version => {6 expect(version).to.equal('1.0.0');7 });8 });9});10describe('Test package versions', () => {11 it('Check the version of the package you want to check', () => {12 cy.getPackageVersions('package-name').then(version => {13 expect(version).to.equal('1.0.0');14 });15 });16});17const getPackageVersions = require('cypress-package-version');18Cypress.Commands.add('getPackageVersions', getPackageVersions);19const getPackageVersions = require('cypress-package-version');20module.exports = (on, config) => {21 on('task', {22 });23};24{25 "devDependencies": {26 }27}28{
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!!