Best JavaScript code snippet using cypress
test.js
Source:test.js
1/**2 * This will load in a spreadsheet and replace the collection with the data in the3 * spreadsheet.4 * It knows what the colection is because it uses the path before the "spreadSheet"5 * command to lookup the config file in that path, and pull out the collection name, which6 * should always contain the characters, "master"7 * Written by Larry Madocks8 **/9var express = require('express');10var router = express.Router();11var restrict = require('../auth/restrict');12var multer = require("multer");13var xlsxj = require("xlsx-to-json");14var mapService = require('../services/map-service');15//var mongoXlsx = require("mongo-xlsx");16var dbVersion = require('../services/dbVersion'); //to update row in map dbVersion database17//var hbs = require('hbs');18//hbs.handlebars === require('handlebars');19const fs = require('fs');20var path = require('path');212223var unauthStatic = express.static(path.join(__dirname, '../public'));24var authStatic = path.join(__dirname, '../authorized');25262728/* GET home page. */29router.get('/', restrict, function(req, res, next) {30 /**31 * Was getting this error when using a folder in the url as a parameter: "Refused to apply style from" "because its 32 * MIME type ('text/html') is not a supported stylesheet MIME type"33 * Found someone talking about this on stackoverflow, but it was in Spanish, plus the fix is too complicated 34 * for using a folder as a parameter in the url. So I will have user insert folder in a form field.35 **/36 //router.get('/:collection', function(req, res, next) {37 // var collection = req.params.collection;38 // if (!(/master/.test(collection))) {39 // let err = "Invalid Collection: "+ collection;40 // console.error();41 // let vm = {42 // messageTitle: 'Error',43 // layout: 'simpleLayout',44 // serverMessage: err45 // };46 // console.error("Incorrect collection.");47 // res.redirect('/error');4849 // }50 return res.render('admin/test', {51 title: 'Import Data or SVG',52 layout: 'simpleLayout',53 baseUrl: JSON.stringify(req.baseUrl)54 //,collection:'master_test3'55 });56});5758//for some reason we are getting undefined fields from the excel file. This deletes them59function removeJunk(obj) {60 for (var prop in obj) {61 if (prop.length == 0) {62 delete obj[prop];63 }64 }65}66/**67 * Looks in list to see if key is in there. If so returns true68 **/69function inList(list, key) {70 return list.split(',').indexOf(key) > -171}727374////var upload = multer({ dest: './import' });75// Set The Storage Engine76var storage = multer.diskStorage({77 destination: function(req, file, cb) {78 if (req.dynamicDestination) {79 cb(null, req.dynamicDestination);80 }81 else cb("Error determining destination of file");8283 },84 filename: function(req, file, cb) {85 var fn = file.originalname + '-' + Date.now() + path.extname(file.originalname);86 req.myFileName = fn;87 cb(null, fn);88 }89});9091// Init Upload92const upload = multer({93 limits: { fileSize: 10000000 },94 fileFilter: function(req, file, cb) {95 checkFileTypeAndPermissions(req, file, cb);96 },97 storage: storage98}).single('myFile'); //This tag, "myFile" MUST match the form input name attribute in the importFile.hbs file99100//Get destination folder of where spreadsheet file is sent to101function destination(req, file) {102 var pathToConfigFile = req.params.path;103 //Now get the config.json data to get the collection name104 pathToConfigFile !== undefined ? pathToConfigFile = pathToConfigFile.replace(/slshslash/g, "\/") : pathToConfigFile = null; //instead of a "/" I replaced it with "slshslash" so it doesn't count as another parameter. This line changes it back to the slash ("/")105 if (pathToConfigFile) {106 var dynamicDestination = authStatic + "/" + pathToConfigFile;107 req.pathToConfigFile = pathToConfigFile; //insert this value in req so I can use it later on in checkFileTypeAndPermissions()108 req.dynamicDestination = dynamicDestination; //insert this in req so I can access it later on109 return pathToConfigFile; // successfully found destination. Code was this: cb(null, dynamicDestination);110 }111 else return null; //cb("Error determining destination of file");112}113// Check File Type and permissions114function checkFileTypeAndPermissions(req, file, cb) {115 // Allowed ext116 const filetypes = /svg|txt|js|css|html|md|json|xlsx|ai|jpeg|jpg|png|gif|sheet/;117 // Check ext118 const extname = filetypes.test(path.extname(file.originalname).toLowerCase());119 if (!extname) {120 return cb('Error: Incorrect file extension!');121 }122 // Check mime123 const mimetype = filetypes.test(file.mimetype);124 if (!mimetype) {125 return cb('Error: Incorrect file mimetype!');126 }127 var pathToConfigFile = destination(req, file); //set destination128 var permissions = req.user._doc.doc.permissions;129 if (!(inList(permissions, 'admin') || inList(permissions, 'editor') || inList(permissions, 'designer'))) {130 // return res.redirect('/'); // not found131 return cb('Invalid permission.');132133 }134 else if (inList(permissions, 'designer')) {135 var authorizedFolders = req.user._doc.doc.hasOwnProperty("folders") ? req.user._doc.doc.folders : "";136 137 if (pathToConfigFile) {138 var mainUrlFolder = req.pathToConfigFile; // req.originalUrl;139 var firstFolder = mainUrlFolder.split("/").slice(0,1).toString(); //get first folder (or directory) in the url string140 if (!(authorizedFolders.split(',').indexOf(firstFolder) > -1)) {141 //only compare the first folder, which would be > -1 if it were a match.142 return cb('Folder Not Available. Please check with your administrator for access to folder: ' + firstFolder);143144 }145 return cb(null, true);146 } else {147 cb("Error determining destination of file");148 }149150 }151152 return cb(null, true); //the user is either an admin or editor so have permissions in all folders. TODO: editor has all permissions?153}154155156157//router.use(express.static(path.join(__dirname, '../authorized')));158//var upload = multer({ storage : storage}).single('xlsx');159//after posting a spreadsheet file to upload, which will be saved in this folder160//and then inserted into the database. DO NOT CHANGE THIS FROM import!!161router.post('/:path', restrict,162 function(req, res, next) {163164 //now look to see if user permissions contain admin165166167 upload(req, res, function(err) {168 if (err) {169 res.json({170 status: "error",171 msg: err172 });173 }174 else {175176177 var pathToConfigFile = req.params.path;178 //Now get the config.json data to get the collection name179 pathToConfigFile !== undefined ? pathToConfigFile = pathToConfigFile.replace(/slshslash/g, "\/") : pathToConfigFile = null; //instead of a "/" I replaced it with "slshslash" so it doesn't count as another parameter. This line changes it back to the slash ("/")180 if (pathToConfigFile) {181 //'utf8', means return a string . If I take that out, then I get binary data back instead of a json structure.182 fs.readFile(authStatic + "/" + pathToConfigFile + "/config.json", 'utf8', (err, data) => {183 if (err) return res.json({184 status: "error",185 msg: 'Invalid path for config.json.'186 });187 var data2json = JSON.parse(data);188 if (data2json == undefined) {189 console.error("Bad json in config.file: " + pathToConfigFile + "/config.json");190 return res.json({191 status: "error",192 msg: "Bad json in config.file: " + pathToConfigFile + "/config.json"193 });194 }195 var collection = data2json.masterDB; //user see just a folder name. This adds _master to user the folder_master collection196197 //User can have multiple permissions, I suppose. If he has admin permissions and or editor permissions here 198 //then he can upload a spreadsheet. But if he only has designer, then he needs to have the collection199 //in the list of collections he can upload to.200 // var permissions = req.user._doc.doc.permissions;201 // if (!inList(permissions, 'admin') && !inList(permissions, 'editor') && inList(permissions, 'designer')) {202 // var authorizedCollections = req.user._doc.doc.collections;203204 // if (!inList(authorizedCollections, collection)) {205 // //only compare the first folder, which would be > -1 if it were a match.206 // return res.json({207 // status: "error",208 // msg: 'Missing permission for this collection.'209 // });210 // }211 // }212 var filePath = req.dynamicDestination + '/' + req.myFileName; //req.files[0].path; //do not add this because then it cannot find the file path + ".xlsx" 213214 if (!(/master/.test(collection))) {215 let err = "Invalid Collection";216 console.error();217 let vm = {218 messageTitle: 'Error',219 layout: 'simpleLayout',220 serverMessage: err221 };222 console.error("Incorrect collection.");223 res.redirect('/error');224225 }226227 // console.log(data); //masterDB228 if (filePath && collection) {229 //console.log("file path here: " + filePath);230 // mongoXlsx.xlsx2MongoData(filePath, null, function(err, mongoData) {231 // if (err) {232 // console.error(err);233 // res.redirect('/error');234 // }235 // else {236 // console.log('Mongo data:', mongoData);237 // }238 // });239 xlsxj({240 input: filePath, //__dirname + '/sample.xlsx',241 sheet: "Structure",242 output: null // set this to null if you are not using it!!! __dirname + '/output.json'243 }, function(err, result) {244 if (err) {245 console.error(err);246 res.redirect('/error');247 }248 else {249 mapService.removeAll(collection, (err) => {250 if (err) {251 console.error(err);252 res.redirect('/error');253 }254 for (var i = 0; i < result.length; i++) {255 var row = result[i];256 if (!row.hasOwnProperty('rowNumber')) {257 row.rowNumber = i.toString();258 }259 if (row.hasOwnProperty('id') && row.id.length == 0) {260 row.id = i.toString();261 }262 else if (!row.hasOwnProperty('id')) {263 row.id = i.toString();264 }265 removeJunk(row); //for some reason we are getting undefined fields from the excel file. This deletes them266 if (row.hasOwnProperty('id') && row.id.length > 0) {267 var id = row.id;268 var rowNumber = Number(row.rowNumber);269 let doc = {270 id: id,271 rowNumber: rowNumber,272 doc: row273 };274 mapService.addmap(doc, collection, function(err) {275 if (err) {276 console.error(err);277 res.redirect('/error');278 }279 });280 }281282 }283 dbVersion.updateRow(collection, (err, doc) => {284 if (err) {285 //Need to update the version number of this db286 console.log("Error updating dbVersion. Will create a new row for this collection slash db. Err: " + err);287 dbVersion.addRow({288 dbName: collection,289 dbVersion: 1290 }, () => {291 // var vm = {292 // status: 'success',293 // msg: 'success in updateRow for map. id: ' + data.id,294 // dbVersion: 1295 // };296297 // res.status(status).json(vm);298 //next(null);299300 res.status(204).end();301 //res.status(200).end();302 //res.render('import', vm);303 });304305 }306 else {307 /* update dbVersion of this collection */308309310 //doc contains the version number that we are sending back311 // var vm = {312 // dbVersion: doc,313 // status: 'success',314 // msg: 'success in updateRow for dbVersion. collection: ' + collection315 // };316317 //res.status(status).json(vm);318 //next(null);319 res.status(204).end();320 //res.status(200).end();321 //res.render('import', vm);322 }323 });324 });325326 //console.log(result);327 }328 });329330331332 } //if (filePath && collection) 333 });334 }335 else {336 return res.json({337 status: "error",338 msg: 'Invalid path for config.json.'339 });340 }341342343344 res.json({345 status: "Success"346 });347 }348349350351352 } //upload(req, res, function(err) {353 );354355356 } //function(req, res, next) {357);358
...
importSpread.js
Source:importSpread.js
1/**2 * This will load in a spreadsheet and replace the collection with the data in the3 * spreadsheet.4 * It knows what the colection is because it uses the path before the "spreadSheet"5 * command to lookup the config file in that path, and pull out the collection name, which6 * should always contain the characters, "master"7 * Written by Larry Madocks8 **/9var express = require('express');10var router = express.Router();11var restrict = require('../auth/restrict');12var multer = require("multer");13var xlsxj = require("xlsx-to-json");14var mapService = require('../services/map-service');15//var mongoXlsx = require("mongo-xlsx");16var dbVersion = require('../services/dbVersion'); //to update row in map dbVersion database17//var hbs = require('hbs');18//hbs.handlebars === require('handlebars');19const fs = require('fs');20var path = require('path');212223var unauthStatic = express.static(path.join(__dirname, '../public'));24var authStatic = path.join(__dirname, '../authorized');25262728/* GET home page. */29router.get('/', restrict, function(req, res, next) {30 /**31 * Was getting this error when using a folder in the url as a parameter: "Refused to apply style from" "because its32 * MIME type ('text/html') is not a supported stylesheet MIME type"33 * Found someone talking about this on stackoverflow, but it was in Spanish, plus the fix is too complicated34 * for using a folder as a parameter in the url. So I will have user insert folder in a form field.35 **/36 //router.get('/:collection', function(req, res, next) {37 // var collection = req.params.collection;38 // if (!(/master/.test(collection))) {39 // let err = "Invalid Collection: "+ collection;40 // console.error();41 // let vm = {42 // messageTitle: 'Error',43 // layout: 'simpleLayout',44 // serverMessage: err45 // };46 // console.error("Incorrect collection.");47 // res.redirect('/error');4849 // }50 return res.render('admin/importSpread', {51 title: 'Import Data or SVG',52 layout: 'simpleLayout',53 baseUrl: JSON.stringify(req.baseUrl)54 //,collection:'master_test3'55 });56});5758//for some reason we are getting undefined fields from the excel file. This deletes them59function removeJunk(obj) {60 for (var prop in obj) {61 if (prop.length == 0) {62 delete obj[prop];63 }64 }65}66/**67 * Looks in list to see if key is in there. If so returns true68 **/69function inList(list, key) {70 return list.split(',').indexOf(key) > -171}727374////var upload = multer({ dest: './import' });75// Set The Storage Engine76var storage = multer.diskStorage({77 destination: function(req, file, cb) {78 if (req.dynamicDestination) {79 cb(null, req.dynamicDestination);80 }81 else cb("Error determining destination of file");8283 },84 filename: function(req, file, cb) {85 var fn = file.originalname + '-' + Date.now() + path.extname(file.originalname);86 req.myFileName = fn;87 cb(null, fn);88 }89});9091// Init Upload92const upload = multer({93 limits: { fileSize: 10000000 },94 fileFilter: function(req, file, cb) {95 checkFileTypeAndPermissions(req, file, cb);96 },97 storage: storage98}).single('myFile'); //This tag, "myFile" MUST match the form input name attribute in the importFile.hbs file99100//Get destination folder of where spreadsheet file is sent to101function destination(req, file) {102 var pathToConfigFile = req.params.path;103 //Now get the config.json data to get the collection name104 pathToConfigFile !== undefined ? pathToConfigFile = pathToConfigFile.replace(/slshslash/g, "\/") : pathToConfigFile = null; //instead of a "/" I replaced it with "slshslash" so it doesn't count as another parameter. This line changes it back to the slash ("/")105 if (pathToConfigFile) {106 var dynamicDestination = authStatic + "/" + pathToConfigFile;107 req.pathToConfigFile = pathToConfigFile; //insert this value in req so I can use it later on in checkFileTypeAndPermissions()108 req.dynamicDestination = dynamicDestination; //insert this in req so I can access it later on109 return pathToConfigFile; // successfully found destination. Code was this: cb(null, dynamicDestination);110 }111 else return null; //cb("Error determining destination of file");112}113// Check File Type and permissions114function checkFileTypeAndPermissions(req, file, cb) {115 // Allowed ext116 const filetypes = /svg|txt|js|css|html|md|json|xlsx|ai|jpeg|jpg|png|gif|sheet/;117 // Check ext118 const extname = filetypes.test(path.extname(file.originalname).toLowerCase());119 if (!extname) {120 return cb('Error: Incorrect file extension!');121 }122 // Check mime123 const mimetype = filetypes.test(file.mimetype);124 if (!mimetype) {125 return cb('Error: Incorrect file mimetype!');126 }127 var pathToConfigFile = destination(req, file); //set destination128 var permissions = req.user._doc.doc.permissions;129 if (!(inList(permissions, 'admin') || inList(permissions, 'editor') || inList(permissions, 'designer'))) {130 // return res.redirect('/'); // not found131 return cb('Invalid permission.');132133 }134 else if (inList(permissions, 'designer')) {135 var authorizedFolders = req.user._doc.doc.hasOwnProperty("folders") ? req.user._doc.doc.folders : "";136137 if (pathToConfigFile) {138 var mainUrlFolder = req.pathToConfigFile; // req.originalUrl;139 var firstFolder = mainUrlFolder.split("/").slice(0,1).toString(); //get first folder (or directory) in the url string140 if (!(authorizedFolders.split(',').indexOf(firstFolder) > -1)) {141 //only compare the first folder, which would be > -1 if it were a match.142 return cb('Folder Not Available. Please check with your administrator for access to folder: ' + firstFolder);143144 }145 return cb(null, true);146 } else {147 cb("Error determining destination of file");148 }149150 }151152 return cb(null, true); //the user is either an admin or editor so have permissions in all folders. TODO: editor has all permissions?153}154155156157//router.use(express.static(path.join(__dirname, '../authorized')));158//var upload = multer({ storage : storage}).single('xlsx');159//after posting a spreadsheet file to upload, which will be saved in this folder160//and then inserted into the database. DO NOT CHANGE THIS FROM import!!161router.post('/:path', restrict,162 function(req, res, next) {163164 //now look to see if user permissions contain admin165166167 upload(req, res, function(err) {168 if (err) {169 res.json({170 status: "error",171 msg: err172 });173 }174 else {175176177 var pathToConfigFile = req.params.path;178 //Now get the config.json data to get the collection name179 pathToConfigFile !== undefined ? pathToConfigFile = pathToConfigFile.replace(/slshslash/g, "\/") : pathToConfigFile = null; //instead of a "/" I replaced it with "slshslash" so it doesn't count as another parameter. This line changes it back to the slash ("/")180 if (pathToConfigFile) {181 //'utf8', means return a string . If I take that out, then I get binary data back instead of a json structure.182 fs.readFile(authStatic + "/" + pathToConfigFile + "/config.json", 'utf8', (err, data) => {183 if (err) return res.json({184 status: "error",185 msg: 'Invalid path for config.json.'186 });187 var data2json = JSON.parse(data);188 if (data2json == undefined) {189 console.error("Bad json in config.file: " + pathToConfigFile + "/config.json");190 return res.json({191 status: "error",192 msg: "Bad json in config.file: " + pathToConfigFile + "/config.json"193 });194 }195 var collection = data2json.masterDB; //user see just a folder name. This adds _master to user the folder_master collection196197 //User can have multiple permissions, I suppose. If he has admin permissions and or editor permissions here 198 //then he can upload a spreadsheet. But if he only has designer, then he needs to have the collection199 //in the list of collections he can upload to.200 // var permissions = req.user._doc.doc.permissions;201 // if (!inList(permissions, 'admin') && !inList(permissions, 'editor') && inList(permissions, 'designer')) {202 // var authorizedCollections = req.user._doc.doc.collections;203204 // if (!inList(authorizedCollections, collection)) {205 // //only compare the first folder, which would be > -1 if it were a match.206 // return res.json({207 // status: "error",208 // msg: 'Missing permission for this collection.'209 // });210 // }211 // }212 var filePath = req.dynamicDestination + '/' + req.myFileName; //req.files[0].path; //do not add this because then it cannot find the file path + ".xlsx" 213214 if (!(/master/.test(collection))) {215 let err = "Invalid Collection";216 console.error();217 let vm = {218 messageTitle: 'Error',219 layout: 'simpleLayout',220 serverMessage: err221 };222 console.error("Incorrect collection.");223 res.redirect('/error');224225 }226227 // console.log(data); //masterDB228 if (filePath && collection) {229 //console.log("file path here: " + filePath);230 // mongoXlsx.xlsx2MongoData(filePath, null, function(err, mongoData) {231 // if (err) {232 // console.error(err);233 // res.redirect('/error');234 // }235 // else {236 // console.log('Mongo data:', mongoData);237 // }238 // });239 xlsxj({240 input: filePath, //__dirname + '/sample.xlsx',241 sheet: "Structure",242 output: null // set this to null if you are not using it!!! __dirname + '/output.json'243 }, function(err, result) {244 if (err) {245 console.error(err);246 res.redirect('/error');247 }248 else {249 mapService.removeAll(collection, (err) => {250 if (err) {251 console.error(err);252 res.redirect('/error');253 }254 for (var i = 0; i < result.length; i++) {255 var row = result[i];256 if (!row.hasOwnProperty('rowNumber')) {257 row.rowNumber = i.toString();258 }259 if (row.hasOwnProperty('id') && row.id.length == 0) {260 row.id = i.toString();261 }262 else if (!row.hasOwnProperty('id')) {263 row.id = i.toString();264 }265 removeJunk(row); //for some reason we are getting undefined fields from the excel file. This deletes them266 if (row.hasOwnProperty('id') && row.id.length > 0) {267 var id = row.id;268 var rowNumber = Number(row.rowNumber);269 let doc = {270 id: id,271 rowNumber: rowNumber,272 doc: row273 };274 mapService.addmap(doc, collection, function(err) {275 if (err) {276 console.error(err);277 res.redirect('/error');278 }279 });280 }281282 }283 dbVersion.updateRow(collection, (err, doc) => {284 if (err) {285 //Need to update the version number of this db286 console.log("Error updating dbVersion. Will create a new row for this collection slash db. Err: " + err);287 dbVersion.addRow({288 dbName: collection,289 dbVersion: 1290 }, () => {291 // var vm = {292 // status: 'success',293 // msg: 'success in updateRow for map. id: ' + data.id,294 // dbVersion: 1295 // };296297 // res.status(status).json(vm);298 //next(null);299300 res.status(204).end();301 //res.status(200).end();302 //res.render('import', vm);303 });304305 }306 else {307 /* update dbVersion of this collection */308309310 //doc contains the version number that we are sending back311 // var vm = {312 // dbVersion: doc,313 // status: 'success',314 // msg: 'success in updateRow for dbVersion. collection: ' + collection315 // };316317 //res.status(status).json(vm);318 //next(null);319 res.status(204).end();320 //res.status(200).end();321 //res.render('import', vm);322 }323 });324 });325326 //console.log(result);327 }328 });329330331332 } //if (filePath && collection) 333 });334 }335 else {336 return res.json({337 status: "error",338 msg: 'Invalid path for config.json.'339 });340 }341342343344 res.json({345 status: "Success"346 });347 }348349350351352 } //upload(req, res, function(err) {353 );354355356 } //function(req, res, next) {357);358
...
settings.js
Source:settings.js
...98 return options.configFile === false ? false : (options.configFile || 'cypress.json');99}100exports.configFile = configFile;101function id(projectRoot, options = {}) {102 const file = pathToConfigFile(projectRoot, options);103 return fs_1.fs.readJson(file)104 .then((config) => config.projectId)105 .catch(() => {106 return null;107 });108}109exports.id = id;110function read(projectRoot, options = {}) {111 if (options.configFile === false) {112 return bluebird_1.default.resolve({});113 }114 const file = pathToConfigFile(projectRoot, options);115 const readPromise = /\.json$/.test(file) ? fs_1.fs.readJSON(path_1.default.resolve(projectRoot, file)) : (0, require_async_1.requireAsync)(file, {116 projectRoot,117 loadErrorCode: 'CONFIG_FILE_ERROR',118 });119 return readPromise120 .catch((err) => {121 var _a;122 if (err.type === 'MODULE_NOT_FOUND' || err.code === 'ENOENT') {123 if ((_a = options.args) === null || _a === void 0 ? void 0 : _a.runProject) {124 return bluebird_1.default.reject(errors_1.default.get('CONFIG_FILE_NOT_FOUND', options.configFile, projectRoot));125 }126 return _write(file, {});127 }128 return bluebird_1.default.reject(err);129 })130 .then((configObject = {}) => {131 if (isComponentTesting(options) && 'component' in configObject) {132 configObject = Object.assign(Object.assign({}, configObject), configObject.component);133 }134 if (!isComponentTesting(options) && 'e2e' in configObject) {135 configObject = Object.assign(Object.assign({}, configObject), configObject.e2e);136 }137 debug('resolved configObject', configObject);138 const changed = _applyRewriteRules(configObject);139 // if our object is unchanged140 // then just return it141 if (lodash_1.default.isEqual(configObject, changed)) {142 return configObject;143 }144 // else write the new reduced obj145 return _write(file, changed)146 .then((config) => {147 return config;148 });149 }).catch((err) => {150 debug('an error occurred when reading config', err);151 if (errors_1.default.isCypressErr(err)) {152 throw err;153 }154 return _logReadErr(file, err);155 });156}157exports.read = read;158function readEnv(projectRoot) {159 const file = pathToCypressEnvJson(projectRoot);160 return fs_1.fs.readJson(file)161 .catch((err) => {162 if (err.code === 'ENOENT') {163 return {};164 }165 if (errors_1.default.isCypressErr(err)) {166 throw err;167 }168 return _logReadErr(file, err);169 });170}171exports.readEnv = readEnv;172function write(projectRoot, obj = {}, options = {}) {173 if (options.configFile === false) {174 return bluebird_1.default.resolve({});175 }176 return read(projectRoot, options)177 .then((settings) => {178 lodash_1.default.extend(settings, obj);179 const file = pathToConfigFile(projectRoot, options);180 return _write(file, settings);181 });182}183exports.write = write;184function pathToConfigFile(projectRoot, options = {}) {185 const file = configFile(options);186 return file && _pathToFile(projectRoot, file);187}188exports.pathToConfigFile = pathToConfigFile;189function pathToCypressEnvJson(projectRoot) {190 return _pathToFile(projectRoot, 'cypress.env.json');191}...
import.js
Source:import.js
1/**2 * This code was originally copy and pasted from the file, "importSpread.js",3 * which was written by Larry Maddocks4 * This will allow the designer to upload a file to a folder, if she has the correct credientials.5 * The command, "import" must be proceeded by the path of the folder that the file should be inserted6 * into. I.e., http://gsap.com/my/folder/import7 **/8var express = require('express');9var router = express.Router();10var restrict = require('../auth/restrict');11var multer = require("multer");12//var xlsxj = require("xlsx-to-json");13//var mapService = require('../services/map-service');14//var mongoXlsx = require("mongo-xlsx");15//var dbVersion = require('../services/dbVersion'); //to update row in map dbVersion database16//var hbs = require('hbs');17//hbs.handlebars === require('handlebars');18const fs = require('fs');19const path = require('path');202122var unauthStatic = express.static(path.join(__dirname, '../public'));23var authStatic = path.join(__dirname, '../authorized');242526/* GET home page. */27router.get('/', restrict, function(req, res, next) {28 /**29 * Was getting this error when using a folder in the url as a parameter: "Refused to apply style from" "because its 30 * MIME type ('text/html') is not a supported stylesheet MIME type"31 * Found someone talking about this on stackoverflow, but it was in Spanish, plus the fix is too complicated 32 * for using a folder as a parameter in the url. So I will have user insert folder in a form field.33 **/3435 return res.render('admin/importFile', {36 title: 'Import File',37 layout: 'simpleLayout',38 baseUrl: JSON.stringify(req.baseUrl)39 //,collection:'master_test3'40 });41});424344/**45 * Looks in list to see if key is in there. If so returns true46 **/47function inList(list, key) {48 return list.split(',').indexOf(key) > -149}5051// Set The Storage Engine52var storage = multer.diskStorage({53 destination: function(req, file, cb) {54 if (req.dynamicDestination) {55 cb(null, req.dynamicDestination);56 }57 else cb("Error determining destination of file");5859 },60 filename: function(req, file, cb) {61 cb(null, file.originalname /* + '-' + Date.now() + path.extname(file.originalname) */ );62 }63});6465// Init Upload66const upload = multer({67 limits: { fileSize: 10000000 },68 fileFilter: function(req, file, cb) {69 checkFileTypeAndPermissions(req, file, cb);70 },71 storage: storage72}).single('myFile'); //This tag, "myFile" MUST match the form input name attribute in the importFile.hbs file7374//Get destination folder of where spreadsheet file is sent to75function destination(req, file) {76 var pathToConfigFile = req.params.path;77 //Now get the config.json data to get the collection name78 pathToConfigFile !== undefined ? pathToConfigFile = pathToConfigFile.replace(/slshslash/g, "\/") : pathToConfigFile = null; //instead of a "/" I replaced it with "slshslash" so it doesn't count as another parameter. This line changes it back to the slash ("/")79 if (pathToConfigFile) {80 var dynamicDestination = authStatic + "/" + pathToConfigFile;81 req.pathToConfigFile = pathToConfigFile; //insert this value in req so I can use it later on in checkFileTypeAndPermissions()82 req.dynamicDestination = dynamicDestination; //insert this in req so I can access it later on83 return pathToConfigFile; // successfully found destination. Code was this: cb(null, dynamicDestination);84 }85 else return null; //cb("Error determining destination of file");86}8788// Check File Type and permissions89function checkFileTypeAndPermissions(req, file, cb) {90 // Allowed ext91 const filetypes = /svg|txt|js|css|html|md|json|xlsx|ai|jpeg|jpg|png|gif|scriv/;92 // Check ext93 const extname = filetypes.test(path.extname(file.originalname).toLowerCase());94 if (!extname) {95 return cb('Error: Incorrect file extension!');96 }97 // Check mime98 const mimetype = filetypes.test(file.mimetype);99 if (!mimetype) {100 return cb('Error: Incorrect file mimetype!');101 }102 var pathToConfigFile = destination(req, file); //set destination103104 var permissions = req.user._doc.doc.permissions;105 if (!(inList(permissions, 'admin') || inList(permissions, 'editor') || inList(permissions, 'designer'))) {106 // return res.redirect('/'); // not found107 return cb('Invalid permission.');108109 }110 //now if user is a designer make sure he has permission to write to this folder.111 else if (inList(permissions, 'designer')) {112 var authorizedFolders = req.user._doc.doc.hasOwnProperty("folders") ? req.user._doc.doc.folders : "";113114 if (pathToConfigFile) {115 var mainUrlFolder = req.pathToConfigFile; // pathToConfigFile is just the path before the command where user wants to send file to.116 var firstFolder = mainUrlFolder.split("/").slice(0, 1).toString(); //get first folder (or directory) in the url string117 if (!(authorizedFolders.split(',').indexOf(firstFolder) > -1)) {118 //only compare the first folder, which would be > -1 if it were a match.119 return cb('Folder Not Available. Please check with your administrator for access to folder: ' + firstFolder);120121 }122 else {123 return cb(null, true); //yea! The user is authorized to write file to this folder!!124 }125 }126 else {127 cb("Error determining destination of file");128 }129130 }131132 return cb(null, true); //this is an admin or editor and can write file to any folder.133}134135136//var upload = multer({ dest: './import' });137//router.use(express.static(path.join(__dirname, '../authorized')));138//var upload = multer({ storage : storage}).single('xlsx');139//after posting a spreadsheet file to upload, which will be saved in this folder140//and then inserted into the database. DO NOT CHANGE THIS FROM import!!141router.post('/:path', restrict, function(req, res, next) {142143 upload(req, res, function(err) {144 if (err) {145 res.json({146 status: "error",147 msg: err148 });149 }150 else151 res.json({152 status: "Success"153 });154155156157 } //upload(req, res, function(err) {158 );159});
...
init.js
Source:init.js
1const chalk = require("chalk");2const fs = require("fs");3const inquirer = require("inquirer");4const { spawn } = require("child_process");5const configPath = ".factorialrc.js";6const packages = [7 "css",8 "e2e",9 "html",10 "images",11 "javascript",12 "svg",13 "twig",14 "vue",15];16const scopeName = "@factorial";17const packagePrefix = "stack";18/**19 * @param {string} name20 * @returns {string}21 */22function getNodeModuleName(name) {23 return `${scopeName}/${packagePrefix}-${name}`;24}25/**26 * Installs all selected packages via yarn by spawning a new child process27 *28 * @param {Array} selectedPackages29 * @returns {Promise}30 */31function installPackages(selectedPackages) {32 if (selectedPackages.length === 0) return Promise.resolve();33 return new Promise((resolve) => {34 const process = spawn("yarn", [35 "add",36 "-D",37 ...selectedPackages.map((p) => getNodeModuleName(p)),38 ]);39 process.stdout.on("data", (data) => {40 console.log(data.toString());41 });42 process.stderr.on("data", (data) => {43 console.log(data.toString());44 });45 process.on("error", (error) => {46 console.log(`${chalk.red("\nERROR:")} ${error.message}`);47 });48 process.on("close", (code) => {49 resolve(code === 0);50 });51 });52}53/**54 * Creates a .factorialrc.js with content based on the selected packages55 *56 * @param {Array} selectedPackages57 * @returns {void}58 */59async function createConfig(selectedPackages) {60 let use = "";61 if (selectedPackages.length > 0) {62 use = `63 use: [${selectedPackages64 .map(65 (p) => `66 require("${getNodeModuleName(p)}")`67 )68 .join(",")}69 ]70`;71 }72 await checkIfFileExists(73 configPath,74 `module.exports = {${use}};75`76 );77}78/**79 * @param {Array} selectedPackages80 */81async function createPackageConfigs(selectedPackages) {82 /* eslint-disable no-restricted-syntax */83 for (const pkg of selectedPackages) {84 const { configFiles } = require(`../../../${packagePrefix}-${pkg}`); // eslint-disable-line global-require, import/no-dynamic-require85 if (Array.isArray(configFiles)) {86 for (const { name, content = "" } of configFiles) {87 await checkIfFileExists(name, content); // eslint-disable-line no-await-in-loop88 }89 }90 }91 /* eslint-enable */92}93/**94 * @param {string} pathToConfigFile95 * @param {string} content96 * @returns {Promise}97 */98async function checkIfFileExists(pathToConfigFile, content) {99 try {100 fs.readFileSync(pathToConfigFile, { encoding: "utf8" });101 const { overwriteConfig } = await inquirer.prompt([102 {103 type: "confirm",104 message: `The file ${pathToConfigFile} already exists. Do you want to overwrite it?`,105 name: "overwriteConfig",106 },107 ]);108 if (overwriteConfig) {109 return writeFile(pathToConfigFile, content);110 }111 return true;112 } catch (e) {113 return writeFile(pathToConfigFile, content);114 }115}116/**117 * @param {*} pathToConfigFile118 * @param {string} content119 * @returns {Promise}120 */121function writeFile(pathToConfigFile, content) {122 return new Promise((resolve, reject) => {123 fs.writeFile(124 pathToConfigFile,125 content,126 "utf-8",127 function writeConfigFileCallback(err) {128 if (err) {129 console.error(err);130 reject();131 }132 resolve();133 }134 );135 });136}137module.exports = function init() {138 inquirer139 .prompt([140 {141 type: "checkbox",142 message: "Select the packages which are required for your project",143 name: "packages",144 choices: packages,145 },146 ])147 .then(async (answers) => {148 await createConfig(answers.packages);149 await installPackages(answers.packages);150 await createPackageConfigs(answers.packages);151 process.exit(0);152 })153 .catch(() => process.exit(1));...
index – koopia.js
Source:index – koopia.js
1/**Config functions. @preserve Copyright(c ) 2021 Manuel Lõhmus.*/2'use strict';3var fs = require('fs');4var path = require('path');5var configFileName = 'config-sets.js';6var configPath = path.resolve(process.cwd(), configFileName);7if (!fs.existsSync(configPath)) { init(configPath); }8var config = require(configPath);9function init(pathToConfigFile) {10 pathToConfigFile = path.resolve(pathToConfigFile);11 if (!pathToConfigFile.endsWith('.js')) {12 pathToConfigFile = path.resolve(pathToConfigFile, configFileName);13 }14 if (fs.existsSync(pathToConfigFile)) {15 config = require(pathToConfigFile);16 selectConfig();17 }18 else {19 fs.writeFileSync(pathToConfigFile,20'/** config-sets file */ \n\21module.exports = { \n\22 \n\23 // default settings \n\24 def: { \n\25 isDebug: false \n\26 }, \n\27 // develop settings \n\28 dev: { \n\29 // overwriting \n\30 isDebug: true \n\31 } \n\32}; ',33 { encoding: 'utf8' }34 );35 }36}37function selectConfig() {38 module.exports = assign(39 module.exports,40 config[process.env.NODE_ENV]41 ? config[process.env.NODE_ENV]42 : config['def']43 );44}45function assign(target, source) {46 if (!target && typeof target !== "object") { target = {}; }47 if (Array.isArray(source) && !Array.isArray(target)) { target = []; }48 if (source && typeof source === "object") {49 Object.keys(source).forEach(function (k) {50 if (!source[k] || typeof source[k] !== "object") {51 if (target[k] === undefined) { target[k] = source[k]; }52 }53 else {54 if (typeof target[k] !== "object") { target[k] = {}; }55 target[k] = assign(target[k], source[k]);56 }57 });58 }59 return target;60}61var def = config.def ? config.def : {};62Object.keys(config).forEach(function (k) { if (k !== 'def') { config[k] = assign(config[k], def); } });63selectConfig();64module.exports.init = init;...
mantraconfig.tests.js
Source:mantraconfig.tests.js
1const Path = require("path");2const assert = require("chai").assert;3const fs = require("fs");4require("gimport").initm( process.cwd() );5const MantraConfig = global.gimport("mantraconfig");6describe( 'MantraConfig tests', () => {7 it( '# ExistsConfigFile test', async () => {8 const pathToConfigFile = Path.join(process.cwd(), "test", "testassets", "mantraconfig.json");9 const existsFile = await MantraConfig.ExistsConfigFile(pathToConfigFile);10 assert.isTrue(existsFile);11 });12 it( '# ExistsConfigFile no existing file test', async () => {13 const pathToConfigFile = Path.join(process.cwd(), "test", "testassets", "mantraconfignoexisting.json");14 const existsFile = await MantraConfig.ExistsConfigFile(pathToConfigFile);15 assert.isFalse(existsFile);16 });17 it( '# IsJsonFileValid test', async () => {18 const pathToConfigFile = Path.join(process.cwd(), "test", "testassets", "mantraconfig.json");19 const isJsonValid = await MantraConfig.IsJsonFileValid(pathToConfigFile);20 assert.isTrue(isJsonValid);21 });22 it( '# IsJsonFileValid invalid file test', async () => {23 const pathToConfigFile = Path.join(process.cwd(), "test", "testassets", "mantraconfiginvalid.json");24 const isJsonValid = await MantraConfig.IsJsonFileValid(pathToConfigFile);25 assert.isFalse(isJsonValid);26 });27 it( '# Json expected', () => {28 const pathToConfigFile = Path.join(process.cwd(), "test", "testassets", "mantraconfig.json");29 let config = MantraConfig.LoadConfig( pathToConfigFile );30 assert.isObject( config );31 });32 it( '# CoreComponents is a directory', () => {33 const pathToConfigFile = Path.join(process.cwd(), "test", "testassets", "mantraconfig.json");34 let config = MantraConfig.LoadConfig( pathToConfigFile );35 assert.isTrue( fs.lstatSync(config.CoreComponents).isDirectory() );36 });...
index.js
Source:index.js
1// ***********************************************************2// This example plugins/index.js can be used to load plugins3//4// You can change the location of this file or turn off loading5// the plugins file with the 'pluginsFile' configuration option.6//7// You can read more here:8// https://on.cypress.io/plugins-guide9// ***********************************************************10// This function is called when a project is opened or re-opened (e.g. due to11// the project's config changing)12const fs = require('fs-extra')13const path = require('path')14function getConfigurationByFile (file) {15 //file variable call the qa.json generic name16 const pathToConfigFile = path.resolve('cypress', 'config', `${file}.json`) 17 //directorio en la carpeta cypress, config y el archivo18 if(!fs.existsSync(pathToConfigFile)){19 return {}; //returning empty object if we do not have a file20 }21 return fs.readJson(pathToConfigFile)22}23module.exports = (on, config) => {24 // require('cypress-plugin-retries/lib/plugin')(on)25 const file = config.env.configFile // || 'development' quitamos ya que no tenemos ambiente llamado development dearrollo y solo queremos usar nuestro archivo qa.json26 return getConfigurationByFile(file)...
Using AI Code Generation
1const path = require('path')2const pathToConfigFile = path.resolve('cypress', 'config', 'cypress.json')3const cypress = require('cypress')4cypress.run({5})6{7}8describe('Sample', function() {9 it('Sample Test', function() {10 cy.visit('/')11 })12})
Using AI Code Generation
1const path = require('path')2const configPath = path.resolve('cypress', 'config', 'test.json')3module.exports = (on, config) => {4 on('file:preprocessor', cucumber())5 return Object.assign({}, config, {6 testFiles: '**/*.{feature,features}',7 env: {8 }9 })10}11import { addMatchImageSnapshotCommand } from 'cypress-image-snapshot/command'12import './commands'13addMatchImageSnapshotCommand({14})15import { Given, When, Then } from 'cypress-cucumber-preprocessor/steps'16import { getConfiguration } from '../../config'17const { configPath } = getConfiguration()18Given('I open the {string} page', (page) => {19 cy.visit(page)20})21When('I click on the {string} button', (button) => {22 cy.get(`[data-cy=${button}]`).click()23})24Then('I should see the {string} page', (page) => {25 cy.get(`[data-cy=${page}]`).should('be.visible')26})27{28}29describe('Feature', () => {30 it('Scenario', () => {31 cy.visit('/login')32 cy.get('[data-cy=login]').click()33 cy.get('[data-cy=home]').should('be.visible')34 })35})36describe('Feature', ()
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 cy.visit(Cypress.config('baseUrl'));4 });5});6{7 "env": {8 }9}10describe('test', () => {11 it('test', () => {12 cy.visit(Cypress.env('REACT_APP_API_URL'));13 });14});15{16 "env": {17 }18}19describe('test', () => {20 it('test', () => {21 cy.visit(Cypress.config('baseUrl'));22 });23});24{25 "env": {26 }27}28describe('test', () => {29 it('test', () => {30 cy.visit(Cypress.env('REACT_APP_API_URL'));31 });32});33{34 "env": {35 }36}37describe('test', () => {38 it('test', () => {39 cy.visit(Cypress.config('baseUrl'));40 });41});42{43 "env": {44 }45}46describe('test', () =>
Using AI Code Generation
1const path = require('path')2const cypress = require('cypress')3const configPath = path.resolve(__dirname, 'cypress.json')4cypress.run({5})6{7}8describe('My First Test', function() {9 it('Visits the Kitchen Sink', function() {10 cy.visit('/')11 })12})
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!!