Best JavaScript code snippet using cypress
app.js
Source:app.js
...34 if (prj) return prj;35 this.navigate('', {trigger: true});36 },37 _getProjectLanguage: function (project_id, language) {38 var prj = this._getProject(project_id),39 lang = yati.app.get('languages').get(language);40 if (prj) {41 if (!lang || !yati.app.get('user').hasLanguage(language)) {42 this.navigate(this.link('project', project_id), {trigger: true});43 } else {44 return [prj, lang];45 }46 }47 },48 _getProjectUser: function (project_id, user_id) {49 var prj = this._getProject(project_id),50 user = prj.get('users').get(user_id);51 if (!user) {52 this.navigate(this.link('project_users', project_id), {trigger: true})53 }54 return [prj, user];55 },56 project: afterInit(function (project_id) {57 var prj = this._getProject(project_id);58 if (prj) {59 //if (prj.get('targetlanguages'))60 // @TODO check which languages are present and which user has61 var langs = prj.getLanguagesForUser(yati.app.get('user'));62 if (langs.length == 1 && !yati.app.get('user').get('is_staff')) {63 this.navigate(this.link('language', project_id, langs[0]), {trigger: true});64 return;65 }66 yati.app.set({view: 'project', project: prj});67 }68 }),69 project_users: afterInit(function (project_id) {70 var prj = this._getProject(project_id);71 if (prj) {72 yati.app.set({view: 'project_users', project: prj});73 }74 }),75 project_users_add: afterInit(function (project_id) {76 var prj = this._getProject(project_id);77 if (prj) {78 //prj.set('invite_user', new yati.models.User);79 //console.log('NEW USER', prj.get('invite_user').attributes);80 yati.app.set({view: 'project_users_add', project: prj});81 }82 }),83 project_users_action: afterInit(function (project_id, user_id, action) {84 var prjuser = this._getProjectUser(project_id, user_id);85 if (prjuser) {86 yati.app.set({view: 'project_users_' + action, project: prj, selected_user: user});87 }88 }),89 /*sourceAdd: afterInit(function (project_id) {90 var prj = this._getProject(project_id);91 if (prj) {92 yati.app.set({view: 'sourceAdd', project: prj});93 }94 }),*/95 language: afterInit(function (project_id, language) {96 var prjlang = this._getProjectLanguage(project_id, language);97 if (prjlang) {98 // check if only one module, redirect there99 if (prjlang[0].get('modules').length === 1 && !yati.app.get('user').get('is_staff')) {100 this.navigate(this.link('module', project_id, language, prjlang[0].get('modules').first().get('id')),101 {trigger: true, replace: true});102 return;103 }104 yati.app.set({view: 'language', project: prjlang[0], language: prjlang[1]});...
project_static.js
Source:project_static.js
...54function _mergeState(clientProject, state) {55 return lodash_1.default.extend({}, clientProject, { state });56}57exports._mergeState = _mergeState;58function _getProject(clientProject, authToken) {59 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {60 debug('get project from api', clientProject.id, clientProject.path);61 try {62 const project = yield api_1.default.getProject(clientProject.id, authToken);63 debug('got project from api');64 return _mergeDetails(clientProject, project);65 }66 catch (err) {67 debug('failed to get project from api', err.statusCode);68 switch (err.statusCode) {69 case 404:70 // project doesn't exist71 return _mergeState(clientProject, 'INVALID');72 case 403:73 // project exists, but user isn't authorized for it74 return _mergeState(clientProject, 'UNAUTHORIZED');75 default:76 throw err;77 }78 }79 });80}81exports._getProject = _getProject;82function getProjectStatuses(clientProjects = []) {83 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {84 debug(`get project statuses for ${clientProjects.length} projects`);85 const authToken = yield user_1.default.ensureAuthToken();86 debug('got auth token: %o', { authToken: keys_1.default.hide(authToken) });87 const projects = ((yield api_1.default.getProjects(authToken)) || []);88 debug(`got ${projects.length} projects`);89 const projectsIndex = lodash_1.default.keyBy(projects, 'id');90 return Promise.all(lodash_1.default.map(clientProjects, (clientProject) => {91 debug('looking at', clientProject.path);92 // not a CI project, just mark as valid and return93 if (!clientProject.id) {94 debug('no project id');95 return _mergeState(clientProject, 'VALID');96 }97 const project = projectsIndex[clientProject.id];98 if (project) {99 debug('found matching:', project);100 // merge in details for matching project101 return _mergeDetails(clientProject, project);102 }103 debug('did not find matching:', project);104 // project has id, but no matching project found105 // check if it doesn't exist or if user isn't authorized106 return _getProject(clientProject, authToken);107 }));108 });109}110exports.getProjectStatuses = getProjectStatuses;111function getProjectStatus(clientProject) {112 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {113 debug('get project status for client id %s at path %s', clientProject.id, clientProject.path);114 if (!clientProject.id) {115 debug('no project id');116 return Promise.resolve(_mergeState(clientProject, 'VALID'));117 }118 const authToken = yield user_1.default.ensureAuthToken();119 debug('got auth token: %o', { authToken: keys_1.default.hide(authToken) });120 return _getProject(clientProject, authToken);121 });122}123exports.getProjectStatus = getProjectStatus;124function remove(path) {125 return cache_1.default.removeProject(path);126}127exports.remove = remove;128function add(path, options) {129 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {130 // don't cache a project if a non-default configFile is set131 // https://git.io/JeGyF132 if (settings.configFile(options) !== 'cypress.json') {133 return Promise.resolve({ path });134 }...
controller.project.js
Source:controller.project.js
...70 });71 return newProject72 .save()73 .then(async (project) => {74 const [isSuccesful, message] = await _getProject(project._id);75 return isSuccesful76 ? res.status(201).json(message)77 : res.status(400).json(message);78 })79 .catch((err) => res.status(400).json("Error" + err));80 },81 /**82 * gets all tasks that is managed by a user by ID from the token83 *84 * @param {express.Request} req85 * @param {express.Response} res86 * @returns All tasks owned by the user87 */88 getProjectByUserId: (req, res) => {89 const userID = decode(req.headers.authorization).id;90 return Project.find({ projectOwner: userID })91 .populate("timeline")92 .populate("projectHistory")93 .populate({94 path: "projectHistory",95 populate: {96 path: "userList",97 },98 })99 .populate({100 path: "projectHistory",101 populate: {102 path: "timeline",103 },104 })105 .populate("projectOwner", [106 "badgeID",107 "firstName",108 "lastName",109 "jobTitle",110 "additionalInfo",111 "emailAddress",112 ])113 .populate("task")114 .sort({ createdAt: -1 })115 .exec(function (err, results) {116 if (err) {117 res.status(400).json({ error: "Error in getting all projects." });118 }119 res.status(200).json(results);120 });121 },122 updateProject: async (req, res) => {123 const [isSuccesful, message] = await _updateProject(req.body);124 return isSuccesful125 ? res.status(201).json(message)126 : res.status(400).json(message);127 },128 /**129 * gets a project by ID from the database130 *131 * @param {express.Request} req132 * @param {express.Response} res133 * @returns a single project from database134 */135 getProject: async (req, res) => {136 // check if the incoming id is valid mongoose id137 if (!req.params.id.match(/^[0-9a-fA-F]{24}$/)) {138 return res.status(400).json("Invalid route/mongoose ID!");139 }140 const [isSuccesful, message] = await _getProject(req.params.id);141 return isSuccesful142 ? res.status(201).json(message)143 : res.status(400).json(message);144 },145 /**146 * computes the current total progress of a project147 *148 * @param {express.Request} req149 * @param {express.Response} res150 * @returns total progress of project151 */152};153// all utility methods starts here154/**155 * gets a single task from db by ID156 *157 * @param {String.ID of Task object} id158 * @returns a single task159 */160const _getTask = (id) => {161 return Task.findById(id)162 .populate("task")163 .populate("timeline")164 .sort({ createdAt: -1 })165 .then((results) => {166 return [true, results];167 })168 .catch((err) => {169 return [false, { error: err }];170 });171};172/**173 * this is a helper method called when a project is updated174 * 175 * @param {Object} project 176 * @returns [boolean, Object]177 */178const _updateProject = async (project) => {179 const [successful, oldProject] = await _getProject(project._id);180 let remarks = "";181 let tempProject = {};182 let history = {};183 if (project.projectOwner) {184 history["userList"] = oldProject.projectOwner;185 tempProject["projectOwner"] = project.projectOwner;186 remarks += "Project owner was updated. \n";187 }188 if (project.projectName) {189 tempProject["projectName"] = project.projectName;190 remarks += "Project name was altered. \n";191 }192 if (project.task) {193 history["task"] = oldProject.task;...
menubar.controller.js
Source:menubar.controller.js
...93 Mousetrap.unbind('ctrl+a', onSelectAll);94 Mousetrap.unbind('ctrl+shift+a', onDeselectAll);95 Mousetrap.unbind('ctrl+i', onInvertSelection);96 }97 function _getProject() {98 return $window.editor.project.get();99 }100 function _getTree() {101 var project = $window.editor.project.get();102 return project.trees.getSelected();103 }104 function onExportProjectJson() {105 $state.go('editor.export', {type:'project', format:'json'});106 return false;107 }108 function onExportTreeJson() {109 $state.go('editor.export', {type:'tree', format:'json'});110 return false;111 }112 function onExportNodesJson() {113 $state.go('editor.export', {type:'nodes', format:'json'});114 return false;115 }116 function onImportProjectJson() {117 $state.go('editor.import', {type:'project', format:'json'});118 return false;119 }120 function onImportTreeJson() {121 $state.go('editor.import', {type:'tree', format:'json'});122 return false;123 }124 function onImportNodesJson() {125 $state.go('editor.import', {type:'nodes', format:'json'});126 return false;127 }128 function onCloseProject() {129 function doClose() {130 projectModel.closeProject();131 $state.go('dash.projects');132 }133 if ($window.editor.isDirty()) {134 dialogService135 .confirm(136 'Leave without saving?', 137 'If you proceed you will lose all unsaved modifications.', 138 null)139 .then(doClose);140 } else {141 doClose();142 }143 return false;144 }145 function onSaveProject() {146 projectModel147 .saveProject()148 .then(function() {149 notificationService.success(150 'Project saved',151 'The project has been saved'152 );153 }, function() {154 notificationService.error(155 'Error',156 'Project couldn\'t be saved'157 );158 });159 return false;160 }161 function onNewTree() {162 var project = _getProject();163 project.trees.add();164 return false;165 }166 function onUndo() {167 var project = _getProject();168 project.history.undo();169 return false;170 }171 function onRedo() {172 var project = _getProject();173 project.history.redo();174 return false;175 }176 function onCopy() {177 var tree = _getTree();178 tree.edit.copy(); 179 return false;180 }181 function onCut() {182 var tree = _getTree();183 tree.edit.cut();184 return false;185 }186 function onPaste() {...
Stream.js
Source:Stream.js
...71 //console.debug("iterating stream", item, key);72 if (item.verb !== "SAVE"){73 if (key === 0){74 username = item.actor.id;75 project = self._getProject(item);76 //this is the first item, need to create a new entry77 entry = new Entry({showProject: self.showProject, username: username, contact: db.contactFullName(username), project: project.id, projectName: project.name});78 entry.addChild(self._getChild(item));79 hasEntries = true;80 //most entries are about something that happened in a project, so need to track the project81 //if there was only one entry, then make sure it get's added82 if (stream.length === 1){83 self.addChild(entry);84 hasEntries = false;85 }86 } else if (key > 0){87 //if the username and project are the same, then we need to add a child to the entry88 if (item.actor.id === username && project.id === self._getProject(item).id){89 entry.addChild(self._getChild(item));90 hasEntries = true;91 } else {92 //otherwise add the existing entry to the stream93 self.addChild(entry);94 username = item.actor.id;95 project = self._getProject(item);96 //and then start a new entry and add a child to it97 entry = new Entry({showProject: self.showProject, username:username, contact: db.contactFullName(username), project: project.id, projectName: project.name});98 entry.addChild(self._getChild(item));99 last = true;100 }101 }102 }103 });104 105 //make sure the last one gets added106 if (last){107 self.addChild(entry);108 hasEntries = false;109 }110 111 //it might be that there is only one entry created but there are more than one stream items112 //in that case, it won't get added (usually when it's a task stream) so check here113 /*114 if (self.getChildren().length === 0 && self.stream.length > 0){115 self.addChild(entry);116 }117 */118 //console.debug("hasEntries", hasEntries);119 if (hasEntries){120 self.addChild(entry);121 }122 },123 124 _getProject: function(item){125 //most entries are about something that happened in a project, so need to track the project126 try {127 var project;128 if (!item.target){129 project = item.object;130 } else {131 project = item.target;132 }133 134 if (item.target && item.target.type !== "PROJECT"){135 //but of the target isn't a project, it migth be that this is something that 136 //happend to the project (project is object), so track that137 project = item.object;138 if (item.object.type !== "PROJECT"){139 140 //just in case something strange happens, just reset the project141 project = {project: "", type: "", name: ""};142 }143 }144 return project;145 } catch (err){146 console.debug("ERROR getting project in stream", item);147 return {project: "", type: "", name: ""};148 }149 150 },151 152 _getChild: function(item){153 var child;154 155 var self = this;156 157 if (item.object.type !== "NOTE" && item.object.type !== "COMMENT"){158 159 item.allowOptions = self.showProject;160 item.project = self._getProject(item);161 child = new Activity(item);162 163 } else {164 165 166 167 var message = item.body,168 created = item.created;169 170 child = new Message({message: message, created: created, project: self._getProject(item), allowOptions: self.showProject});171 }172 173 return child;174 },175 176 destroy: function(){177 this.destroyDescendants();178 this.inherited(arguments);179 this.stream = [];180 //console.debug("stream destroyed");181 },182 183 baseClass: "stream"184 });...
GCloudStorage.js
Source:GCloudStorage.js
...20 * @returns {promise}21 */22GCloudStorage.prototype.upload = function (options) {23 var defer = Q.defer();24 var bucket = this._getProject().storage().bucket(options.bucket);25 var file = bucket.file(options.key);26 fs.createReadStream(options.body)27 .pipe(file.createWriteStream())28 .on('error', function (error) {29 defer.reject(error);30 })31 .on('end', function () {32 defer.resolve();33 });34 return defer.promise;35};36/**37 * Download file from GCloud Storage38 * @param {Object} options Object with `bucket` and `key` properties39 * @returns {promise}40 */41GCloudStorage.prototype.get = function (options) {42 var defer = Q.defer();43 var bucket = this._getProject().storage().bucket(options.bucket);44 var file = bucket.file(options.key);45 var buffer = '';46 file.createReadStream()47 .on('data', function (data) {48 buffer += data;49 })50 .on('end', function () {51 defer.resolve(new Buffer(buffer));52 })53 .on('error', function (error) {54 defer.reject(error);55 });56 return defer.promise;57};58/**59 * Remove file from GCloud Storage60 * @param {Object} options Options with `bucket` and `key` properties61 * @returns {promise}62 */63GCloudStorage.prototype.remove = function (options) {64 var defer = Q.defer();65 var bucket = this._getProject().storage().bucket(options.bucket);66 var file = bucket.file(options.key);67 file.delete(function (error) {68 if (error) {69 defer.reject(error);70 } else {71 defer.resolve();72 }73 });74 return defer.promise;75};76/**77 * Get gcloud project78 * @returns {*}79 * @private...
routes.js
Source:routes.js
1var db = require('./db')2module.exports = {3 _getProjects: _getProjects,4 getProjects: _getProjects.bind(null, db),5 _getProject: _getProject,6 getProject: _getProject.bind(null, db),7 _addProject: _addProject,8 addProject: _addProject.bind(null, db),9 _updateProject: _updateProject,10 updateProject: _updateProject.bind(null, db)11}12function _getProjects (db, req, res) {13 db.getProjects()14 .then(function (projects) {15 res.json(projects)16 })17 .catch(function (err) {18 res.send(err.message).status(500)19 })20}21function _getProject (db, req, res) {22 var projectId = Number(req.params.id)23 if (isNaN(projectId)) {24 res.send('invalid id').status(404)25 } else {26 db.getProject(projectId)27 .then(function (project) {28 res.json(project)29 })30 .catch(function (err) {31 res.send(err.message).status(500)32 })33 }34}35function _addProject (db, req, res) {36 var project = {37 title: req.body.title,38 teamName: req.body.teamName,39 description: req.body.description,40 date: req.body.date,41 repoUrl: req.body.repoUrl,42 appUrl: req.body.appUrl,43 teamMembers: req.body.teamMembers,44 photoUrl: req.body.photoUrl,45 photoCaption: req.body.photoCaption46 }47 db.addProject(project)48 .then(function () {49 res.json(project)50 })51 .catch(function (err) {52 res.send(err.message).status(500)53 })54}55function _updateProject (db, req, res) {56 var project = {57 id: req.body.id,58 title: req.body.title,59 teamName: req.body.teamName,60 description: req.body.description,61 date: req.body.date,62 repoUrl: req.body.repoUrl,63 appUrl: req.body.appUrl,64 teamMembers: req.body.teamMembers,65 photoUrl: req.body.photoUrl,66 photoCaption: req.body.photoCaption67 }68 db.updateProject(project)69 .then(function () {70 res.json(project)71 })72 .catch(function (err) {73 res.send(err.message).status(500)74 })...
projectAPIService.js
Source:projectAPIService.js
1angular.module("UpTeam").factory("projectAPI", function($http, config){2 var _getProjects = function(){3 return $http.get(config.baseUrl + "Project/")4 };5 var _getProject = function(id){6 console.log($http.get(config.baseUrl + "Project/?id=" + id));7 };8 var _setProject = function(project){9 return $http.post(config.baseUrl + "Project/?name='" + project.name 10 + "'&team=" + project.team 11 +"&estimatedDeadline="+ project.estimatedDeadline12 + "&description='" + project.description 13 + "'")14 };15 16 return {17 getProjects: _getProjects,18 getProject: _getProject,19 setProject: _setProject20 };...
Using AI Code Generation
1Cypress.Commands.add('_getProject', (projectName) => {2 .request({3 qs: {4 where: {5 },6 },7 })8 .its('body')9 .then((projects) => {10 return projects[0];11 });12});13describe('Test', () => {14 before(() => {15 cy._getProject('Project Name').then((project) => {16 cy.wrap(project).as('project');17 });18 });19 it('test', () => {20 cy.get('@project').then((project) => {21 cy.log(project.id);22 });23 });24});25describe('Test', () => {26 before(() => {27 cy._getProject('Project Name').then((project) => {28 cy.wrap(project).as('project');29 });30 });31 it('test', () => {32 cy.get('@project').then((project) => {33 cy.log(project.id);34 });35 });36});37describe('Test', () => {38 before(() => {39 cy._getProject('Project Name').then((project) => {40 cy.wrap(project).as('project');41 });42 });43 it('test', () => {44 cy.get('@project').then((project) => {45 cy.log(project.id);46 });47 });48});49describe('Test', () => {50 before(() => {51 cy._getProject('Project Name').then((project) => {52 cy.wrap(project).as('project');53 });54 });55 it('test', () => {56 cy.get('@project').then((project) => {57 cy.log(project.id);58 });59 });60});61describe('Test', () => {62 before(() => {63 cy._getProject('Project Name').then((project) => {64 cy.wrap(project).as('project');65 });66 });67 it('test', () => {
Using AI Code Generation
1Cypress.Commands.add('_getProject', (projectName) => {2 cy.get('app-projects').find('mat-card').each(($el, index, $list) => {3 cy.wrap($el).find('mat-card-title').then(($title) => {4 if ($title.text() === projectName) {5 cy.wrap($el).find('button').click();6 }7 });8 });9});10Cypress.Commands.add('_getProject', (projectName) => {11 cy.get('app-projects').find('mat-card').each(($el, index, $list) => {12 cy.wrap($el).find('mat-card-title').then(($title) => {13 if ($title.text() === projectName) {14 cy.wrap($el).find('button').click();15 }16 });17 });18});19Cypress.Commands.add('_getProject', (projectName) => {20 cy.get('app-projects').find('mat-card').each(($el, index, $list) => {21 cy.wrap($el).find('mat-card-title').then(($title) => {22 if ($title.text() === projectName) {23 cy.wrap($el).find('button').click();24 }25 });26 });27});28Cypress.Commands.add('_getProject', (projectName) => {29 cy.get('app-projects').find('mat-card').each(($el, index, $list) => {30 cy.wrap($el).find('mat-card-title').then(($title) => {31 if ($title.text() === projectName) {32 cy.wrap($el).find('button').click();33 }34 });35 });36});37Cypress.Commands.add('_getProject', (projectName) => {38 cy.get('app-projects').find('mat-card').each(($el, index, $list) => {39 cy.wrap($el).find('mat-card-title').then(($title) => {40 if ($title.text() === projectName) {41 cy.wrap($el).find('button').click();42 }43 });44 });45});
Using AI Code Generation
1describe('Testing', function() {2 it('Test', function() {3 cy.get('.home-list li:first').click()4 cy.get('.query-btn').click()5 cy.get('.query-list')6 .should('have.class', 'big')7 .and('contain', 'green')8 .find('li')9 .should('have.length', 3)10 })11})
Using AI Code Generation
1cy._getProject().then((projectRoot: string) => {2 console.log(projectRoot);3});4const fs = require('fs-extra');5const path = require('path');6module.exports = (on, config) => {7 on('task', {8 _getProject() {9 return config.projectRoot;10 },11 });12};
Using AI Code Generation
1import { _getProject } from '@cypress/vue'2Cypress.Commands.add('getProject', () => _getProject())3it('tests', () => {4 cy.getProject().then((project) => {5 })6})7See the [examples](
Using AI Code Generation
1Cypress._getProject = () => {2 const root = Cypress.config('projectRoot')3}4Cypress._getProject = () => {5 const root = Cypress.config('projectRoot')6}7Cypress._getProject = () => {8 const root = Cypress.config('projectRoot')9}10Cypress._getProject = () => {11 const root = Cypress.config('projectRoot')12}13Cypress._getProject = () => {14 const root = Cypress.config('projectRoot')15}16Cypress._getProject = () => {17 const root = Cypress.config('projectRoot')18}19Cypress._getProject = () => {20 const root = Cypress.config('projectRoot')21}22Cypress._getProject = () => {23 const root = Cypress.config('projectRoot')24}25Cypress._getProject = () => {
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!!