How to use buildCypressApp method in Cypress

Best JavaScript code snippet using cypress

build.js

Source:build.js Github

copy

Full Screen

1const _ = require('lodash')2const fse = require('fs-extra')3const os = require('os')4const del = require('del')5const path = require('path')6const cp = require('child_process')7const chalk = require('chalk')8const Promise = require('bluebird')9const pluralize = require('pluralize')10const execa = require('execa')11const electron = require('@packages/electron')12const debug = require('debug')('cypress:binary')13const R = require('ramda')14const la = require('lazy-ass')15const check = require('check-more-types')16const meta = require('./meta')17const smoke = require('./smoke')18const packages = require('./util/packages')19const xvfb = require('../../cli/lib/exec/xvfb')20const { transformRequires } = require('./util/transform-requires')21const { testStaticAssets } = require('./util/testStaticAssets')22const performanceTracking = require('../../packages/server/test/support/helpers/performance.js')23const rootPackage = require('@packages/root')24const fs = Promise.promisifyAll(fse)25const logger = function (msg, platform) {26  const time = new Date()27  const timeStamp = time.toLocaleTimeString()28  return console.log(timeStamp, chalk.yellow(msg), chalk.blue(platform))29}30const logBuiltAllPackages = () => {31  return console.log('built all packages')32}33// can pass options to better control the build34// for example35//   skipClean - do not delete "dist" folder before build36const buildCypressApp = function (platform, version, options = {}) {37  la(check.unemptyString(version), 'missing version to build', version)38  const distDir = _.partial(meta.distDir, platform)39  const buildDir = _.partial(meta.buildDir, platform)40  const buildAppDir = _.partial(meta.buildAppDir, platform)41  const log = _.partialRight(logger, platform)42  const testVersion = (folderNameFn) => {43    return (function () {44      log('#testVersion')45      const dir = folderNameFn()46      la(check.unemptyString(dir), 'missing folder for platform', platform)47      console.log('testing dist package version')48      console.log('by calling: node index.js --version')49      console.log('in the folder %s', dir)50      return execa('node', ['index.js', '--version'], {51        cwd: dir,52      }).then((result) => {53        la(check.unemptyString(result.stdout),54          'missing output when getting built version', result)55        console.log('app in %s', dir)56        console.log('built app version', result.stdout)57        la(result.stdout === version, 'different version reported',58          result.stdout, 'from input version to build', version)59        return console.log('✅ using node --version works')60      })61    })62  }63  const testBuiltStaticAssets = function () {64    log('#testBuiltStaticAssets')65    return testStaticAssets(distDir())66  }67  const checkPlatform = function () {68    log('#checkPlatform')69    if (platform === os.platform()) {70      return71    }72    console.log(`trying to build ${platform} from ${os.platform()}`)73    if ((platform === 'linux') && (os.platform() === 'darwin')) {74      console.log('npm run binary-build-linux')75    }76    return Promise.reject(new Error('Build platform mismatch'))77  }78  const cleanupPlatform = function () {79    log('#cleanupPlatform')80    if (options.skipClean) {81      log('skipClean')82      return83    }84    const cleanup = function () {85      const dir = distDir()86      la(check.unemptyString(dir), 'empty dist dir', dir, 'for platform', platform)87      return fs.removeAsync(distDir())88    }89    return cleanup()90    .catch(cleanup)91  }92  const buildPackages = function () {93    log('#buildPackages')94    return packages.runAllBuild()95    // Promise.resolve()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 () {115    log(`#createRootPackage ${platform} ${version}`)116    return fs.outputJsonAsync(distDir('package.json'), {117      name: 'cypress',118      productName: 'Cypress',119      description: rootPackage.description,120      version,121      main: 'index.js',122      scripts: {},123      env: 'production',124    })125    .then(() => {126      const str = `\127process.env.CYPRESS_INTERNAL_ENV = process.env.CYPRESS_INTERNAL_ENV || 'production'128require('./packages/server')\129`130      return fs.outputFileAsync(distDir('index.js'), str)131    })132  }133  const removeTypeScript = function () {134    // remove the .ts files in our packages135    log('#removeTypeScript')136    return del([137      // include ts files of packages138      distDir('**', '*.ts'),139      // except those in node_modules140      `!${distDir('**', 'node_modules', '**', '*.ts')}`,141    ])142    .then((paths) => {143      console.log(144        'deleted %d TS %s',145        paths.length,146        pluralize('file', paths.length),147      )148      return console.log(paths)149    })150  }151  // we also don't need ".bin" links inside Electron application152  // thus we can go through dist/packages/*/node_modules and remove all ".bin" folders153  const removeBinFolders = function () {154    log('#removeBinFolders')155    const searchMask = distDir('packages', '*', 'node_modules', '.bin')156    console.log('searching for', searchMask)157    return del([searchMask])158    .then((paths) => {159      console.log(160        'deleted %d .bin %s',161        paths.length,162        pluralize('folder', paths.length),163      )164      return console.log(paths)165    })166  }167  const removeCyFolders = function () {168    log('#removeCyFolders')169    const searchMask = distDir('packages', 'server', '.cy')170    console.log('searching', searchMask)171    return del([searchMask])172    .then((paths) => {173      console.log(174        'deleted %d .cy %s',175        paths.length,176        pluralize('file', paths.length),177      )178      return console.log(paths)179    })180  }181  const cleanJs = function () {182    log('#cleanJs')183    return packages.runAllCleanJs()184  }185  const getIconFilename = function (platform) {186    const filenames = {187      darwin: 'cypress.icns',188      win32: 'cypress.ico',189      linux: 'icon_512x512.png',190    }191    const iconFilename = electron.icons().getPathToIcon(filenames[platform])192    console.log(`For platform ${platform} using icon ${iconFilename}`)193    return iconFilename194  }195  const electronPackAndSign = function () {196    log('#electronPackAndSign')197    // See the internal wiki document "Signing Test Runner on MacOS"198    // to learn how to get the right Mac certificate for signing and notarizing199    // the built Test Runner application200    const appFolder = distDir()201    const outputFolder = meta.buildRootDir(platform)202    const electronVersion = electron.getElectronVersion()203    la(check.unemptyString(electronVersion), 'missing Electron version to pack', electronVersion)204    const iconFilename = getIconFilename(platform)205    console.log(`output folder: ${outputFolder}`)206    const args = [207      '--publish=never',208      `--c.electronVersion=${electronVersion}`,209      `--c.directories.app=${appFolder}`,210      `--c.directories.output=${outputFolder}`,211      `--c.icon=${iconFilename}`,212      // for now we cannot pack source files in asar file213      // because electron-builder does not copy nested folders214      // from packages/*/node_modules215      // see https://github.com/electron-userland/electron-builder/issues/3185216      // so we will copy those folders later ourselves217      '--c.asar=false',218    ]219    const opts = {220      stdio: 'inherit',221    }222    console.log('electron-builder arguments:')223    console.log(args.join(' '))224    return execa('electron-builder', args, opts)225  }226  const removeDevElectronApp = function () {227    log('#removeDevElectronApp')228    // when we copy packages/electron, we get the "dist" folder with229    // empty Electron app, symlinked to our server folder230    // in production build, we do not need this link, and it231    // would not work anyway with code signing232    // hint: you can see all symlinks in the build folder233    // using "find build/darwin/Cypress.app/ -type l -ls"234    console.log('platform', platform)235    const electronDistFolder = distDir('packages', 'electron', 'dist')236    la(check.unemptyString(electronDistFolder),237      'empty electron dist folder for platform', platform)238    console.log(`Removing unnecessary folder '${electronDistFolder}'`)239    return fs.removeAsync(electronDistFolder) // .catch(_.noop) why are we ignoring an error here?!240  }241  const lsDistFolder = function () {242    log('#lsDistFolder')243    const buildFolder = buildDir()244    console.log('in build folder %s', buildFolder)245    return execa('ls', ['-la', buildFolder])246    .then(R.prop('stdout'))247    .then(console.log)248  }249  const runSmokeTests = function () {250    log('#runSmokeTests')251    const run = function () {252      // make sure to use a longer timeout - on Mac the first253      // launch of a built application invokes gatekeeper check254      // which takes a couple of seconds255      const executablePath = meta.buildAppExecutable(platform)256      return smoke.test(executablePath)257    }258    if (xvfb.isNeeded()) {259      return xvfb.start()260      .then(run)261      .finally(xvfb.stop)262    }263    return run()264  }265  const verifyAppCanOpen = function () {266    if (platform !== 'darwin') {267      return Promise.resolve()268    }269    const appFolder = meta.zipDir(platform)270    log(`#verifyAppCanOpen ${appFolder}`)271    return new Promise((resolve, reject) => {272      const args = ['-a', '-vvvv', appFolder]273      debug(`cmd: spctl ${args.join(' ')}`)274      const sp = cp.spawn('spctl', args, { stdio: 'inherit' })275      return sp.on('exit', (code) => {276        if (code === 0) {277          return resolve()278        }279        return reject(new Error('Verifying App via GateKeeper failed'))280      })281    })282  }283  const printPackageSizes = function () {284    const appFolder = meta.buildAppDir(platform, 'packages')285    log(`#printPackageSizes ${appFolder}`)286    if (platform === 'win32') {287      return Promise.resolve()288    }289    // "du" - disk usage utility290    // -d -1 depth of 1291    // -h human readable sizes (K and M)292    const args = ['-d', '1', appFolder]293    const parseDiskUsage = function (result) {294      const lines = result.stdout.split(os.EOL)295      // will store {package name: package size}296      const data = {}297      lines.forEach((line) => {298        const parts = line.split('\t')299        const packageSize = parseFloat(parts[0])300        const folder = parts[1]301        const packageName = path.basename(folder)302        if (packageName === 'packages') {303          return // root "packages" information304        }305        data[packageName] = packageSize306      })307      return data308    }309    const printDiskUsage = function (sizes) {310      const bySize = R.sortBy(R.prop('1'))311      return console.log(bySize(R.toPairs(sizes)))312    }313    return execa('du', args)314    .then(parseDiskUsage)315    .then(R.tap(printDiskUsage))316    .then((sizes) => {317      return performanceTracking.track('test runner size', sizes)318    })319  }320  return Promise.resolve()321  .then(checkPlatform)322  .then(cleanupPlatform)323  .then(buildPackages)324  .then(copyPackages)325  .then(npmInstallPackages)326  .then(createRootPackage)327  .then(removeTypeScript)328  .then(cleanJs)329  .then(transformSymlinkRequires)330  .then(testVersion(distDir))331  .then(testBuiltStaticAssets)332  .then(removeBinFolders)333  .then(removeCyFolders)334  .then(removeDevElectronApp)335  .then(electronPackAndSign)336  .then(lsDistFolder)337  .then(testVersion(buildAppDir))338  .then(runSmokeTests)339  .then(verifyAppCanOpen)340  .then(printPackageSizes)341  .return({342    buildDir: buildDir(),343  })344}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...182    debug('parsed build options %o', options)183    return askMissingOptions(['version', 'platform'])(options)184    .then(() => {185      debug('building binary: platform %s version %s', options.platform, options.version)186      return build.buildCypressApp(options)187    })188  },189  zip (options) {190    console.log('#zip')191    if (!options) {192      options = this.parseOptions(process.argv)193    }194    return askMissingOptions(['platform'])(options)195    .then((options) => {196      const zipDir = meta.zipDir(options.platform)197      console.log('directory to zip %s', zipDir)198      options.zip = path.resolve(zippedFilename(options.platform))199      return zip.ditto(zipDir, options.zip)200    })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildCypressApp } = require('@cypress/webpack-preprocessor');2const webpackOptions = require('../webpack.config.js');3module.exports = (on, config) => {4  on('file:preprocessor', buildCypressApp(webpackOptions));5};6const path = require('path');7const webpack = require('webpack');8module.exports = {9  resolve: {10  },11  module: {12      {13        test: /\.(ts|tsx)$/,14        options: {15        },16      },17  },18    new webpack.NormalModuleReplacementPlugin(19      /(.*)environment\.dev\.ts$/,20      function (resource) {21        resource.request = resource.request.replace(22        );23      }24};25{26  "env": {27  },28}29{30  "compilerOptions": {31    "importHelpers": true,32  }33}

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress');2cypress.run({3}).then((results) => {4    console.log(results);5});6describe('My First Test', () => {7    it('Does not do much!', () => {8        expect(true).to.equal(true)9    });10});11{12}13{14}15{16}17{18}19{

Full Screen

Using AI Code Generation

copy

Full Screen

1import { buildCypressApp } from 'cypress-angular-unit-test';2const { mount } = buildCypressApp('<app-root></app-root>', AppComponent);3describe('test', () => {4  it('test', () => {5    mount();6    cy.get('h1').should('contain', 'Welcome to my-app!');7  });8});9const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');10module.exports = (on, config) => {11  addMatchImageSnapshotPlugin(on, config);12};13import 'cypress-angular-unit-test/support';14import 'cypress-image-snapshot/command';15import './commands';16{17}18{

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress')2cypress.buildCypressApp('path/to/app', 'path/to/build')3const cypress = require('cypress')4module.exports = (on, config) => {5  on('task', {6    buildApp: (config) => {7      cypress.buildCypressApp(config.appPath, config.buildPath)8    }9  })10}11const cypress = require('cypress')12module.exports = (on, config) => {13  on('task', {14    buildApp: (config) => {15      cypress.buildCypressApp(config.appPath, config.buildPath)16    }17  })18}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { buildCypressApp } from '@cypress/vue'2const options = {3  props: {4  },5}6buildCypressApp(options)7describe('MyComponent', () => {8  it('works', () => {9    cy.mount()10    cy.get('h1').should('contain', 'Hello World')11  })12})13import { mount } from '@cypress/vue'14Cypress.Commands.overwrite('mount', (originalFn, options) => {15  return originalFn({ ...options, attachToDocument: true })16})17const webpackPreprocessor = require('@cypress/webpack-preprocessor')18module.exports = (on, config) => {19  const options = {20    webpackOptions: require('../../webpack.config'),21  }22  on('file:preprocessor', webpackPreprocessor(options))23}24{25}26module.exports = {27  module: {28      {29      },30  },31}32{33  "scripts": {34  },35  "devDependencies": {36  },37  "dependencies": {38  }39}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildCypressApp } = require("cypress-app");2const app = buildCypressApp();3app.start();4app.stop();5app.restart();6describe("My First Test", () => {7  it("Does not do much!", () => {8    cy.app().then((app) => {9      app.start();10      app.stop();11      app.restart();12    });13  });14});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildCypressApp } = require('@cypress/vue')2buildCypressApp().then((options) => {3})4describe('My component', () => {5  it('works', () => {6    cy.visit('/test.html')7    cy.contains('Hello world')8  })9})10const { startDevServer } = require('@cypress/webpack-dev-server')11module.exports = (on, config) => {12  on('dev-server:start', (options) => {13    return startDevServer({14      webpackConfig: require('../../webpack.config'),15    })16  })17}18import './commands'19Cypress.Commands.add('mount', (component, options) => {20  cy.window().then((win) => {21    const app = mount(component, options)22    cy.document().then((doc) => {23      doc.body.appendChild(app.$el)24    })25  })26})27describe('My component', () => {28  it('works', () => {29    cy.visit('/test.html')30    cy.mount(MyComponent)31    cy.contains('Hello world')32  })33})34import './commands'35Cypress.Commands.add('mount', (component, options) => {36  cy.window().then((win) => {37    const app = mount(component, options)38    cy.document().then((doc) => {39      doc.body.appendChild(app.$el)40    })41  })42})43describe('My component', () => {44  it('works', () => {45    cy.visit('/test.html')

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