Best JavaScript code snippet using cypress
build.js
Source:build.js
...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 return Promise.reject(new Error('Build platform mismatch'))73 }74 const cleanupPlatform = function () {75 log('#cleanupPlatform')76 if (options.skipClean) {77 log('skipClean')78 return79 }...
packages-spec.js
Source:packages-spec.js
1/* global sinon */2const os = require('os')3const _ = require('lodash')4const path = require('path')5const proxyquire = require('proxyquire')6const mockfs = require('mock-fs')7const _snapshot = require('snap-shot-it')8const chai = require('chai')9const debug = require('debug')('test')10chai.use(require('chai-as-promised'))11const { expect } = chai12const packages = require('../../../binary/util/packages')13const { transformRequires } = require('../../../binary/util/transform-requires')14const { testPackageStaticAssets } = require('../../../binary/util/testStaticAssets')15const externalUtils = require('../../../binary/util/3rd-party')16global.beforeEach(() => {17 mockfs.restore()18})19const snapshot = (...args) => {20 mockfs.restore()21 return _snapshot(...args)22}23describe('packages', () => {24 it('can copy files from package.json', async () => {25 sinon.stub(os, 'tmpdir').returns('/tmp')26 mockfs({27 'packages': {28 'coffee': {29 'package.json': '{"main":"src/main.js", "name": "foo", "files": ["lib"]}',30 'src': { 'main.js': Buffer.from('console.log()') },31 'lib': { 'foo.js': '{}' },32 },33 },34 })35 sinon.stub(externalUtils, 'globby')36 .withArgs(['package.json', 'lib', 'src/main.js'])37 .resolves([38 'package.json',39 'lib/foo.js',40 'src/main.js',41 ])42 const destinationFolder = os.tmpdir()43 debug('destination folder %s', destinationFolder)44 await packages.copyAllToDist(destinationFolder)45 const files = getFs()46 snapshot(files)47 })48 it('can find packages with script', async () => {49 mockfs(50 {51 'packages': {52 'foo': {53 'package.json': JSON.stringify({54 scripts: {55 build: 'somefoo',56 },57 }),58 },59 'bar': {60 'package.json': JSON.stringify({61 scripts: {62 start: 'somefoo',63 },64 }),65 },66 'baz': {67 'package.json': JSON.stringify({68 main: 'somefoo',69 }),70 },71 },72 },73 )74 const res = await packages.getPackagesWithScript('build')75 expect(res).deep.eq(['foo'])76 })77})78describe('transformRequires', () => {79 it('can find and replace symlink requires', async function () {80 // these tests really refuse to work on Mac, so for now run it only on Linux81 if (os.platform() !== 'linux') {82 return this.skip()83 }84 const buildRoot = 'build/linux/Cypress/resources/app'85 mockfs({86 [buildRoot]: { 'packages': {87 'foo': {88 'package.json': '{"main":"src/main.js", "name": "foo", "files": ["lib"]}',89 'src': { 'main.js': Buffer.from('console.log()') },90 'lib': { 'foo.js': /*js*/`require("@packages/bar/src/main")${''}` },91 },92 'bar': {93 'package.json': '{"main":"src/main.js", "name": "foo", "files": ["lib"]}',94 'src': { 'main.js': Buffer.from('console.log()') },95 'lib': { 'foo.js': `require("@packages/foo/lib/somefoo")${''}` },96 'node_modules': { 'no-search.js': '' },97 'dist': { 'no-search.js': '' },98 },99 },100 },101 })102 // should return number of transformed requires103 await expect(transformRequires(buildRoot)).to.eventually.eq(2)104 const files = getFs()105 if (debug.enabled) {106 debug('returned file system')107 /* eslint-disable-next-line no-console */108 console.error(files)109 }110 snapshot(files)111 })112 it('can find and replace symlink requires on win32', async function () {113 if (os.platform() !== 'linux') {114 return this.skip()115 }116 const { transformRequires } = proxyquire('../../../binary/util/transform-requires', { path: path.win32 })117 const buildRoot = 'build/linux/Cypress/resources/app'118 mockfs({119 [buildRoot]: { 'packages': {120 'foo': {121 'package.json': '{"main":"src/main.js", "name": "foo", "files": ["lib"]}',122 'src': { 'main.js': Buffer.from('console.log()') },123 'lib': { 'foo.js': /*js*/`require("@packages/bar/src/main")${''}` },124 },125 'bar': {126 'package.json': '{"main":"src/main.js", "name": "foo", "files": ["lib"]}',127 'src': { 'main.js': Buffer.from('console.log()') },128 'lib': { 'foo.js': `require("@packages/foo/lib/somefoo")${''}` },129 'node_modules': { 'no-search.js': '' },130 'dist': { 'no-search.js': '' },131 },132 },133 },134 })135 await transformRequires(buildRoot)136 snapshot(getFs())137 })138})139describe('testStaticAssets', () => {140 it('can detect bad strings in asset', async () => {141 const buildDir = 'resources/app'142 mockfs({143 [buildDir]: {144 'packages': {145 'runner': {146 'dist': {147 'runner.js': `148 some js149 some really bad string150 some more js151 `,152 },153 },154 },155 },156 })157 // logFs()158 await expect(testPackageStaticAssets({159 assetGlob: `${buildDir}/packages/runner/dist/*.js`,160 badStrings: ['some really bad string'],161 })).to.rejected.with.eventually.property('message').contain('some really bad string')162 mockfs.restore()163 mockfs({164 [buildDir]: {165 'packages': {166 'runner': {167 'dist': {},168 },169 },170 },171 })172 await expect(testPackageStaticAssets({173 assetGlob: `${buildDir}/packages/runner/dist/*.js`,174 badStrings: ['some really bad string'],175 })).to.rejected.with.eventually176 .property('message').contain('assets to be found')177 })178 it('can detect asset with too many lines', async () => {179 const buildDir = 'resources/app'180 mockfs({181 [buildDir]: {182 'packages': {183 'runner': {184 'dist': {185 'runner.js': `186 ${'minified code;minified code;minified code;\n'.repeat(50)}187 `,188 },189 },190 },191 },192 })193 await expect(testPackageStaticAssets({194 assetGlob: `${buildDir}/packages/runner/dist/*.js`,195 minLineCount: 100,196 })).to.rejected.with.eventually197 .property('message').contain('minified')198 })199 it('can detect asset that includes specified number of goodStrings', async () => {200 const buildDir = 'resources/app'201 mockfs({202 [buildDir]: {203 'packages': {204 'test': {205 'file.css': `206 ${'-moz-user-touch: "none"\n'.repeat(5)}207 `,208 },209 },210 },211 })212 await expect(testPackageStaticAssets({213 assetGlob: `${buildDir}/packages/test/file.css`,214 goodStrings: [['-moz-', 10]],215 })).to.rejected.with.eventually216 .property('message').contain('at least 10')217 })218 it('can have custom testAssetString tests', async () => {219 const buildDir = 'resources/app'220 mockfs({221 [buildDir]: {222 'packages': {223 'test': {224 'file.css': `225 ${'-moz-user-touch: "none"\n'.repeat(5)}226 foo-bar-baz\227 `,228 },229 },230 },231 })232 await expect(testPackageStaticAssets({233 assetGlob: `${buildDir}/packages/test/file.css`,234 testAssetStrings: [235 [(str) => !str.split('\n').slice(-1)[0].includes('foo-bar-baz'), 'expected not to end with foo-bar-baz'],236 ],237 })).to.rejected.with.eventually238 .property('message').contain('foo-bar-baz')239 })240})241/*242// Example: Test real assets243 it('can detect', async () => {244 const buildDir = process.cwd()245 await expect(testPackageStaticAssets({246 assetGlob: `${buildDir}/packages/runner/dist/*.css`,247 goodStrings: [['-ms-', 20]],248 })).not.be.rejected249 })250*/251afterEach(() => {252 mockfs.restore()253})254// eslint-disable-next-line255const logFs = () => {256 // eslint-disable-next-line no-console257 console.dir(getFs(), { depth: null })258}259const getFs = () => {260 const cwd = process.cwd().split(path.sep).slice(1)261 const recurse = (dir, d) => {262 if (_.isString(dir)) {263 return dir264 }265 return _.extend({}, ..._.map(dir, (val, key) => {266 let nextDepth = null267 if (d !== null) {268 if (d === -1) {269 nextDepth = d + 1270 } else if (!(d > cwd.length) && key === cwd[d]) {271 key = 'foo'272 nextDepth = d + 1273 if (d === cwd.length - 1) {274 return { '[cwd]': recurse(val._items, nextDepth) }275 }276 return recurse(val._items, nextDepth)277 } else {278 nextDepth = null279 }280 }281 return {282 [key]: recurse(val._content ? val._content.toString() : val._items, nextDepth),283 }284 }))285 }286 return recurse({ root: mockfs.getMockRoot() }, -1).root...
testStaticAssets.js
Source:testStaticAssets.js
1/* eslint-disable arrow-body-style */2const la = require('lazy-ass')3const fs = require('fs-extra')4const _ = require('lodash')5const glob = require('glob')6const chalk = require('chalk').default7const Promise = require('bluebird')8const { stripIndent } = require('common-tags')9const globAsync = Promise.promisify(glob)10const testStaticAssets = async (buildResourcePath) => {11 await Promise.all([12 testPackageStaticAssets({13 assetGlob: `${buildResourcePath}/packages/runner/dist/cypress_runner.js`,14 badStrings: [15 // should only exist during development16 'webpack-livereload-plugin',17 // indicates eval source maps were included, which cause cross-origin errors18 '//# sourceURL=cypress://',19 // make sure webpack is not run with NODE_ENV=development20 'react.development.js',21 ],22 goodStrings: [23 // make sure webpack is run with NODE_ENV=production24 'react.production.min.js',25 ],26 testAssetStrings: [27 [28 (str) => !str.split('\n').slice(-1)[0].includes('//# sourceMappingURL'),29 'sourcemaps were detected, ensure `web-config/webpack.base.config.ts` does not have sourcemaps enabled in production',30 ],31 ],32 minLineCount: 5000,33 }),34 testPackageStaticAssets({35 assetGlob: `${buildResourcePath}/packages/runner/dist/injection.js`,36 goodStrings: [37 'action("app:window:before:load",window)',38 ],39 }),40 testPackageStaticAssets({41 assetGlob: `${buildResourcePath}/packages/runner/dist/*.css`,42 goodStrings: [43 // indicates css autoprefixer is correctly appending vendor prefixes (e.g -moz-touch)44 ['-ms-', 20],45 ],46 }),47 testPackageStaticAssets({48 assetGlob: `${buildResourcePath}/packages/desktop-gui/dist/index.html`,49 goodStrings: [50 // make sure webpack is run with NODE_ENV=production51 `window.env = 'production'`,52 ],53 }),54 testPackageStaticAssets({55 assetGlob: `${buildResourcePath}/packages/desktop-gui/dist/app.js`,56 goodStrings: [57 // make sure webpack is run with NODE_ENV=production58 'react.production.min.js',59 ],60 }),61 ])62}63const testPackageStaticAssets = async (options = {}) => {64 la(options.assetGlob, 'missing resourcePath')65 const opts = _.defaults(options, {66 assetGlob: '',67 goodStrings: [],68 badStrings: [],69 testAssetStrings: [],70 minLineCount: 0,71 })72 const foundAssets = await globAsync(opts.assetGlob)73 .map(async (path) => {74 const fileStr = (await fs.readFile(path)).toString()75 opts.goodStrings.forEach((str) => {76 const [passed, count, atLeast] = includesString(fileStr, str)77 la(passed, stripIndent`78 Error in ${path}: expected to find at least ${atLeast} strings of ${chalk.bold(str)}79 contained: ${count}80 `)81 })82 opts.badStrings.forEach((str) => {83 const [passed, count, atLeast] = includesString(fileStr, str)84 la(!passed, stripIndent`85 Error in ${path}: expected ${chalk.bold('not')} to find more than ${atLeast - 1} strings of ${chalk.bold(str)}86 contained: ${count}87 `)88 })89 opts.testAssetStrings.forEach(([testFn, errorMsg]) => {90 la(testFn(fileStr), `Error in ${path}: ${errorMsg}`)91 })92 if (opts.minLineCount) {93 const lineCount = (fileStr.match(/\n/g) || '').length + 194 la(lineCount > opts.minLineCount, stripIndent`95 Error in ${chalk.red(path)}: Detected this file was minified, having fewer than ${opts.minLineCount} lines of code.96 Minified code takes longer to inspect in browser Devtools, so we should leave it un-minified.97 `)98 }99 return path100 })101 la(!!foundAssets.length, stripIndent`102 expected assets to be found in ${chalk.green(opts.assetGlob)}103 `)104}105module.exports = {106 testStaticAssets,107 testPackageStaticAssets,108}109function includesCount (string, subString) {110 string += ''111 subString += ''112 if (subString.length <= 0) return (string.length + 1)113 let n = 0114 let pos = 0115 let step = subString.length116 // eslint-disable-next-line117 while (true) {118 pos = string.indexOf(subString, pos)119 if (pos >= 0) {120 ++n121 pos += step122 } else {123 break124 }125 }126 return n127}128const includesString = (fileStr, options) => {129 const opts = _.isArray(options) ? options : [options, 1]130 const [substr, atLeast] = opts131 const count = includesCount(fileStr, substr)132 const passed = count >= atLeast133 return [passed, count, atLeast]...
Using AI Code Generation
1describe('My First Test', () => {2 it('Visits the Kitchen Sink', () => {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.testStaticAssets()4 })5})6import './commands'7Cypress.Commands.add("testStaticAssets", () => {8 cy.get('img').each(($img) => {9 cy.request($img.prop('src')).its('status').should('eq', 200)10 })11 cy.get('link[rel="stylesheet"]').each(($link) => {12 cy.request($link.prop('href')).its('status').should('eq', 200)13 })14 cy.get('script').each(($script) => {15 cy.request($script.prop('src')).its('status').should('eq', 200)16 })17})18describe('My First Test', function() {19 it('Does not do much!', function() {20 cy.testStaticAssets()21 })22})23import './commands'24Cypress.Commands.add("testStaticAssets", () => {25 cy.get('img').each(($img) => {26 cy.request($img.prop('src')).its('status').should('eq', 200)27 })28 cy.get('link[rel="stylesheet"]').each(($link) => {29 cy.request($link.prop('href')).its('status').should('eq', 200)30 })31 cy.get('script').each(($script) => {32 cy.request($script.prop('src')).its('status').should('eq', 200)33 })34})35describe('My First Test', function() {36 it('Does not do much!', function() {37 cy.testStaticAssets()38 })39})40import './commands'41Cypress.Commands.add("testStaticAssets", () => {42 cy.get('img').each(($img) => {43 cy.request($img.prop('src')).its('status').should('eq', 200)44 })45 cy.get('link[
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.testStaticAssets();4 })5})6Cypress.Commands.add('testStaticAssets', function () {7 cy.get('img').each(($el) => {8 cy.request($el.prop('src')).its('status').should('eq', 200);9 });10 cy.get('link').each(($el) => {11 cy.request($el.prop('href')).its('status').should('eq', 200);12 });13 cy.get('script').each(($el) => {14 cy.request($el.prop('src')).its('status').should('eq', 200);15 })16});17{18}
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.testStaticAssets();4 })5})6Cypress.Commands.add('testStaticAssets', () => {7 cy.get('img').each(($img) => {8 cy.request($img.prop('src')).its('status').should('eq', 200)9 })10})11Cypress.Commands.add('testStaticAssets', () => {12 cy.get('img').each(($img) => {13 cy.request($img.prop('src')).its('status').should('eq', 200)14 })15})16declare namespace Cypress {17 interface Chainable {18 testStaticAssets: typeof testStaticAssets;19 }20}21function testStaticAssets(): Chainable<JQuery<HTMLElement>>;
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.testStaticAssets();4 });5});6module.exports = (on, config) => {7 on('task', {8 testStaticAssets({ assets }) {9 console.log(assets);10 return null;11 }12 });13};14Cypress.Commands.add('testStaticAssets', () => {15 cy.window().then(win => {16 const assets = win.__STATIC_ASSETS__;17 cy.task('testStaticAssets', { assets });18 });19});20{21 "testFiles": "**/*.{js,jsx,ts,tsx}"22}23{24 "dependencies": {25 },26 "scripts": {27 },28 "eslintConfig": {29 },30 "browserslist": {
Using AI Code Generation
1describe('Test Static Assets', function() {2 it('Test static assets', function() {3 cy.testStaticAssets();4 });5});6import 'cypress-axe';7import 'cypress-plugin-tab';8import 'cypress-wait-until';9import 'cypress-file-upload';10import 'cypress-iframe';11import 'cypress-xpath';12import 'cypress-verify-ssl-certs';13Cypress.Commands.add('testStaticAssets', () => {14 cy.injectAxe();15 cy.checkA11y();16 cy.get('a').each(($link) => {17 if ($link.attr('href').startsWith('http')) {18 cy.request({19 url: $link.attr('href'),20 }).then((response) => {21 expect(response.status).to.be.oneOf([200, 301, 302]);22 });23 }24 });25});26const { verifySslCertificates } = require('cypress-verify-ssl-certs/dist/plugin');27module.exports = (on, config) => {28 verifySslCertificates(on, config);29};30{31 "env": {32 },33 "reporterOptions": {34 },35}36{37 "mochawesomeReporterOptions": {
Using AI Code Generation
1describe('test Static Assets', () => {2 it('testStaticAssets', () => {3 cy.testStaticAssets();4 });5});6Cypress.Commands.add('testStaticAssets', () => {7 cy.get('img').each(($el) => {8 cy.request($el.prop('src')).its('status').should('eq', 200);9 });10});11describe('test Links', () => {12 it('testLinks', () => {13 cy.testLinks();14 });15});16Cypress.Commands.add('testLinks', () => {17 cy.get('a').each(($el) => {18 cy.request($el.prop('href')).its('status').should('eq', 200);19 });20});21describe('test Links', () => {22 it('testLinks', () => {23 cy.testLinks();24 });25});26Cypress.Commands.add('testLinks', () => {27 cy.get('a').each(($el) => {28 cy.request($el.prop('href')).its('status').should('eq', 200);29 });30});31describe('test Links', () => {32 it('testLinks', () => {33 cy.testLinks();34 });35});36Cypress.Commands.add('testLinks', () => {37 cy.get('a').each(($el) => {38 cy.request($el.prop('href')).its('status').should('eq', 200);39 });40});
Using AI Code Generation
1describe('Static assets', () => {2 it('should not have broken links', () => {3 cy.testStaticAssets()4 })5})6import './commands'7Cypress.Commands.add('testStaticAssets', () => {8 cy.get('script').each(($el, index, $list) => {9 cy.request($el.attr('src')).its('status').should('eq', 200)10 })11 cy.get('link').each(($el, index, $list) => {12 cy.request($el.attr('href')).its('status').should('eq', 200)13 })14 cy.get('img').each(($el, index, $list) => {15 cy.request($el.attr('src')).its('status').should('eq', 200)16 })17})18import './commands'19Cypress.Commands.add('testStaticAssets', () => {20 cy.get('script').each(($el, index, $list) => {21 cy.request($el.attr('src')).its('status').should('eq', 200)22 })23 cy.get('link').each(($el, index, $list) => {24 cy.request($el.attr('href')).its('status').should('eq', 200)25 })26 cy.get('img').each(($el, index, $list) => {27 cy.request($el.attr('src')).its('status').should('eq', 200)28 })29})30import './commands'31Cypress.Commands.add('testStaticAssets', () => {32 cy.get('script').each(($el, index, $list) => {33 cy.request($el.attr('src')).its('status').should('eq', 200)34 })
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!!