Best JavaScript code snippet using cypress
uploadTo145.js
Source:uploadTo145.js
1const archiver = require('archiver');2const fs = require("fs");3const path = require("path");4const FTPS = require('ftps');5const unzip = require('extract-zip');6const fsextra = require('fs-extra')7// 大å
FTPåæ°8const hallFtpOpt = {9 host: "192.168.2.145",10 port: 21,11 username: "lanwan",12 password: "Lanwanhudong@20191010"13}14const defaultGame = "10017";15const archiverPromise = async (dirpath, zippath) => {16 if (fs.existsSync(zippath)) {17 fs.unlinkSync(zippath);18 }19 if (!fs.existsSync(dirpath)) {20 console.log('ç®å½ä¸åå¨' + dirpath);21 return;22 }23 return new Promise((resolve, reject) => {24 let output = fs.createWriteStream(zippath);25 let archive = archiver('zip', {26 zlib: {27 level: 928 }29 });30 output.on('close', function () {31 console.log(archive.pointer() + ' total bytes');32 console.log('archiver has been finalized and the output file descriptor has closed.');33 resolve(zippath);34 });35 output.on('end', function () {36 console.log('Data has been drained');37 });38 archive.on('warning', function (err) {39 console.log("archive warning", err)40 if (err.code === 'ENOENT') { } else { }41 });42 archive.on('error', function (err) {43 console.log("archive error", err)44 reject(err);45 });46 archive.pipe(output);47 archive.directory(dirpath, false);48 archive.finalize();49 })50}51let main = async function () {52 let WORKSPACE = path.dirname(__dirname);53 fsextra.removeSync(path.join(WORKSPACE, "temp", "resoutput.zip"));54 await archiverPromise(path.join(WORKSPACE, "temp", "resoutput"), path.join(WORKSPACE, "temp", "resoutput.zip"));55 console.log("çæ", path.join(WORKSPACE, "temp", "resoutput.zip"));56 if (!fsextra.existsSync(path.join(WORKSPACE, "nativeapp", "hallgames"))) {57 fsextra.mkdirSync(path.join(WORKSPACE, "nativeapp", "hallgames"));58 }59 let ftps = new FTPS(hallFtpOpt);60 ftps.raw(`rm -rf ios/assetspatch`);61 ftps.put(path.join(WORKSPACE, "temp", "resoutput.zip"), `ios/assetspatch.zip`)62 ftps.mirror({63 remoteDir: `ios/assetspatch`,64 localDir: path.join(WORKSPACE, "temp", "resoutput"),65 upload: true,66 options: "--allow-chown"67 });68 console.log("åå¤ä¸ä¼ å° " + hallFtpOpt.host + " ios/assetspatch")69 ftps.raw(`rm -rf android/assetspatch`);70 ftps.put(path.join(WORKSPACE, "temp", "resoutput.zip"), `android/assetspatch.zip`)71 ftps.mirror({72 remoteDir: `android/assetspatch`,73 localDir: path.join(WORKSPACE, "temp", "resoutput"),74 upload: true,75 options: "--allow-chown"76 });77 let zipgamefilepath = path.join(WORKSPACE, "nativeapp", "hallgames", defaultGame + ".zip");78 fsextra.removeSync(zipgamefilepath);79 ftps.get(`hallgames/${defaultGame}.zip`, zipgamefilepath);80 console.log("åå¤ä¸ä¼ å° " + hallFtpOpt.host + " android/assetspatch")81 await new Promise((resolve, reject) => {82 ftps.exec(function (err, res) {83 if (err) {84 console.log(res);85 reject(err)86 } else {87 console.log(res);88 resolve(res);89 }90 });91 });92 unzip(zipgamefilepath, { dir: path.join(path.dirname(zipgamefilepath), defaultGame) }, () => {93 fsextra.removeSync(zipgamefilepath);94 })95}...
newsagent.js
Source:newsagent.js
1import Process from 'process'2import FSExtra from 'fs-extra'3import Bree from 'bree'4import * as Zod from 'zod'5function validate(watch) {6 const schema = Zod.object({7 name: Zod.string(),8 source: Zod.object({ method: Zod.string() }).nonstrict(),9 schedule: Zod.string(),10 monitor: Zod.string().regex(/additions-only|additions-and-removals|removals-only/),11 processes: Zod.array(Zod.object({ method: Zod.string() }).nonstrict()).optional(),12 alerts: Zod.array(Zod.object({ method: Zod.string() }).nonstrict())13 })14 return schema.safeParse(watch)15}16async function generate(watch, i) {17 const executor = await FSExtra.readFile('executor.js')18 const id = watch.name.toLowerCase().replace(/[^a-z ]+/g, '').replace(/ /g, '-')19 const code = `const watch = ${JSON.stringify(watch)}\n` + executor20 const path = `./.newsagent-jobs/job-${i + 1}-${id}.js`21 await FSExtra.writeFile(path, code)22 return path23}24async function run(watches, message = () => {}) {25 await FSExtra.remove('.newsagent-jobs')26 await FSExtra.ensureDir('.newsagent-jobs')27 await FSExtra.ensureDir('.newsagent-cache')28 Process.on('SIGINT', async () => {29 await FSExtra.remove('.newsagent-jobs')30 process.exit()31 })32 const jobsGeneration = watches.map(async (watch, i) => {33 const validation = validate(watch)34 if (validation.error) {35 const error = validation.error.errors[0]36 message(watch.name, 'watch-invalid', {37 error: `${error.message}: ${error.path.join('.')} wanted ${error.expected} but got ${error.received}`38 })39 return null40 }41 return {42 name: watch.name,43 path: await generate(watch, i),44 interval: watch.schedule45 }46 })47 const jobs = (await Promise.all(jobsGeneration)).filter(x => x)48 if (jobs.length === 0) throw new Error('nothing to watch!')49 const logger = {50 info: (text, metadata) => {51 if (text.startsWith('Worker for job') && text.endsWith('online')) {52 const source = text.split('"')[1]53 message(source, 'worker-starting')54 }55 else if (text.startsWith('Worker for job') && text.endsWith('exited with code 0')) {56 const source = text.split('"')[1]57 message(source, 'worker-finished')58 }59 else if (text.startsWith('Worker for job') && text.endsWith('sent a message')) {60 const source = text.split('"')[1]61 message(source, metadata.message.event, metadata.message.data)62 }63 else message(null, 'INFO', { text, metadata })64 },65 warn: (e, metadata) => {66 if (e.message.startsWith('Job') && e.message.endsWith('is already running')) {67 const source = e.message.split('"')[1]68 message(source, 'worker-still-running')69 }70 else message(null, 'WARN', { text: e.message, metadata })71 },72 error: (e, metadata) => {73 if (typeof e === 'string' && e.startsWith('Worker for job') && e.endsWith('exited with code 1')) {74 const source = e.split('"')[1]75 message(source, 'worker-execution-failure')76 }77 else message(null, 'ERROR', { text: e.message || e, ...(metadata ? { metadata } : {}) })78 }79 }80 new Bree({81 root: false,82 logger,83 jobs84 }).start()85}...
github_pages.js
Source:github_pages.js
1// The MIT License (MIT)2// 3// node-enumerable (https://github.com/mkloubert/node-enumerable)4// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>5// 6// Permission is hereby granted, free of charge, to any person obtaining a copy7// of this software and associated documentation files (the "Software"), to8// deal in the Software without restriction, including without limitation the9// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or10// sell copies of the Software, and to permit persons to whom the Software is11// furnished to do so, subject to the following conditions:12// 13// The above copyright notice and this permission notice shall be included in14// all copies or substantial portions of the Software.15// 16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING21// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER22// DEALINGS IN THE SOFTWARE.232425// this is a script target for26// vs-deploy VSCode extension27// 28// s. https://github.com/mkloubert/vs-deploy29// for more information3031const Path = require('path');32const vscode = require('vscode');3334exports.execute = function(args) {35 const FSExtra = args.require('fs-extra');3637 // workspace folder38 const WORKSPACE = Path.resolve(39 Path.join(__dirname, '../')40 );4142 // GitHub pages43 const GITHUB_PAGES = Path.resolve(44 Path.join(__dirname, '../mkloubert.github.io')45 );4647 // copy demo and playground page48 {49 const DEMO = Path.resolve(50 Path.join(WORKSPACE, 'demo')51 );5253 const GITHUB_PAGES_DEMOS = Path.resolve(54 Path.join(GITHUB_PAGES, 'demos/node-enumerable')55 );5657 if (FSExtra.existsSync(GITHUB_PAGES_DEMOS)) {58 FSExtra.removeSync(GITHUB_PAGES_DEMOS);59 }60 FSExtra.mkdirsSync(GITHUB_PAGES_DEMOS);6162 FSExtra.copySync(DEMO, GITHUB_PAGES_DEMOS);63 }6465 // copy documentation66 {67 const DOCS = Path.resolve(68 Path.join(WORKSPACE, 'docs')69 );7071 const GITHUB_PAGES_DOCS = Path.resolve(72 Path.join(GITHUB_PAGES, 'node-enumerable')73 );7475 if (FSExtra.existsSync(GITHUB_PAGES_DOCS)) {76 FSExtra.removeSync(GITHUB_PAGES_DOCS);77 }78 FSExtra.mkdirsSync(GITHUB_PAGES_DOCS);7980 FSExtra.copySync(DOCS, GITHUB_PAGES_DOCS);81 }
...
test-api.js
Source:test-api.js
1const path = require('path');2const os = require('os');3const fs = require('fs');4const fsextra = require('fs-extra');5const nexlApp = require('../backend/nexl-app/nexl-app');6const confConsts = require('../backend/common/conf-constants');7const confMgmt = require('../backend/api/conf-mgmt');8const TEST_HOST = 'localhost';9const TEST_PORT = 8989;10// --------------------------------------------------------------------------------11function printLongDash() {12 console.log('-----------------------------------------------------------------------------------');13}14function startNexlApp(initTest, runTests, finalizeTests) {15 // recreating tmp nexl home dir16 const tmpNexlHomeDir = path.join(os.tmpdir(), '.nexl');17 fsextra.removeSync(tmpNexlHomeDir);18 fs.mkdirSync(tmpNexlHomeDir);19 // recreating tmp nexl storage files dir20 const tmpNexlStorageDir = path.join(os.tmpdir(), 'nexl-storage');21 fsextra.removeSync(tmpNexlStorageDir);22 fs.mkdirSync(tmpNexlStorageDir);23 // setting up nexl home dir in process args24 process.argv.push(`--${confConsts.NEXL_HOME_DEF}=${tmpNexlHomeDir}`);25 return nexlApp.create()26 .then(_ => {27 const predefinedNexlStorageDir = path.join(__dirname, 'resources/storage');28 const settings = confMgmt.getNexlSettingsCached();29 settings[confConsts.SETTINGS.HTTP_BINDING] = TEST_HOST;30 settings[confConsts.SETTINGS.HTTP_PORT] = TEST_PORT;31 return initTest(predefinedNexlStorageDir, tmpNexlStorageDir);32 })33 .then(nexlApp.start)34 .then(runTests)35 .then(finalizeTests)36 .then(_ => {37 printLongDash();38 console.log('All tests are passed !!!');39 printLongDash();40 nexlApp.stop();41 })42 .catch(err => {43 printLongDash();44 console.log('Tests are failed :(');45 if (err !== undefined) {46 console.log('Reason :');47 printLongDash();48 console.log(err);49 printLongDash();50 } else {51 printLongDash();52 }53 nexlApp.stop();54 });55}56// --------------------------------------------------------------------------------57module.exports.startNexlApp = startNexlApp;58module.exports.TEST_HOST = TEST_HOST;59module.exports.TEST_PORT = TEST_PORT;...
create.js
Source:create.js
1const path = require('path')2const fsextra = require('fs-extra')3const fs = require('fs')4const Inquirer = require('inquirer')56const CreateTemplate = require('./downloadTemplate.js')7async function create(projectName, options) {8 console.log(projectName, options)9 const cwd = process.cwd() // è·åå½åå½ä»¤æ§è¡æ¶çå·¥ä½ç®å½10 const targetDir = path.join(cwd, projectName) // ç®æ ç®å½11 console.log('targetDir', targetDir)12 if(fsextra.existsSync(targetDir)) {13 if(options.force) {14 // 强å¶å建15 await fsextra.remove(targetDir)16 console.log('å é¤æ§é¡¹ç®æå')17 createDir(projectName)18 } else {19 let { action } = await Inquirer.prompt([20 {21 name: 'action',22 type: 'list',23 message: 'Target directory already exists Pick an action:',24 choices: [25 { name: 'Overwrite', value: 'overwrite' },26 { name: 'Cancek', value: false }27 ]28 }29 ])30 if(!action) {31 console.log('åæ¶æä½')32 return33 } else if(action === 'overwrite') {34 await fsextra.remove(targetDir)35 console.log('å é¤æ§é¡¹ç®æå')36 createDir(projectName, targetDir)37 }38 }39 } else {40 createDir(projectName, targetDir)41 }42}4344function createDir(projectName, targetDir) {45 fs.mkdir(`./${projectName}`, async (err) => {46 if(err) {47 console.log('å建失败')48 } else {49 console.log('å建æå')50 let { action } = await Inquirer.prompt([51 {52 name: 'action',53 type: 'list',54 message: 'ä¸è½½æ¨¡æ¿ç±»å:',55 choices: [56 { name: 'search-pages', value: 'search-pages' }57 ]58 }59 ])60 if(action) {61 new CreateTemplate(action, targetDir)62 }63 }64 })65}6667module.exports = (...args) => {68 return create(...args)
...
build.js
Source:build.js
1/**2 * Build script that will be executed by `npm run build`3 */4const fs = require('fs');5const fsextra = require('fs-extra');6const replace = require('replace');7const uglifyjs = require('uglify-es');8const uglifycss = require('uglifycss');9// ensure that '_site' folder is created10fsextra.emptyDirSync('_site');11// copy in all assets and .html12fsextra.copySync('assets', '_site/assets');13fsextra.copySync('images', '_site/images');14fsextra.copySync('index.html', '_site/index.html');15fsextra.copySync('favicon.ico', '_site/favicon.ico');16// uglify and minify main.js17var result = uglifyjs.minify({18 'main.js': fs.readFileSync('_site/assets/js/main.js', 'utf8')19});20fs.writeFileSync('_site/assets/js/main.min.js', result.code, 'utf8');21// uglify and minify main.css22result = uglifycss.processFiles(['_site/assets/css/main.css']);23fs.writeFileSync('_site/assets/css/main.min.css', result, 'utf8');24// remove input file from bulid folder25fsextra.removeSync('_site/assets/js/main.js');26fsextra.removeSync('_site/assets/css/main.css');27// sed js inclusion in index.html28replace({29 regex: '<link rel="stylesheet" href="assets/css/main.css" />',30 replacement: '<link rel="stylesheet" href="assets/css/main.min.css" />',31 paths: ['_site/index.html'],32 recursive: false,33 silent: true34});35replace({36 regex: '<script src="assets/js/main.js"></script>',37 replacement: '<script src="assets/js/main.min.js"></script>',38 paths: ['_site/index.html'],39 recursive: false,40 silent: true...
logsCleaner.js
Source:logsCleaner.js
1const fsextra = require("fs-extra");2const path = require("path");3const logsLocation = path.resolve("./combined.log");4const allureResultsLocation = path.resolve("allure-results/");5const allureReportLocation = path.resolve("allure-report/");6fsextra.removeSync(logsLocation);7fsextra.removeSync(allureResultsLocation);...
deploy.js
Source:deploy.js
1const fsextra = require("fs-extra");2function delFoldersSync() {3 //УдалÑем папки ÑозданнÑе командой dev или serve.4 fsextra.removeSync('./.cache');5 fsextra.removeSync('./dist');6}7 ...
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1const fsExtra = require('fs-extra')2fsExtra.remove('cypress/fixtures/snapshots')3fsExtra.remove('cypress/screenshots')4fsExtra.remove('cypress/videos')5fsExtra.remove('cypress/reports')6const fs = require('fs')7fs.rmdirSync('cypress/fixtures/snapshots', { recursive: true })8fs.rmdirSync('cypress/screenshots', { recursive: true })9fs.rmdirSync('cypress/videos', { recursive: true })10fs.rmdirSync('cypress/reports', { recursive: true })11const fs = require('fs')12fs.rmdirSync('cypress/fixtures/snapshots', { recursive: true })13fs.rmdirSync('cypress/screenshots', { recursive: true })14fs.rmdirSync('cypress/videos', { recursive: true })15fs.rmdirSync('cypress/reports', { recursive: true })16const fs = require('fs')17fs.rmdirSync('cypress/fixtures/snapshots', { recursive: true })18fs.rmdirSync('cypress/screenshots', { recursive: true })19fs.rmdirSync('cypress/videos', { recursive: true })20fs.rmdirSync('cypress/reports', { recursive: true })21const fs = require('fs')22fs.rmdirSync('cypress/fixtures/snapshots', { recursive: true })23fs.rmdirSync('cypress/screenshots', { recursive: true })24fs.rmdirSync('cypress/videos', { recursive: true })25fs.rmdirSync('cypress/reports', { recursive: true })26const fs = require('fs')27fs.rmdirSync('cypress/fixtures/snapshots', { recursive: true })28fs.rmdirSync('cypress/screenshots', { recursive: true })29fs.rmdirSync('cypress/videos', { recursive: true })30fs.rmdirSync('cypress/reports', { recursive: true })31const fs = require('fs')32fs.rmdirSync('cypress/fixtures/snapshots', { recursive: true })33fs.rmdirSync('cypress/screenshots', { recursive: true })34fs.rmdirSync('cypress/videos
Using AI Code Generation
1const fsExtra = require('fs-extra');2const path = require('path');3const rimraf = require('rimraf');4const dir = path.join(__dirname, 'cypress/fixtures');5rimraf(dir, () => {6 fsExtra.remove(dir);7});8const fsExtra = require('fs-extra');9const path = require('path');10const rimraf = require('rimraf');11const dir = path.join(__dirname, 'cypress/fixtures');12rimraf(dir, () => {13 fsExtra.remove(dir);14});15const fsExtra = require('fs-extra');16const path = require('path');17const rimraf = require('rimraf');18const dir = path.join(__dirname, 'cypress/fixtures');19rimraf(dir, () => {20 fsExtra.remove(dir);21});22const fsExtra = require('fs-extra');23const path = require('path');24const rimraf = require('rimraf');25const dir = path.join(__dirname, 'cypress/fixtures');26rimraf(dir, () => {27 fsExtra.remove(dir);28});29const fsExtra = require('fs-extra');30const path = require('path');31const rimraf = require('rimraf');32const dir = path.join(__dirname, 'cypress/fixtures');33rimraf(dir, () => {34 fsExtra.remove(dir);35});36const fsExtra = require('fs-extra');37const path = require('path');38const rimraf = require('rimraf');39const dir = path.join(__dirname, 'cypress/fixtures');40rimraf(dir, () => {41 fsExtra.remove(dir);42});
Using AI Code Generation
1describe('File Upload Test Suite', function() {2 it('File Upload Test Case', function() {3 cy.get('#file-upload').attachFile('sample.png')4 cy.get('#file-submit').click()5 })6})7{8 "env": {9 },10}11Cypress.Commands.add('attachFile', { prevSubject: true }, (subject, fileName, fileType = '') => {12 cy.log('Custom Command: attachFile')13 return cy.get(subject).then(subject => {14 return cy.fixture(fileName, 'base64').then(Cypress.Blob.base64StringToBlob).then(blob => {15 const testFile = new File([blob], fileName, { type: fileType })16 const dataTransfer = new DataTransfer()17 dataTransfer.items.add(testFile)18 })19 })20})21import './commands'22describe('File Upload Test Suite', function() {23 it('File Upload Test Case', function() {24 cy.get('#file-upload
Using AI Code Generation
1const fs = require('fs-extra')2afterEach(() => {3 fs.remove('./cypress/screenshots')4 fs.remove('./cypress/videos')5})6const fs = require('fs-extra')7afterEach(() => {8 fs.remove('./cypress/screenshots')9 fs.remove('./cypress/videos')10})11const fs = require('fs-extra')12afterEach(() => {13 fs.remove('./cypress/screenshots')14 fs.remove('./cypress/videos')15})16const fs = require('fs-extra')17afterEach(() => {18 fs.remove('./cypress/screenshots')19 fs.remove('./cypress/videos')20})
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!!