Best JavaScript code snippet using cypress
build.js
Source:build.js
...96 .then(R.tap(logBuiltAllPackages))97 }98 const copyPackages = function () {99 log('#copyPackages')100 return packages.copyAllToDist(distDir())101 }102 const transformSymlinkRequires = function () {103 log('#transformSymlinkRequires')104 return transformRequires(distDir())105 .then((replaceCount) => {106 return la(replaceCount > 5, 'expected to replace more than 5 symlink requires, but only replaced', replaceCount)107 })108 }109 const npmInstallPackages = function () {110 log('#npmInstallPackages')111 const pathToPackages = distDir('packages', '*')112 return packages.npmInstallAll(pathToPackages)113 }114 const createRootPackage = function () {...
packages.js
Source:packages.js
1const _ = require('lodash')2let fs = require('fs-extra')3const path = require('path')4// we wrap glob to handle EMFILE error5let glob = require('glob')6const Promise = require('bluebird')7const retry = require('bluebird-retry')8const la = require('lazy-ass')9const check = require('check-more-types')10const execa = require('execa')11const R = require('ramda')12const prettyMs = require('pretty-ms')13const pluralize = require('pluralize')14const debug = require('debug')('cypress:binary')15const externalUtils = require('./3rd-party')16fs = Promise.promisifyAll(fs)17glob = Promise.promisify(glob)18const DEFAULT_PATHS = 'package.json'.split(' ')19const pathToPackageJson = function (packageFolder) {20 la(check.unemptyString(packageFolder), 'expected package path', packageFolder)21 return path.join(packageFolder, 'package.json')22}23const createCLIExecutable = (command) => {24 return (function (args, cwd, env = {}) {25 const commandToExecute = `${command} ${args.join(' ')}`26 console.log(commandToExecute)27 if (cwd) {28 console.log('in folder:', cwd)29 }30 la(check.maybe.string(cwd), 'invalid CWD string', cwd)31 return execa(command, args, { stdio: 'inherit', cwd, env })32 // if everything is ok, resolve with nothing33 .then(R.always(undefined))34 .catch((result) => {35 const msg = `${commandToExecute} failed with exit code: ${result.code}`36 throw new Error(msg)37 })38 })39}40const yarn = createCLIExecutable('yarn')41const npx = createCLIExecutable('npx')42const runAllBuild = _.partial(npx, ['lerna', 'run', 'build-prod', '--ignore', 'cli'])43// removes transpiled JS files in the original package folders44const runAllCleanJs = _.partial(npx, ['lerna', 'run', 'clean-js', '--ignore', 'cli'])45const copyAllToDist = function (distDir) {46 const copyRelativePathToDist = function (relative) {47 const dest = path.join(distDir, relative)48 return retry(() => {49 console.log(relative, '->', dest)50 return fs.copyAsync(relative, dest)51 })52 }53 const copyPackage = function (pkg) {54 console.log('** copy package: %s **', pkg)55 // copies the package to dist56 // including the default paths57 // and any specified in package.json files58 return Promise.resolve(fs.readJsonAsync(pathToPackageJson(pkg)))59 .then((json) => {60 // grab all the files that match "files" wildcards61 // but without all negated files ("!src/**/*.spec.js" for example)62 // and default included paths63 // and convert to relative paths64 return DEFAULT_PATHS65 .concat(json.files || [])66 .concat(json.main || [])67 }).then((pkgFileMasks) => {68 debug('for pkg %s have the following file masks %o', pkg, pkgFileMasks)69 const globOptions = {70 cwd: pkg, // search in the package folder71 absolute: false, // and return relative file paths72 followSymbolicLinks: false, // do not follow symlinks73 }74 return externalUtils.globby(pkgFileMasks, globOptions)75 }).map((foundFileRelativeToPackageFolder) => {76 return path.join(pkg, foundFileRelativeToPackageFolder)77 })78 .tap(debug)79 .map(copyRelativePathToDist, { concurrency: 1 })80 }81 // fs-extra concurrency tests (copyPackage / copyRelativePathToDist)82 // 1/1 4168883 // 1/5 4221884 // 1/10 4256685 // 2/1 4504186 // 2/2 4358987 // 3/3 5139988 // cp -R concurrency tests89 // 1/1 6581190 const started = new Date()91 return fs.ensureDirAsync(distDir)92 .then(() => {93 const globs = ['./packages/*', './npm/*']94 const globOptions = {95 onlyFiles: false,96 }97 return Promise.resolve(externalUtils.globby(globs, globOptions))98 .map(copyPackage, { concurrency: 1 })99 }).then(() => {100 console.log('Finished Copying %dms', new Date() - started)101 return console.log('')102 })103}104// replaces local npm version 0.0.0-development105// with the path to the package106// we need to do this instead of just changing the symlink (like we do for require('@packages/...'))107// so the packages actually get installed to node_modules and work with peer dependencies108const replaceLocalNpmVersions = function (basePath) {109 const visited = []110 const updateNpmPackage = function (pkg) {111 if (!visited.includes(pkg)) {112 visited.push(pkg)113 return updatePackageJson(`./npm/${pkg}/package.json`)114 }115 return Promise.resolve()116 }117 const updatePackageJson = function (pattern) {118 return Promise.resolve(glob(pattern, { cwd: basePath }))119 .map((pkgPath) => {120 const pkgJsonPath = path.join(basePath, pkgPath)121 return fs.readJsonAsync(pkgJsonPath)122 .then((json) => {123 const { dependencies } = json124 let shouldWriteFile = false125 if (dependencies) {126 return Promise.all(_.map(dependencies, (version, pkg) => {127 const parsedPkg = /(@cypress\/)(.*)/g.exec(pkg)128 if (parsedPkg && parsedPkg.length === 3 && version === '0.0.0-development') {129 const pkgName = parsedPkg[2]130 json.dependencies[`@cypress/${pkgName}`] = `file:${path.join(basePath, 'npm', pkgName)}`131 shouldWriteFile = true132 return updateNpmPackage(pkgName)133 }134 }))135 .then(() => {136 if (shouldWriteFile) {137 return fs.writeJsonAsync(pkgJsonPath, json, { spaces: 2 })138 }139 })140 }141 return Promise.resolve()142 })143 })144 }145 return updatePackageJson('./packages/*/package.json')146}147const forceNpmInstall = function (packagePath, packageToInstall) {148 console.log('Force installing %s', packageToInstall)149 console.log('in %s', packagePath)150 la(check.unemptyString(packageToInstall), 'missing package to install')151 return yarn(['install', '--force', packageToInstall], packagePath)152}153const removeDevDependencies = function (packageFolder) {154 const packagePath = pathToPackageJson(packageFolder)155 console.log('removing devDependencies from %s', packagePath)156 return fs.readJsonAsync(packagePath)157 .then((json) => {158 delete json.devDependencies159 return fs.writeJsonAsync(packagePath, json, { spaces: 2 })160 })161}162const retryGlobbing = function (pathToPackages, delay = 1000) {163 const retryGlob = () => {164 return glob(pathToPackages)165 .catch({ code: 'EMFILE' }, () => {166 // wait, then retry167 return Promise168 .delay(delay)169 .then(retryGlob)170 })171 }172 return retryGlob()173}174// installs all packages given a wildcard175// pathToPackages would be something like "C:\projects\cypress\dist\win32\packages\*"176const npmInstallAll = function (pathToPackages) {177 console.log(`npmInstallAll packages in ${pathToPackages}`)178 const started = new Date()179 const retryNpmInstall = function (pkg) {180 console.log('installing %s', pkg)181 console.log('NODE_ENV is %s', process.env.NODE_ENV)182 // force installing only PRODUCTION dependencies183 // https://docs.npmjs.com/cli/install184 const npmInstall = _.partial(yarn, ['install', '--production'])185 return npmInstall(pkg, { NODE_ENV: 'production' })186 .catch({ code: 'EMFILE' }, () => {187 return Promise188 .delay(1000)189 .then(() => {190 return retryNpmInstall(pkg)191 })192 }).catch((err) => {193 console.log(err, err.code)194 throw err195 })196 }197 const printFolders = (folders) => {198 return console.log('found %s', pluralize('folder', folders.length, true))199 }200 // only installs production dependencies201 return retryGlobbing(pathToPackages)202 .tap(printFolders)203 .mapSeries((packageFolder) => {204 return removeDevDependencies(packageFolder)205 .then(() => {206 return retryNpmInstall(packageFolder)207 })208 }).then(() => {209 const end = new Date()210 return console.log('Finished NPM Installing', prettyMs(end - started))211 })212}213module.exports = {214 runAllBuild,215 copyAllToDist,216 npmInstallAll,217 runAllCleanJs,218 forceNpmInstall,219 replaceLocalNpmVersions,220}221if (!module.parent) {222 console.log('demo force install')223 forceNpmInstall('packages/server', '@ffmpeg-installer/win32-x64')...
packages-spec.js
Source:packages-spec.js
...27 'lib': { 'foo.js': '{}' },28 },29 },30 })31 await packages.copyAllToDist(os.tmpdir())32 const files = getFs()33 snapshot(files)34 })35 it('can find packages with script', async () => {36 mockfs(37 {38 'packages': {39 'foo': {40 'package.json': JSON.stringify({41 scripts: {42 build: 'somefoo',43 },44 }),45 },...
gulpfile.js
Source:gulpfile.js
1const { parallel } = require('gulp');2const gulp = require('gulp');3const concat = require('gulp-concat');4const connect = require('gulp-connect');5const sass = require('gulp-sass');6const source = {7 all: [8 './index.html',9 '*tpl/**/*',10 '*img/**/*',11 '*js/**/*'12 ],13 sass: [14 '../*.scss',15 './sass/*.scss'16 ],17};18const dest = {19 all: './dist/**/*',20 css: './dist/css',21 root: './dist',22};23function connectServer () {24 return connect.server({25 root: dest.root,26 livereload: true27 });28}29function copyAllToDist () {30 return gulp.src(source.all)31 .pipe(gulp.dest(dest.root));32}33function compileSass () {34 return gulp.src(source.sass)35 .pipe(sass({ errLogToConsole: true, outputStyle: 'compressed' }))36 .pipe(concat('style.min.css'))37 .pipe(gulp.dest(dest.css));38}39function livereload () {40 return gulp.src(dest.all)41 .pipe(connect.reload());42}43function watch () {44 gulp.watch(source.all, copyAllToDist);45 gulp.watch(source.sass, compileSass);46 gulp.watch(dest.all, livereload);47}...
Using AI Code Generation
1const { copyAllToDist } = require("cypress-plugin-snapshots/plugin");2module.exports = (on, config) => {3 copyAllToDist(on, config);4 return config;5};6{7}8describe("Sample Test", () => {9 it("should take screenshot", () => {10 cy.get("h1").should("have.text", "Hello World!");11 cy.matchImageSnapshot();12 });13});14{15}16const { copyAllToDist } = require("cypress-plugin-snapshots/plugin");17module.exports = (on, config) => {18 copyAllToDist(on, config);19 return config;20};21{22}23describe("Sample Test", () => {24 it("should take screenshot", () => {25 cy.get("h1").should("have.text", "Hello World!");26 cy.matchImageSnapshot();27 });28});
Using AI Code Generation
1const CypressBuilder = require('@cypress/webpack-preprocessor');2const cypressBuilder = new CypressBuilder();3cypressBuilder.copyAllToDist();4const CypressBuilder = require('../../test.js');5const cypressBuilder = new CypressBuilder();6module.exports = (on, config) => {7 on('file:preprocessor', cypressBuilder.create(options));8};
Using AI Code Generation
1beforeEach(function() {2 cy.log('***beforeEach***')3 cy.copyAllToDist()4})5describe('My First Test', function() {6 it('Does not do much!', function() {7 cy.contains('h1', 'Hello World!')8 })9})10Cypress.Commands.add('copyAllToDist', () => {11 cy.log('***copyAllToDist***')12 cy.task('copyAllToDist')13})14const fs = require('fs-extra')15module.exports = (on, config) => {16 on('task', {17 copyAllToDist() {18 console.log('***copyAllToDist***')19 fs.copySync('cypress', 'dist/cypress')20 }21 })22}23I have a task in cypress/plugins/index.js that I want to use in a beforeEach() in a test file. I am trying to use the add() method to add the task to the Cypress object. I have tried to add the task to the Cypress object in several ways, but I always get a “Cypress is not defined” error. I have tried the following:24Cypress.Commands.add(‘copyAllToDist’, () => { … })25Cypress.Commands.add(‘copyAllToDist’, function() { … })26Cypress.Commands.add(‘copyAllToDist’, function() => { … })27I have a task in cypress/plugins/index.js that I want to use in a beforeEach() in a test file. I am trying to use the add() method to add the task to the Cypress object. I have tried to add the task to the Cypress object in several ways, but I always get a “Cypress is not defined” error. I have tried the following:28Cypress.Commands.add(‘copyAllToDist’, () => { … })29Cypress.Commands.add(‘copyAllToDist’, function() { … })30Cypress.Commands.add(‘copyAllToDist’, function() => { … })
Using AI Code Generation
1const copyAllToDist = require('cypress-fixture-merger').copyAllToDist;2copyAllToDist('./cypress/integration','./cypress/fixtures');3const copyAllToDist = require('cypress-fixture-merger').copyAllToDist;4module.exports = (on, config) => {5 on('task', {6 })7}8Cypress.Commands.add('copyAllToDist', (src, dest) => {9 return cy.task('copyAllToDist', {src, dest});10});11import './commands';12{13}14{15 "scripts": {
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!!