Best JavaScript code snippet using cypress
react-docgen-test.js
Source:react-docgen-test.js
1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 */8// NOTE: This test spawns a subprocesses that load the files from dist/, not9// src/. Before running this test run `npm run build` or `npm run watch`.10const TEST_TIMEOUT = 120000;11const fs = require('fs');12const path = require('path');13const rimraf = require('rimraf');14const temp = require('temp');15const spawn = require('cross-spawn');16function run(args, stdin) {17 return new Promise(resolve => {18 const docgen = spawn(path.join(__dirname, '../react-docgen.js'), args);19 let stdout = '';20 let stderr = '';21 docgen.stdout.on('data', data => (stdout += data));22 docgen.stderr.on('data', data => (stderr += data));23 docgen.on('close', () => resolve([stdout, stderr]));24 docgen.on('error', e => {25 throw e;26 });27 if (stdin) {28 docgen.stdin.write(stdin);29 }30 docgen.stdin.end();31 });32}33const component = fs.readFileSync(34 path.join(__dirname, '../../example/components/Component.js'),35);36describe('react-docgen CLI', () => {37 let tempDir;38 let tempComponents = [];39 let tempNoComponents = [];40 function createTempfiles(suffix, dir) {41 if (!tempDir) {42 tempDir = temp.mkdirSync();43 }44 if (!dir) {45 dir = tempDir;46 } else {47 dir = path.join(tempDir, dir);48 try {49 fs.mkdirSync(dir);50 } catch (error) {51 if (error.message.indexOf('EEXIST') === -1) {52 throw error;53 }54 }55 }56 if (!suffix) {57 suffix = 'js';58 }59 const componentPath = path.join(dir, 'Component.' + suffix);60 const componentFile = fs.openSync(componentPath, 'w');61 fs.writeSync(componentFile, component.toString());62 fs.closeSync(componentFile);63 const noComponentPath = path.join(dir, 'NoComponent.' + suffix);64 const noComponentFile = fs.openSync(noComponentPath, 'w');65 fs.writeSync(noComponentFile, '{}');66 fs.closeSync(noComponentFile);67 tempComponents.push(componentPath);68 tempNoComponents.push(noComponentPath);69 return dir;70 }71 afterEach(() => {72 if (tempDir) {73 rimraf.sync(tempDir);74 }75 tempDir = null;76 tempComponents = [];77 tempNoComponents = [];78 }, TEST_TIMEOUT);79 it(80 'reads from stdin',81 () => {82 return run([], component).then(([stdout, stderr]) => {83 expect(stdout).not.toBe('');84 expect(stderr).toBe('');85 });86 },87 TEST_TIMEOUT,88 );89 it(90 'reads files provided as command line arguments',91 () => {92 createTempfiles();93 return run(tempComponents.concat(tempNoComponents)).then(94 ([stdout, stderr]) => {95 expect(stdout).toContain('Component');96 expect(stderr).toContain('NoComponent');97 },98 );99 },100 TEST_TIMEOUT,101 );102 it(103 'reads directories provided as command line arguments',104 () => {105 createTempfiles();106 return run([tempDir]).then(([stdout, stderr]) => {107 expect(stdout).toContain('Component');108 expect(stderr).toContain('NoComponent');109 });110 },111 TEST_TIMEOUT,112 );113 it(114 'considers js and jsx by default',115 () => {116 createTempfiles();117 createTempfiles('jsx');118 createTempfiles('foo');119 return run([tempDir]).then(([stdout, stderr]) => {120 expect(stdout).toContain('Component.js');121 expect(stdout).toContain('Component.jsx');122 expect(stdout).not.toContain('Component.foo');123 expect(stderr).toContain('NoComponent.js');124 expect(stderr).toContain('NoComponent.jsx');125 expect(stderr).not.toContain('NoComponent.foo');126 });127 },128 TEST_TIMEOUT,129 );130 it(131 'considers files with the specified extension',132 () => {133 createTempfiles('foo');134 createTempfiles('bar');135 const verify = ([stdout, stderr]) => {136 expect(stdout).toContain('Component.foo');137 expect(stdout).toContain('Component.bar');138 expect(stderr).toContain('NoComponent.foo');139 expect(stderr).toContain('NoComponent.bar');140 };141 return Promise.all([142 run(['--extension=foo', '--extension=bar', tempDir]).then(verify),143 run(['-x', 'foo', '-x', 'bar', tempDir]).then(verify),144 ]);145 },146 TEST_TIMEOUT,147 );148 it(149 'ignores files in node_modules, __tests__ and __mocks__ by default',150 () => {151 createTempfiles(null, 'node_modules');152 createTempfiles(null, '__tests__');153 createTempfiles(null, '__mocks__');154 return run([tempDir]).then(([stdout, stderr]) => {155 expect(stdout).toBe('');156 expect(stderr).toBe('');157 });158 },159 TEST_TIMEOUT,160 );161 it(162 'ignores specified folders',163 () => {164 createTempfiles(null, 'foo');165 const verify = ([stdout, stderr]) => {166 expect(stdout).toBe('');167 expect(stderr).toBe('');168 };169 return Promise.all([170 run(['--ignore=foo', tempDir]).then(verify),171 run(['-i', 'foo', tempDir]).then(verify),172 ]);173 },174 TEST_TIMEOUT,175 );176 it(177 'writes to stdout',178 () => {179 return run([], component).then(([stdout, stderr]) => {180 expect(stdout.length > 0).toBe(true);181 expect(stderr.length).toBe(0);182 });183 },184 TEST_TIMEOUT,185 );186 it(187 'writes to stderr',188 () => {189 return run([], '{}').then(([stdout, stderr]) => {190 expect(stderr.length > 0).toBe(true);191 expect(stdout.length).toBe(0);192 });193 },194 TEST_TIMEOUT,195 );196 it(197 'writes to a file if provided',198 () => {199 const outFile = temp.openSync();200 createTempfiles();201 const verify = ([stdout]) => {202 expect(fs.readFileSync(outFile.path)).not.toBe('');203 expect(stdout).toBe('');204 };205 return Promise.all([206 run(['--out=' + outFile.path, tempDir]).then(verify),207 run(['-o', outFile.path, tempDir]).then(verify),208 ]);209 },210 TEST_TIMEOUT,211 );212 describe('--resolver', () => {213 it(214 'accepts the names of built in resolvers',215 () => {216 return Promise.all([217 // No option passed: same as --resolver=findExportedComponentDefinition218 run([219 path.join(__dirname, '../../example/components/Component.js'),220 ]).then(([stdout]) => {221 expect(stdout).toContain('Component');222 }),223 run([224 '--resolver=findExportedComponentDefinition',225 path.join(__dirname, '../../example/components/Component.js'),226 ]).then(([stdout]) => {227 expect(stdout).toContain('Component');228 }),229 run([230 '--resolver=findAllComponentDefinitions',231 path.join(__dirname, './example/MultipleComponents.js'),232 ]).then(([stdout]) => {233 expect(stdout).toContain('ComponentA');234 expect(stdout).toContain('ComponentB');235 }),236 ]);237 },238 TEST_TIMEOUT,239 );240 it(241 'accepts a path to a resolver function',242 () => {243 return Promise.all([244 run([245 '--resolver=' + path.join(__dirname, 'example/customResolver.js'),246 path.join(__dirname, '../../example/components/Component.js'),247 ]).then(([stdout]) => {248 expect(stdout).toContain('Custom');249 }),250 ]);251 },252 TEST_TIMEOUT,253 );254 });255 describe('--exclude/-e', () => {256 it(257 'ignores files by name',258 () => {259 createTempfiles(null, 'foo');260 createTempfiles(null, 'bar');261 const verify = ([stdout, stderr]) => {262 expect(stdout).toBe('');263 expect(stderr).toBe('');264 };265 return run([266 '--exclude=Component.js',267 '--exclude=NoComponent.js',268 tempDir,269 ]).then(verify);270 },271 TEST_TIMEOUT,272 );273 it(274 'ignores files by regex',275 () => {276 createTempfiles(null, 'foo');277 createTempfiles(null, 'bar');278 const verify = ([stdout, stderr]) => {279 expect(stdout).toBe('');280 expect(stderr).toBe('');281 };282 return run(['--exclude=/.*Component\\.js/', tempDir]).then(verify);283 },284 TEST_TIMEOUT,285 );286 });...
jobQueue.js
Source:jobQueue.js
...23 * @param {Object} socket24 * @param {String} dir25 * @return {Promise}26 */27 createTempFiles(model, socket, dir) {28 const slides = model.slides || [model.slide];29 return new Promise((resolve, reject) => {30 async.waterfall([31 (callback) => {32 console.log('creating temp dirs');33 helpers.createTempDirs(dir)34 .then(dirs => {35 callback(null, dirs);36 })37 .catch(e => {38 callback(e);39 });40 },41 (dirs, callback) => {42 try {43 progressResponse(socket, { progress: 0, message: 'Downloading Assets' });44 if (!model.narration || !model.narration.file) {45 callback(null, dirs);46 return;47 }48 console.log('Downloading Audio');49 const narrationFile = `${dirs.audio}${model.narration.name}`50 helpers.download(model.narration.file, narrationFile, () => {51 model.narration.file = narrationFile;52 callback(null, dirs);53 });54 } catch (e) {55 callback(e);56 }57 },58 (dirs, callback) => {59 console.log('Downloading Images/Video');60 helpers.downloadSlides(socket, dirs, slides, callback);61 },62 (dirs, callback) => {63 console.log('Writing Project Config');64 helpers.writeFile(dirs.json + 'config.json', model, callback);65 }66 ], (e, result) => {67 if (e) {68 reject(new JobQueueError(e.message, model.type));69 return false;70 }71 resolve();72 });73 });74 }75 /**76 */77 addProject(project, socketId) {78 this.addJob(project, {79 type: 'project',80 projectId: project._id,81 socketId: socketId82 });83 }84 /**85 */86 addPreview(preview, socketId) {87 this.addJob(preview, {88 type: 'preview',89 previewId: preview._id,90 socketId: socketId91 });92 }93 /**94 * Save project assets before adding to job queue95 * This frees up the job queue to only handle jobs that are ready to compile96 * @param {Object} model97 * @param {Object} jobData98 */99 addJob(model, jobData) {100 const socket = io().sockets.connected[jobData.socketId];101 const dir = `${appRoot}/temp/${model._id}`;102 this.createTempFiles(model, socket, dir)103 .then(() => {104 console.log('temp files downloaded')105 this.queueJob(new Job(jobData), socket);106 })107 .catch(e => {108 errorHandler(e, socket);109 // Delete saved data and files110 model.remove(() => {111 helpers.clearFiles([dir + '/**']);112 });113 });114 }115 /**116 * Added Job to queue...
compiler.js
Source:compiler.js
...95 } else {96 callback('cant format board info');97 }98 }99 function createTempFiles(data, callback) {100 LOG.info('createTempInoFile');101 let tmpPath = PATH.join(OS.homedir(), '.web2boardjs', 'tmp', UUIDV4());102 MKDIRP.sync(tmpPath);103 ASYNC.parallel([104 ASYNC.apply(MKDIRP, tmpPath + PATHS.compilationFolder),105 ASYNC.apply(createTempInoFile, data, tmpPath),106 ], function (err, results) {107 callback(err, tmpPath);108 });109 }110 function createTempInoFile(data, tmpPath, callback) {111 let inoFilePath = PATH.join(tmpPath, PATHS.tempInoFile);112 FS.writeFile(inoFilePath, data.code, function (err) {113 callback(err, inoFilePath);...
speech-to-text.js
Source:speech-to-text.js
...37 });38 });39 });40};41SpeechToText.createTempFiles = function createTempFiles(obj) {42 var tempFiles = [SpeechToText.createTempFile('.wav'), SpeechToText.createTempFile('.wav')];43 return Promise.all(tempFiles).then(function(files) {44 obj.source = files[0];45 obj.upsample = files[1];46 return obj;47 });48};49SpeechToText.downloadWav = function downloadWav(obj) {50 return new Promise(function(resolve, reject) {51 var sourceStream = fs.createWriteStream(obj.source.path);52 sourceStream.on('finish', function() {53 resolve(obj);54 });55 request(obj.url)56 .on('error', reject)57 .pipe(sourceStream);58 });59};60SpeechToText.transcodeTo16k = function transcodeTo16k(obj) {61 return new Promise(function(resolve, reject) {62 var job = sox.transcode(obj.source.path, obj.upsample.path, {63 sampleRate: 16000,64 format: 'wav',65 channelCount: 166 });67 job.on('error', reject);68 job.on('end', function() {69 console.log('coversion done');70 resolve(obj);71 });72 job.start();73 });74};75SpeechToText.toText = function toText(obj) {76 return new Promise(function(resolve, reject) {77 var params = utils.changeCase('snakeCase', {78 audio: fs.createReadStream(obj.upsample.path),79 contentType: 'audio/l16; rate=16000'80 });81 SpeechToText.watson.recognize(params, function(err, res) {82 if (err) {83 return reject(err);84 }85 obj.res = res;86 resolve(obj);87 });88 });89};90SpeechToText.cleanUp = function cleanUp(obj) {91 return new Promise(function(resolve, reject) {92 obj.source.cleanupFn();93 obj.upsample.cleanupFn();94 resolve(obj);95 });96};97SpeechToText.getText = function getText(wavUrl) {98 var obj = {99 url: wavUrl100 };101 SpeechToText.createTempFiles(obj)102 .then(SpeechToText.downloadWav)103 .then(SpeechToText.transcodeTo16k)104 .then(SpeechToText.toText)105 .then(SpeechToText.cleanUp);106};...
cacheBusterTest.js
Source:cacheBusterTest.js
...53 done();54 }55 });56});57function createTempFiles() {58 try {59 fs.mkdirSync(tmpPath);60 } catch (e) {61 if (e.code !== "EEXIST") throw e;62 }63 fs.writeFileSync(path.join(tmpPath, tmpCss), ".bar {}");...
concatenate.js
Source:concatenate.js
...60 return data;61};62const concatenate = async (PATH) => {63 const fileList = getTranslationsList(PATH);64 const tmpFolder = createTempFiles(fileList);65 const esFileList = await preprocessJs(tmpFolder);66 const data = readData(esFileList);67 tmpFolder.removeCallback();68 return data;69};70module.exports = {71 concatenate,...
warmUpChecksumCacheTest.js
Source:warmUpChecksumCacheTest.js
...30 done();31 });32 });33});34function createTempFiles() {35 [tmpPath, tmpSubPath1, tmpSubPath2].forEach(function (dir) {36 try {37 fs.mkdirSync(dir);38 } catch (e) {39 if (e.code !== "EEXIST") throw e;40 }41 });42 fs.writeFileSync(path.join(tmpSubPath1, tmp1Css), ".bar1 {}");43 fs.writeFileSync(path.join(tmpSubPath2, tmp2Css), ".bar2 {}");...
start.js
Source:start.js
...6const temp = path.resolve(__dirname, '../temp/')7const pidFilePath = path.join(temp, 'beauty-json-clipboard.pid')8const outFilePath = path.join(temp, 'out.log')9const errorFilePath = path.join(temp, 'error.log')10function createTempFiles() {11 if (!fs.existsSync(temp)) {12 fs.mkdirSync(temp);13 }14 try {15 fs.writeFileSync(pidFilePath, '', { flag: 'wx' });16 fs.writeFileSync(outFilePath, '', { flag: 'wx' });17 fs.writeFileSync(errorFilePath, '', { flag: 'wx' });18 } catch(e){19 return20 }21}22program23 .command('start')24 .description('start listening from clipboard')25 .action(() => {26 createTempFiles()27 pm2.start(path.resolve(__dirname, '../lib/index.js'), {28 name: APP_NAME,29 pid: pidFilePath,30 output: outFilePath,31 error: errorFilePath,32 interpreter: 'node',33 instances: 1,34 autorestart: false35 }, () => {36 pm2.disconnect()37 console.log('⨠I am ready to beautify your clipboard\'s JSONs')38 });...
Using AI Code Generation
1describe('My First Test', () => {2 it('Does not do much!', () => {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1Cypress.Commands.add('createTempFiles', (fileName, fileContent, fileType) => {2 cy.window().then(win => {3 cy.fixture(fileName, 'base64').then(fileContent => {4 cy.get('input[type=file]').upload({5 });6 });7 });8});9Cypress.Commands.add('createTempFiles', (fileName, fileContent, fileType) => {10 cy.window().then(win => {11 cy.fixture(fileName, 'base64').then(fileContent => {12 cy.get('input[type=file]').upload({13 });14 });15 });16});17Cypress.Commands.add('createTempFiles', (fileName, fileContent, fileType) => {18 cy.window().then(win => {19 cy.fixture(fileName, 'base64').then(fileContent => {20 cy.get('input[type=file]').upload({21 });22 });23 });24});25Cypress.Commands.add('createTempFiles', (fileName, fileContent, fileType) => {26 cy.window().then(win => {27 cy.fixture(fileName, 'base64').then(fileContent => {28 cy.get('input[type=file]').upload({29 });30 });31 });32});33Cypress.Commands.add('createTempFiles', (fileName, fileContent, fileType) => {34 cy.window().then(win => {35 cy.fixture(fileName, 'base64').then(fileContent => {36 cy.get('input[type=file]').upload({37 });38 });39 });40});41Cypress.Commands.add('createTempFiles', (fileName, fileContent, fileType) => {42 cy.window().then(win => {43 cy.fixture(fileName, 'base64').then(fileContent => {44 cy.get('input[type=file]').upload({45 });46 });47 });48});49Cypress.Commands.add('createTempFiles', (fileName, file
Using AI Code Generation
1describe('createTempFiles', () => {2 it('creates temporary files', () => {3 cy.createTempFiles({4 })5 cy.task('readTempFile', 'file1.txt').should('eq', 'contents of file 1')6 cy.task('readTempFile', 'file2.txt').should('eq', 'contents of file 2')7 })8})9const createTempFiles = require('cypress-terminal-report/src/installLogsPrinter').createTempFiles10const fs = require('fs-extra')11const path = require('path')12module.exports = (on, config) => {13 on('task', {14 readTempFile(fileName) {15 return fs.readFileSync(path.join(config.env.tempDir, fileName), 'utf-8')16 },17 })18 createTempFiles(config.env.tempDir)19}20const { addMatchImageSnapshotCommand } = require('cypress-image-snapshot/command')21addMatchImageSnapshotCommand({22})23Cypress.Commands.add('createTempFiles', (files) => {24 const { createTempFiles } = require('cypress-terminal-report/src/installLogsPrinter')25 createTempFiles(Cypress.env('tempDir'), files)26})27{28 "env": {29 }30}
Using AI Code Generation
1describe('Test Suite', function(){2 it('Test Case', function(){3 cy.get('.gLFyf').type('Selenium')4 cy.get('.gNO89b').click()5 cy.get('h3').should('have.text', 'Selenium - Web Browser Automation')6 })7})8describe('Test Suite', function(){9 it('Test Case', function(){10 cy.get('.gLFyf').type('Selenium')11 cy.get('.gNO89b').click()12 cy.get('h3').should('have.text', 'Selenium - Web Browser Automation')13 })14})15describe('Test Suite', function(){16 it('Test Case', function(){17 cy.get('.gLFyf').type('Selenium')18 cy.get('.gNO89b').click()19 cy.get('h3').should('have.text', 'Selenium - Web Browser Automation')20 })21})22describe('Test Suite', function(){23 it('Test Case', function(){24 cy.get('.gLFyf').type('Selenium')25 cy.get('.gNO89b').click()26 cy.get('h3').should('have.text', 'Selenium - Web Browser Automation')27 })28})29describe('Test Suite', function(){30 it('Test Case', function(){31 cy.get('.gLFyf').type('Selenium')32 cy.get('.gNO89b').click()33 cy.get('h3').should('have.text', 'Selenium - Web Browser Automation')34 })35})36describe('Test Suite', function(){37 it('Test Case', function(){
Using AI Code Generation
1describe('Test', () => {2 before(() => {3 cy.createTempFiles({4 {5 },6 {7 },8 });9 });10 it('should pass', () => {11 cy.readFile('cypress/fixtures/test1.txt').should('equal', 'Hello World');12 cy.readFile('cypress/fixtures/test2.txt').should('equal', 'Hello World');13 });14});15Cypress.Commands.add('createTempFiles', (options) => {16 const { files } = options;17 files.forEach((file) => {18 cy.writeFile(`cypress/fixtures/${file.fileName}`, file.content);19 });20});
Using AI Code Generation
1describe('Test', function() {2 it('Test', function() {3 cy.createTempFiles(1, 'txt').then((files) => {4 cy.fixture(files[0].name).then((fileContent) => {5 cy.log(fileContent);6 });7 });8 });9});10Cypress.Commands.add('createTempFiles', (count, extension) => {11 const files = [];12 for (let i = 0; i < count; i++) {13 const fileName = `${Cypress._.random(0, 1e9)}.${extension}`;14 cy.writeFile(`cypress/fixtures/${fileName}`, 'test');15 files.push({ name: fileName });16 }17 return cy.wrap(files);18});
Using AI Code Generation
1const cypress = require('cypress')2cypress.createTempFiles()3const cypress = require('cypress')4cypress.createTempFiles()5const cypress = require('cypress')6cypress.createTempFiles()7const cypress = require('cypress')8cypress.createTempFiles()9const cypress = require('cypress')10cypress.createTempFiles()11const cypress = require('cypress')12cypress.createTempFiles()13const cypress = require('cypress')14cypress.createTempFiles()15const cypress = require('cypress')16cypress.createTempFiles()
Using AI Code Generation
1describe('create temp files', () => {2 it('create temp files', () => {3 cy.createTempFiles({4 files: {5 },6 }).then((tempFilePaths) => {7 console.log(tempFilePaths);8 });9 });10});11const createTempFiles = require('cypress-create-temp-files');12module.exports = (on) => {13 on('task', {14 });15};16Cypress.Commands.add('createTempFiles', (options) => {17 return cy.task('createTempFiles', options);18});19{20}21{22 "scripts": {23 },24 "devDependencies": {25 }26}
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!!