Best JavaScript code snippet using cypress
cache.js
Source:cache.js
1var path = require( 'path' );2var fs = require( 'graceful-fs' );3var del = require( 'del' ).sync;4var utils = require( './utils' );5var writeJSON = utils.writeJSON;6var cache = {7 /**8 * Load a cache identified by the given Id. If the element does not exists, then initialize an empty9 * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted10 * then the cache module directory `./cache` will be used instead11 *12 * @method load13 * @param docId {String} the id of the cache, would also be used as the name of the file cache14 * @param [cacheDir] {String} directory for the cache entry15 */16 load: function ( docId, cacheDir ) {17 var me = this;18 me._visited = { };19 me._persisted = { };20 me._pathToFile = cacheDir ? path.resolve( cacheDir, docId ) : path.resolve( __dirname, './.cache/', docId );21 if ( fs.existsSync( me._pathToFile ) ) {22 me._persisted = utils.tryParse( me._pathToFile, { } );23 }24 },25 /**26 * Load the cache from the provided file27 * @method loadFile28 * @param {String} pathToFile the path to the file containing the info for the cache29 */30 loadFile: function ( pathToFile ) {31 var me = this;32 var dir = path.dirname( pathToFile );33 var fName = path.basename( pathToFile );34 me.load( fName, dir );35 },36 /**37 * Returns the entire persisted object38 * @method all39 * @returns {*}40 */41 all: function () {42 return this._persisted;43 },44 keys: function () {45 return Object.keys( this._persisted );46 },47 /**48 * sets a key to a given value49 * @method setKey50 * @param key {string} the key to set51 * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify52 */53 setKey: function ( key, value ) {54 this._visited[ key ] = true;55 this._persisted[ key ] = value;56 },57 /**58 * remove a given key from the cache59 * @method removeKey60 * @param key {String} the key to remove from the object61 */62 removeKey: function ( key ) {63 delete this._visited[ key ]; // esfmt-ignore-line64 delete this._persisted[ key ]; // esfmt-ignore-line65 },66 /**67 * Return the value of the provided key68 * @method getKey69 * @param key {String} the name of the key to retrieve70 * @returns {*} the value from the key71 */72 getKey: function ( key ) {73 this._visited[ key ] = true;74 return this._persisted[ key ];75 },76 /**77 * Remove keys that were not accessed/set since the78 * last time the `prune` method was called.79 * @method _prune80 * @private81 */82 _prune: function () {83 var me = this;84 var obj = { };85 var keys = Object.keys( me._visited );86 // no keys visited for either get or set value87 if ( keys.length === 0 ) {88 return;89 }90 keys.forEach( function ( key ) {91 obj[ key ] = me._persisted[ key ];92 } );93 me._visited = { };94 me._persisted = obj;95 },96 /**97 * Save the state of the cache identified by the docId to disk98 * as a JSON structure99 * @param [noPrune=false] {Boolean} whether to remove from cache the non visited files100 * @method save101 */102 save: function ( noPrune ) {103 var me = this;104 (!noPrune) && me._prune();105 writeJSON( me._pathToFile, me._persisted );106 },107 /**108 * remove the file where the cache is persisted109 * @method removeCacheFile110 * @return {Boolean} true or false if the file was successfully deleted111 */112 removeCacheFile: function () {113 return del( this._pathToFile, { force: true } );114 },115 /**116 * Destroy the file cache and cache content.117 * @method destroy118 */119 destroy: function () {120 var me = this;121 me._visited = { };122 me._persisted = { };123 me.removeCacheFile();124 }125};126module.exports = {127 /**128 * Alias for create. Should be considered depreacted. Will be removed in next releases129 *130 * @method load131 * @param docId {String} the id of the cache, would also be used as the name of the file cache132 * @param [cacheDir] {String} directory for the cache entry133 * @returns {cache} cache instance134 */135 load: function ( docId, cacheDir ) {136 return this.create( docId, cacheDir );137 },138 /**139 * Load a cache identified by the given Id. If the element does not exists, then initialize an empty140 * cache storage.141 *142 * @method create143 * @param docId {String} the id of the cache, would also be used as the name of the file cache144 * @param [cacheDir] {String} directory for the cache entry145 * @returns {cache} cache instance146 */147 create: function ( docId, cacheDir ) {148 var obj = Object.create( cache );149 obj.load( docId, cacheDir );150 return obj;151 },152 createFromFile: function ( filePath ) {153 var obj = Object.create( cache );154 obj.loadFile( filePath );155 return obj;156 },157 /**158 * Clear the cache identified by the given id. Caches stored in a different cache directory can be deleted directly159 *160 * @method clearCache161 * @param docId {String} the id of the cache, would also be used as the name of the file cache162 * @param cacheDir {String} the directory where the cache file was written163 * @returns {Boolean} true if the cache folder was deleted. False otherwise164 */165 clearCacheById: function ( docId, cacheDir ) {166 var filePath = cacheDir ? path.resolve( cacheDir, docId ) : path.resolve( __dirname, './.cache/', docId );167 return del( filePath, { force: true } ).length > 0;168 },169 /**170 * Remove all cache stored in the cache directory171 * @method clearAll172 * @returns {Boolean} true if the cache folder was deleted. False otherwise173 */174 clearAll: function ( cacheDir ) {175 var filePath = cacheDir ? path.resolve( cacheDir ) : path.resolve( __dirname, './.cache/' );176 return del( filePath, { force: true } ).length > 0;177 }...
settings.js
Source:settings.js
...84 }85 , _.cloneDeep(obj))86 },87 id (projectRoot) {88 const file = this._pathToFile(projectRoot, 'cypress.json')89 return fs.readJsonAsync(file)90 .get('projectId')91 .catch(() => {92 return null93 })94 },95 exists (projectRoot) {96 const file = this._pathToFile(projectRoot, 'cypress.json')97 //# first check if cypress.json exists98 return fs.statAsync(file)99 .then(() =>100 //# if it does also check that the projectRoot101 //# directory is writable102 {103 return fs.accessAsync(projectRoot, fs.W_OK)104 }).catch({ code: 'ENOENT' }, (err) => {105 //# cypress.json does not exist, we missing project106 log('cannot find file %s', file)107 return this._err('PROJECT_DOES_NOT_EXIST', projectRoot, err)108 }).catch((err) => {109 if (errors.isCypressErr(err)) {110 throw err111 }112 //# else we cannot read due to folder permissions113 return this._logReadErr(file, err)114 })115 },116 read (projectRoot) {117 const file = this._pathToFile(projectRoot, 'cypress.json')118 return fs.readJsonAsync(file)119 .catch({ code: 'ENOENT' }, () => {120 return this._write(file, {})121 }).then((json = {}) => {122 const changed = this._applyRewriteRules(json)123 //# if our object is unchanged124 //# then just return it125 if (_.isEqual(json, changed)) {126 return json127 }128 //# else write the new reduced obj129 return this._write(file, changed)130 }).catch((err) => {131 if (errors.isCypressErr(err)) {132 throw err133 }134 return this._logReadErr(file, err)135 })136 },137 readEnv (projectRoot) {138 const file = this._pathToFile(projectRoot, 'cypress.env.json')139 return fs.readJsonAsync(file)140 .catch({ code: 'ENOENT' }, () => {141 return {}142 })143 .catch((err) => {144 if (errors.isCypressErr(err)) {145 throw err146 }147 return this._logReadErr(file, err)148 })149 },150 write (projectRoot, obj = {}) {151 return this.read(projectRoot)152 .then((settings) => {153 _.extend(settings, obj)154 const file = this._pathToFile(projectRoot, 'cypress.json')155 return this._write(file, settings)156 })157 },158 remove (projectRoot) {159 return fs.unlinkSync(this._pathToFile(projectRoot, 'cypress.json'))160 },161 pathToCypressJson (projectRoot) {162 return this._pathToFile(projectRoot, 'cypress.json')163 },164 pathToCypressEnvJson (projectRoot) {165 return this._pathToFile(projectRoot, 'cypress.env.json')166 },...
activityLog.js
Source:activityLog.js
1'use strict'2const fs = require('fs')3const path = require('path')4function ActivityLogInit (dir) {5 if (!dir) {6 console.error('Must include dir')7 return {}8 }9 return ActivityLog.config(dir)10}11const ActivityLog = {12 config (dir) {13 this._pathToFile = path.resolve(path.join(dir, '/ffmpeg-streamer-activity.json'))14 this._running = fs.existsSync(this._pathToFile)15 this._activity = this._activityFromFile16 return this17 },18 create () {19 try {20 fs.writeFileSync(this._pathToFile, JSON.stringify([]))21 this._running = true22 } catch (err) {23 console.error(err.message)24 this._running = false25 }26 this._activity = []27 return this28 },29 destroy () {30 try {31 fs.unlinkSync(this._pathToFile)32 } catch (err) {33 console.warn(err.message)34 }35 this._running = false36 this._activity = []37 return this38 },39 add (data) {40 if (!this._running) {41 console.warn('Activity logging is not active')42 return43 }44 if (!data) {45 console.warn('Must pass a data object')46 return47 }48 this._activity = this._activityFromFile49 this._activity.push(data)50 while (this._activity.length > 1) {51 this._activity.shift()52 }53 try {54 fs.writeFileSync(this._pathToFile, JSON.stringify(this._activity))55 } catch (err) {56 console.warn(err.message)57 this._running = false58 }59 return this60 },61 remove (index) {62 if (!this.running) {63 console.warn('Activity logging is not active')64 return65 }66 if (typeof index === 'undefined' || isNaN(index)) {67 console.warn('Must pass an array index')68 return69 }70 if (!(index in this._activity)) {71 console.warn('Index not in array')72 return73 }74 this._activity = this._activityFromFile75 this._activity.splice(index, 1)76 try {77 fs.writeFileSync(this._pathToFile, JSON.stringify(this._activity))78 } catch (err) {79 console.warn(err.message)80 this._running = false81 }82 return this83 },84 get running () {85 return this._running86 },87 get activity () {88 return this._activity89 },90 get lastActivity () {91 if (!this._activity.length) {92 return null93 }94 return this._activity[this._activity.length - 1]95 },96 get _activityFromFile () {97 try {98 const data = fs.readFileSync(this._pathToFile)99 const jsonData = JSON.parse(data)100 if (Array.isArray(jsonData)) {101 return jsonData102 } else {103 return []104 }105 } catch (err) {106 // console.log(err.message);107 return []108 }109 }110}...
VfsFile.js
Source:VfsFile.js
1import trimExt from '../util/trimExt';2class VfsFile {3 #_pathToFile; // File4 #_ownerUuid; // string? as UUID5 #_vfsMetaFile; // VfsMetaFile6 constructor(ownerUuid, pathToFile, vfsMetaFile) {7 this.#_pathToFile = pathToFile;8 this.#_ownerUuid = ownerUuid;9 this.#_vfsMetaFile = vfsMetaFile;10 }11 getPath() {12 return this.#_pathToFile;13 }14 getPathToMetaFile() {15 return trimExt(trimExt(this.#_pathToFile)) + '.meta.json'; // my_file.gz.enc => my_file.meta.json16 }17 getVfsMetaFile() {18 return this.#_vfsMetaFile;19 }20}...
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 cy.get('a').contains('Commands').click()4 cy.get('a').contains('Navigation').click()5 cy.get('a').contains('Location').click()6 cy.get('a
Using AI Code Generation
1cy.get('input[type="file"]').attachFile('path/to/file');2cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'drag-n-drop' });3cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'drag-n-drop' });4cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });5cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });6cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });7cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });8cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });9cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });10cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });11cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });12cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });13cy.get('input[type="file"]').attachFile('path/to/file', { subjectType: 'input' });
Using AI Code Generation
1cy._pathToFile('data.csv', 'fixtures')2cy._pathToFile('data.csv', 'fixtures')3cy._pathToFile('data.csv', 'fixtures')4cy._pathToFile('data.csv', 'fixtures')5cy._pathToFile('data.csv', 'fixtures')6cy._pathToFile('data.csv', 'fixtures')7cy._pathToFile('data.csv', 'fixtures')8cy._pathToFile('data.csv', 'fixtures')9cy._pathToFile('data.csv', 'fixtures')10Cypress.Commands.add('_pathToFile', (fileName, folder) => {11 return folder + '/' + fileName;12});13import './commands'14module.exports = (on, config) => {15 on('task', {16 _pathToFile (fileName, folder) {17 return folder + '/' + fileName;18 }19 })20}21describe('Test', () => {22 it('should upload file', () => {23 cy.get('input[type="file"]').attachFile('data.csv', { subjectType: 'input' })24 })25})
Using AI Code Generation
1const path = require('path')2const filePath = path.join(__dirname, 'files', 'example.txt')3cy.get('input[type="file"]').attachFile(filePath)4const path = require('path')5const filePath = path.join(__dirname, 'files', 'example.txt')6cy.get('input[type="file"]').attachFile(filePath)7const path = require('path')8const filePath = path.join(__dirname, 'files', 'example.txt')9cy.get('input[type="file"]').attachFile(filePath)10const path = require('path')11const filePath = path.join(__dirname, 'files', 'example.txt')12cy.get('input[type="file"]').attachFile(filePath)13const path = require('path')14const filePath = path.join(__dirname, 'files', 'example.txt')15cy.get('input[type="file"]').attachFile(filePath)16const path = require('path')17const filePath = path.join(__dirname, 'files', 'example.txt')18cy.get('input[type="file"]').attachFile(filePath)19const path = require('path')20const filePath = path.join(__dirname, 'files', 'example.txt')21cy.get('input[type="file"]').attachFile(filePath)22const path = require('path')23const filePath = path.join(__dirname, 'files', 'example.txt')24cy.get('input[type="file"]').attachFile(filePath)25const path = require('path')26const filePath = path.join(__dirname, 'files', 'example.txt')27cy.get('input[type="file"]').attachFile(filePath)28const path = require('path')29const filePath = path.join(__dirname, 'files', 'example.txt')30cy.get('input[type="file"]').attachFile(filePath)
Using AI Code Generation
1describe('Test', () => {2 it('should', () => {3 cy.get('a').click()4 cy.url().should('include', '/commands/files')5 cy.get('input[type=file]').attachFile('test.txt')6 cy.get('input[type=file]').should('have.value', 'C:\\fakepath\\test.txt')7 })8})9describe('Test', () => {10 it('should', () => {11 cy.get('a').click()12 cy.url().should('include', '/commands/files')13 cy.get('input[type=file]').attachFile('test.txt')14 cy.get('input[type=file]').should('have.value', 'C:\\fakepath\\test.txt')15 })16})17describe('Test', () => {18 it('should', () => {19 cy.get('a').click()20 cy.url().should('include', '/commands/files')21 cy.get('input[type=file]').attachFile('test.txt')22 cy.get('input[type=file]').should('have.value', 'C:\\fakepath\\test.txt')23 })24})25describe('Test', () => {26 it('should', () => {27 cy.get('a').click()28 cy.url().should('include', '/commands/files')29 cy.get('input[type=file]').attachFile('test.txt')30 cy.get('input[type=file]').should('have.value', 'C:\\fakepath\\test.txt')31 })32})33describe('Test', () => {34 it('should', () => {35 cy.get('a').click()36 cy.url().should('include', '/commands/files')37 cy.get('input[type=file]').attachFile('test.txt')38 cy.get('input[type=file]').should('have.value', 'C
Using AI Code Generation
1cy._pathToFile('test.json');2Cypress.Commands.add('_pathToFile', (path) => {3 return Cypress._.chain(path)4 .split('/')5 .reduce((acc, part) => {6 return Cypress._.isString(acc)7 ? Cypress._.chain(acc).split('\\').concat(part).join('\\').value()8 : Cypress._.chain(acc).concat(part).value();9 })10 .value();11});12Cypress.Commands.add('_pathToFile', (path) => {13 return Cypress._.chain(path)14 .split('/')15 .reduce((acc, part) => {16 return Cypress._.isString(acc)17 ? Cypress._.chain(acc).split('\\').concat(part).join('\\').value()18 : Cypress._.chain(acc).concat(part).value();19 })20 .value();21});22declare namespace Cypress {23 interface Chainable {24 _pathToFile(path: string): string;25 }26}27declare namespace Cypress {28 interface Chainable {29 _pathToFile(path: string): string;30 }31}32declare namespace Cypress {33 interface Chainable {34 _pathToFile(path: string): string;35 }36}37declare namespace Cypress {38 interface Chainable {39 _pathToFile(path: string): string;40 }41}42declare namespace Cypress {43 interface Chainable {44 _pathToFile(path: string): string;45 }46}47declare namespace Cypress {48 interface Chainable {49 _pathToFile(path: string): string;50 }51}
Using AI Code Generation
1cy._pathToFile('myFile.json')2Cypress.Commands.add('_pathToFile', (path) => {3 return path.replace(/^.*[\\\/]/, '')4})5Cypress.Commands.add('_pathToFile', (path) => {6 return path.replace(/^.*[\\\/]/, '')7})8Cypress.Commands.add('_pathToFile', (path) => {9 return path.replace(/^.*[\\\/]/, '')10})11Cypress.Commands.add('_pathToFile', (path) => {12 return path.replace(/^.*[\\\/]/, '')13})14Cypress.Commands.add('_pathToFile', (path) => {15 return path.replace(/^.*[\\\/]/, '')16})17Cypress.Commands.add('_pathToFile', (path) => {18 return path.replace(/^.*[\\\/]/, '')19})20Cypress.Commands.add('_pathToFile', (path) => {21 return path.replace(/^.*[\\\/]/, '')22})23Cypress.Commands.add('_pathToFile', (path) => {24 return path.replace(/^.*[\\\/]/, '')25})26Cypress.Commands.add('_pathToFile', (path) => {27 return path.replace(/^.*[\\\/]/, '')28})29Cypress.Commands.add('_pathToFile', (path) => {30 return path.replace(/^.*[\\\/]/, '')31})32Cypress.Commands.add('_pathToFile', (path
Using AI Code Generation
1describe('Test', () => {2 it('should be able to get the path of a file', () => {3 const path = Cypress._pathToFile('test.txt');4 cy.log(path);5 });6});7{8}9Cypress._pathToApp() - Get the path to the application10describe('Test', () => {11 it('should be able to get the path of the application', () => {12 const path = Cypress._pathToApp();13 cy.log(path);14 });15});16{17}18Cypress._pathToFixtures() - Get the path to the fixtures folder19describe('Test', () => {20 it('should be able to get the path of the fixtures folder', () => {21 const path = Cypress._pathToFixtures();22 cy.log(path);23 });24});25{26}27Cypress._pathToSupport() - Get the path to the support folder
Using AI Code Generation
1describe('Test', () => {2 it('test', () => {3 cy.get('input[type="file"]').attachFile(4 Cypress._pathToFile('test.pdf', 'fixtures')5 );6 });7});8describe('Test', () => {9 it('test', () => {10 cy.get('input[type="file"]').attachFile(11 Cypress._pathToFile('test.pdf', 'fixtures')12 );13 });14});15describe('Test', () => {16 it('test', () => {17 cy.get('input[type="file"]').attachFile(18 Cypress._pathToFile('test.pdf', 'fixtures')19 );20 });21});22describe('Test', () => {23 it('test', () => {24 cy.get('input[type="file"]').attachFile(25 Cypress._pathToFile('test.pdf', 'fixtures')26 );27 });28});29describe('Test', () => {30 it('test', () => {31 cy.get('input[type="file"]').attachFile(32 Cypress._pathToFile('test.pdf', 'fixtures')33 );34 });35});36describe('Test', () => {37 it('test', () => {38 cy.get('input[type="file"]').attachFile(39 Cypress._pathToFile('test.pdf', 'fixtures')40 );41 });42});
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!!