How to use this.determineIsNewProject method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

project.js

Source: project.js Github

copy
1(function() {
2  var Automation, EE, Project, Promise, R, Reporter, Server, Watchers, _, api, browsers, cache, check, commitInfo, config, cwd, debug, errors, fs, la, localCwd, logger, multipleForwardSlashesRe, path, plugins, preprocessor, savedState, scaffold, scaffoldDebug, settings, specsUtil, user,
3    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
4    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
5    hasProp = {}.hasOwnProperty;
6
7  _ = require("lodash");
8
9  R = require("ramda");
10
11  EE = require("events");
12
13  path = require("path");
14
15  Promise = require("bluebird");
16
17  commitInfo = require("@cypress/commit-info");
18
19  la = require("lazy-ass");
20
21  check = require("check-more-types");
22
23  scaffoldDebug = require("debug")("cypress:server:scaffold");
24
25  debug = require("debug")("cypress:server:project");
26
27  cwd = require("./cwd");
28
29  api = require("./api");
30
31  user = require("./user");
32
33  cache = require("./cache");
34
35  config = require("./config");
36
37  logger = require("./logger");
38
39  errors = require("./errors");
40
41  Server = require("./server");
42
43  plugins = require("./plugins");
44
45  scaffold = require("./scaffold");
46
47  Watchers = require("./watchers");
48
49  Reporter = require("./reporter");
50
51  browsers = require("./browsers");
52
53  savedState = require("./saved_state");
54
55  Automation = require("./automation");
56
57  preprocessor = require("./plugins/preprocessor");
58
59  fs = require("./util/fs");
60
61  settings = require("./util/settings");
62
63  specsUtil = require("./util/specs");
64
65  localCwd = cwd();
66
67  multipleForwardSlashesRe = /[^:\/\/](\/{2,})/g;
68
69  Project = (function(superClass) {
70    extend(Project, superClass);
71
72    function Project(projectRoot) {
73      this.getConfig = bind(this.getConfig, this);
74      if (!(this instanceof Project)) {
75        return new Project(projectRoot);
76      }
77      if (!projectRoot) {
78        throw new Error("Instantiating lib/project requires a projectRoot!");
79      }
80      if (!check.unemptyString(projectRoot)) {
81        throw new Error("Expected project root path, not " + projectRoot);
82      }
83      this.projectRoot = path.resolve(projectRoot);
84      this.watchers = Watchers();
85      this.cfg = null;
86      this.spec = null;
87      this.browser = null;
88      this.server = null;
89      this.memoryCheck = null;
90      this.automation = null;
91      debug("Project created %s", this.projectRoot);
92    }
93
94    Project.prototype.open = function(options) {
95      var logMemory;
96      if (options == null) {
97        options = {};
98      }
99      debug("opening project instance %s", this.projectRoot);
100      this.server = Server();
101      _.defaults(options, {
102        report: false,
103        onFocusTests: function() {},
104        onError: function() {},
105        onSettingsChanged: false
106      });
107      if (process.env.CYPRESS_MEMORY) {
108        logMemory = function() {
109          return console.log("memory info", process.memoryUsage());
110        };
111        this.memoryCheck = setInterval(logMemory, 1000);
112      }
113      return this.getConfig(options).tap((function(_this) {
114        return function(cfg) {
115          process.chdir(_this.projectRoot);
116          if (cfg.pluginsFile) {
117            return scaffold.plugins(path.dirname(cfg.pluginsFile), cfg);
118          }
119        };
120      })(this)).then((function(_this) {
121        return function(cfg) {
122          return _this._initPlugins(cfg, options).then(function(modifiedCfg) {
123            debug("plugin config yielded:", modifiedCfg);
124            return config.updateWithPluginValues(cfg, modifiedCfg);
125          });
126        };
127      })(this)).then((function(_this) {
128        return function(cfg) {
129          return _this.server.open(cfg, _this).spread(function(port, warning) {
130            if (!cfg.port) {
131              cfg.port = port;
132              _.extend(cfg, config.setUrls(cfg));
133            }
134            _this.cfg = cfg;
135            debug("project config: %o", _.omit(cfg, "resolved"));
136            if (warning) {
137              options.onWarning(warning);
138            }
139            options.onSavedStateChanged = function(state) {
140              return _this.saveState(state);
141            };
142            return Promise.join(_this.watchSettingsAndStartWebsockets(options, cfg), _this.scaffold(cfg)).then(function() {
143              return Promise.join(_this.checkSupportFile(cfg), _this.watchPluginsFile(cfg, options));
144            });
145          });
146        };
147      })(this))["return"](this);
148    };
149
150    Project.prototype._initPlugins = function(cfg, options) {
151      cfg = config.whitelist(cfg);
152      return plugins.init(cfg, {
153        onError: function(err) {
154          debug('got plugins error', err.stack);
155          browsers.close();
156          return options.onError(err);
157        }
158      });
159    };
160
161    Project.prototype.getRuns = function() {
162      return Promise.all([this.getProjectId(), user.ensureAuthToken()]).spread(function(projectId, authToken) {
163        return api.getProjectRuns(projectId, authToken);
164      });
165    };
166
167    Project.prototype.reset = function() {
168      debug("resetting project instance %s", this.projectRoot);
169      this.spec = this.browser = null;
170      return Promise["try"]((function(_this) {
171        return function() {
172          var ref, ref1;
173          if ((ref = _this.automation) != null) {
174            ref.reset();
175          }
176          return (ref1 = _this.server) != null ? ref1.reset() : void 0;
177        };
178      })(this));
179    };
180
181    Project.prototype.close = function() {
182      var ref, ref1;
183      debug("closing project instance %s", this.projectRoot);
184      if (this.memoryCheck) {
185        clearInterval(this.memoryCheck);
186      }
187      this.cfg = this.spec = this.browser = null;
188      return Promise.join((ref = this.server) != null ? ref.close() : void 0, (ref1 = this.watchers) != null ? ref1.close() : void 0, preprocessor.close()).then(function() {
189        return process.chdir(localCwd);
190      });
191    };
192
193    Project.prototype.checkSupportFile = function(cfg) {
194      var supportFile;
195      if (supportFile = cfg.supportFile) {
196        return fs.pathExists(supportFile).then((function(_this) {
197          return function(found) {
198            if (!found) {
199              return errors["throw"]("SUPPORT_FILE_NOT_FOUND", supportFile);
200            }
201          };
202        })(this));
203      }
204    };
205
206    Project.prototype.watchPluginsFile = function(cfg, options) {
207      debug("attempt watch plugins file: " + cfg.pluginsFile);
208      if (!cfg.pluginsFile) {
209        return Promise.resolve();
210      }
211      return fs.pathExists(cfg.pluginsFile).then((function(_this) {
212        return function(found) {
213          debug("plugins file found? " + found);
214          if (!found) {
215            return;
216          }
217          debug("watch plugins file");
218          return _this.watchers.watchTree(cfg.pluginsFile, {
219            onChange: function() {
220              debug("plugins file changed");
221              return _this._initPlugins(cfg, options)["catch"](function(err) {
222                return options.onError(err);
223              });
224            }
225          });
226        };
227      })(this));
228    };
229
230    Project.prototype.watchSettings = function(onSettingsChanged) {
231      var obj;
232      if (!onSettingsChanged) {
233        return;
234      }
235      debug("watch settings files");
236      obj = {
237        onChange: (function(_this) {
238          return function(filePath, stats) {
239            if (_this.generatedProjectIdTimestamp && (new Date - _this.generatedProjectIdTimestamp) < 1000) {
240              return;
241            }
242            return onSettingsChanged.call(_this);
243          };
244        })(this)
245      };
246      this.watchers.watch(settings.pathToCypressJson(this.projectRoot), obj);
247      return this.watchers.watch(settings.pathToCypressEnvJson(this.projectRoot), obj);
248    };
249
250    Project.prototype.watchSettingsAndStartWebsockets = function(options, cfg) {
251      var err, errorMsg, paths, projectRoot, reporter;
252      if (options == null) {
253        options = {};
254      }
255      if (cfg == null) {
256        cfg = {};
257      }
258      this.watchSettings(options.onSettingsChanged);
259      reporter = cfg.reporter, projectRoot = cfg.projectRoot;
260      if (cfg.report) {
261        try {
262          Reporter.loadReporter(reporter, projectRoot);
263        } catch (error) {
264          err = error;
265          paths = Reporter.getSearchPathsForReporter(reporter, projectRoot);
266          errorMsg = err.code === "MODULE_NOT_FOUND" ? err.message : err.stack;
267          errors["throw"]("INVALID_REPORTER_NAME", {
268            paths: paths,
269            error: errorMsg,
270            name: reporter
271          });
272        }
273        reporter = Reporter.create(reporter, cfg.reporterOptions, projectRoot);
274      }
275      this.automation = Automation.create(cfg.namespace, cfg.socketIoCookie, cfg.screenshotsFolder);
276      return this.server.startWebsockets(this.automation, cfg, {
277        onReloadBrowser: options.onReloadBrowser,
278        onFocusTests: options.onFocusTests,
279        onSpecChanged: options.onSpecChanged,
280        onSavedStateChanged: options.onSavedStateChanged,
281        onConnect: (function(_this) {
282          return function(id) {
283            return _this.emit("socket:connected", id);
284          };
285        })(this),
286        onSetRunnables: function(runnables) {
287          debug("received runnables %o", runnables);
288          return reporter != null ? reporter.setRunnables(runnables) : void 0;
289        },
290        onMocha: (function(_this) {
291          return function(event, runnable) {
292            debug("onMocha", event);
293            if (!reporter) {
294              return;
295            }
296            reporter.emit(event, runnable);
297            if (event === "end") {
298              return Promise.all([reporter != null ? reporter.end() : void 0, _this.server.end()]).spread(function(stats) {
299                if (stats == null) {
300                  stats = {};
301                }
302                return _this.emit("end", stats);
303              });
304            }
305          };
306        })(this)
307      });
308    };
309
310    Project.prototype.changeToUrl = function(url) {
311      return this.server.changeToUrl(url);
312    };
313
314    Project.prototype.setCurrentSpecAndBrowser = function(spec, browser) {
315      this.spec = spec;
316      return this.browser = browser;
317    };
318
319    Project.prototype.getCurrentSpecAndBrowser = function() {
320      return _.pick(this, "spec", "browser");
321    };
322
323    Project.prototype.setBrowsers = function(browsers) {
324      if (browsers == null) {
325        browsers = [];
326      }
327      return this.getConfig().then(function(cfg) {
328        return cfg.browsers = browsers;
329      });
330    };
331
332    Project.prototype.getAutomation = function() {
333      return this.automation;
334    };
335
336    Project.prototype.determineIsNewProject = function(folder) {
337      return scaffold.isNewProject(folder);
338    };
339
340    Project.prototype.getConfig = function(options) {
341      var setNewProject;
342      if (options == null) {
343        options = {};
344      }
345      if (this.cfg) {
346        return Promise.resolve(this.cfg);
347      }
348      setNewProject = (function(_this) {
349        return function(cfg) {
350          if (cfg.isTextTerminal) {
351            return;
352          }
353          if (!cfg.integrationFolder) {
354            throw new Error("Missing integration folder");
355          }
356          return _this.determineIsNewProject(cfg.integrationFolder).then(function(untouchedScaffold) {
357            var userHasSeenOnBoarding;
358            userHasSeenOnBoarding = _.get(cfg, 'state.showedOnBoardingModal', false);
359            scaffoldDebug("untouched scaffold " + untouchedScaffold + " modal closed " + userHasSeenOnBoarding);
360            return cfg.isNewProject = untouchedScaffold && !userHasSeenOnBoarding;
361          });
362        };
363      })(this);
364      return config.get(this.projectRoot, options).then((function(_this) {
365        return function(cfg) {
366          return _this._setSavedState(cfg);
367        };
368      })(this)).tap(setNewProject);
369    };
370
371    Project.prototype.saveState = function(stateChanges) {
372      var newState;
373      if (stateChanges == null) {
374        stateChanges = {};
375      }
376      if (!this.cfg) {
377        throw new Error("Missing project config");
378      }
379      if (!this.projectRoot) {
380        throw new Error("Missing project root");
381      }
382      newState = _.merge({}, this.cfg.state, stateChanges);
383      return savedState(this.projectRoot, this.cfg.isTextTerminal).then(function(state) {
384        return state.set(newState);
385      }).then((function(_this) {
386        return function() {
387          _this.cfg.state = newState;
388          return newState;
389        };
390      })(this));
391    };
392
393    Project.prototype._setSavedState = function(cfg) {
394      debug("get saved state");
395      return savedState(this.projectRoot, cfg.isTextTerminal).then(function(state) {
396        return state.get();
397      }).then(function(state) {
398        cfg.state = state;
399        return cfg;
400      });
401    };
402
403    Project.prototype.getSpecUrl = function(absoluteSpecPath) {
404      return this.getConfig().then((function(_this) {
405        return function(cfg) {
406          var prefixedPath;
407          if (!absoluteSpecPath || (absoluteSpecPath === "__all")) {
408            return _this.normalizeSpecUrl(cfg.browserUrl, "/__all");
409          } else {
410            prefixedPath = _this.getPrefixedPathToSpec(cfg, absoluteSpecPath);
411            return _this.normalizeSpecUrl(cfg.browserUrl, prefixedPath);
412          }
413        };
414      })(this));
415    };
416
417    Project.prototype.getPrefixedPathToSpec = function(cfg, pathToSpec, type) {
418      var integrationFolder, projectRoot;
419      if (type == null) {
420        type = "integration";
421      }
422      integrationFolder = cfg.integrationFolder, projectRoot = cfg.projectRoot;
423      return "/" + path.join(type, path.relative(integrationFolder, path.resolve(projectRoot, pathToSpec)));
424    };
425
426    Project.prototype.normalizeSpecUrl = function(browserUrl, specUrl) {
427      var replacer;
428      replacer = function(match, p1) {
429        return match.replace("//", "/");
430      };
431      return [browserUrl, "#/tests", specUrl].join("/").replace(multipleForwardSlashesRe, replacer);
432    };
433
434    Project.prototype.scaffold = function(cfg) {
435      var push, scaffolds;
436      debug("scaffolding project %s", this.projectRoot);
437      scaffolds = [];
438      push = scaffolds.push.bind(scaffolds);
439      push(scaffold.support(cfg.supportFolder, cfg));
440      if (!cfg.isTextTerminal) {
441        push(scaffold.integration(cfg.integrationFolder, cfg));
442        push(scaffold.fixture(cfg.fixturesFolder, cfg));
443      }
444      return Promise.all(scaffolds);
445    };
446
447    Project.prototype.writeProjectId = function(id) {
448      var attrs;
449      attrs = {
450        projectId: id
451      };
452      logger.info("Writing Project ID", _.clone(attrs));
453      this.generatedProjectIdTimestamp = new Date;
454      return settings.write(this.projectRoot, attrs)["return"](id);
455    };
456
457    Project.prototype.getProjectId = function() {
458      return this.verifyExistence().then((function(_this) {
459        return function() {
460          return settings.read(_this.projectRoot);
461        };
462      })(this)).then((function(_this) {
463        return function(settings) {
464          var id;
465          if (settings && (id = settings.projectId)) {
466            return id;
467          }
468          return errors["throw"]("NO_PROJECT_ID", _this.projectRoot);
469        };
470      })(this));
471    };
472
473    Project.prototype.verifyExistence = function() {
474      return fs.statAsync(this.projectRoot)["return"](this)["catch"]((function(_this) {
475        return function() {
476          return errors["throw"]("NO_PROJECT_FOUND_AT_PROJECT_ROOT", _this.projectRoot);
477        };
478      })(this));
479    };
480
481    Project.prototype.createCiProject = function(projectDetails) {
482      return user.ensureAuthToken().then((function(_this) {
483        return function(authToken) {
484          return commitInfo.getRemoteOrigin(_this.projectRoot).then(function(remoteOrigin) {
485            return api.createProject(projectDetails, remoteOrigin, authToken);
486          });
487        };
488      })(this)).then((function(_this) {
489        return function(newProject) {
490          return _this.writeProjectId(newProject.id)["return"](newProject);
491        };
492      })(this));
493    };
494
495    Project.prototype.getRecordKeys = function() {
496      return Promise.all([this.getProjectId(), user.ensureAuthToken()]).spread(function(projectId, authToken) {
497        return api.getProjectRecordKeys(projectId, authToken);
498      });
499    };
500
501    Project.prototype.requestAccess = function(projectId) {
502      return user.ensureAuthToken().then(function(authToken) {
503        return api.requestAccess(projectId, authToken);
504      });
505    };
506
507    Project.getOrgs = function() {
508      return user.ensureAuthToken().then(function(authToken) {
509        return api.getOrgs(authToken);
510      });
511    };
512
513    Project.paths = function() {
514      return cache.getProjectRoots();
515    };
516
517    Project.getPathsAndIds = function() {
518      return cache.getProjectRoots().map(function(projectRoot) {
519        return Promise.props({
520          path: projectRoot,
521          id: settings.id(projectRoot)
522        });
523      });
524    };
525
526    Project._mergeDetails = function(clientProject, project) {
527      return _.extend({}, clientProject, project, {
528        state: "VALID"
529      });
530    };
531
532    Project._mergeState = function(clientProject, state) {
533      return _.extend({}, clientProject, {
534        state: state
535      });
536    };
537
538    Project._getProject = function(clientProject, authToken) {
539      debug("get project from api", clientProject.id, clientProject.path);
540      return api.getProject(clientProject.id, authToken).then(function(project) {
541        debug("got project from api");
542        return Project._mergeDetails(clientProject, project);
543      })["catch"](function(err) {
544        debug("failed to get project from api", err.statusCode);
545        switch (err.statusCode) {
546          case 404:
547            return Project._mergeState(clientProject, "INVALID");
548          case 403:
549            return Project._mergeState(clientProject, "UNAUTHORIZED");
550          default:
551            throw err;
552        }
553      });
554    };
555
556    Project.getProjectStatuses = function(clientProjects) {
557      if (clientProjects == null) {
558        clientProjects = [];
559      }
560      debug("get project statuses for " + clientProjects.length + " projects");
561      return user.ensureAuthToken().then(function(authToken) {
562        debug("got auth token " + authToken);
563        return api.getProjects(authToken).then(function(projects) {
564          var projectsIndex;
565          if (projects == null) {
566            projects = [];
567          }
568          debug("got " + projects.length + " projects");
569          projectsIndex = _.keyBy(projects, "id");
570          return Promise.all(_.map(clientProjects, function(clientProject) {
571            var project;
572            debug("looking at", clientProject.path);
573            if (!clientProject.id) {
574              debug("no project id");
575              return Project._mergeState(clientProject, "VALID");
576            }
577            if (project = projectsIndex[clientProject.id]) {
578              debug("found matching:", project);
579              return Project._mergeDetails(clientProject, project);
580            } else {
581              debug("did not find matching:", project);
582              return Project._getProject(clientProject, authToken);
583            }
584          }));
585        });
586      });
587    };
588
589    Project.getProjectStatus = function(clientProject) {
590      debug("get project status for", clientProject.id, clientProject.path);
591      if (!clientProject.id) {
592        debug("no project id");
593        return Promise.resolve(Project._mergeState(clientProject, "VALID"));
594      }
595      return user.ensureAuthToken().then(function(authToken) {
596        debug("got auth token " + authToken);
597        return Project._getProject(clientProject, authToken);
598      });
599    };
600
601    Project.remove = function(path) {
602      return cache.removeProject(path);
603    };
604
605    Project.add = function(path) {
606      return cache.insertProject(path).then((function(_this) {
607        return function() {
608          return _this.id(path);
609        };
610      })(this)).then(function(id) {
611        return {
612          id: id,
613          path: path
614        };
615      })["catch"](function() {
616        return {
617          path: path
618        };
619      });
620    };
621
622    Project.id = function(path) {
623      return Project(path).getProjectId();
624    };
625
626    Project.ensureExists = function(path) {
627      return settings.exists(path);
628    };
629
630    Project.config = function(path) {
631      return Project(path).getConfig();
632    };
633
634    Project.getSecretKeyByPath = function(path) {
635      return Project.id(path).then(function(id) {
636        return user.ensureAuthToken().then(function(authToken) {
637          return api.getProjectToken(id, authToken)["catch"](function() {
638            return errors["throw"]("CANNOT_FETCH_PROJECT_TOKEN");
639          });
640        });
641      });
642    };
643
644    Project.generateSecretKeyByPath = function(path) {
645      return Project.id(path).then(function(id) {
646        return user.ensureAuthToken().then(function(authToken) {
647          return api.updateProjectToken(id, authToken)["catch"](function() {
648            return errors["throw"]("CANNOT_CREATE_PROJECT_TOKEN");
649          });
650        });
651      });
652    };
653
654    Project.findSpecs = function(projectRoot, specPattern) {
655      debug("finding specs for project %s", projectRoot);
656      la(check.unemptyString(projectRoot), "missing project path", projectRoot);
657      la(check.maybe.unemptyString(specPattern), "invalid spec pattern", specPattern);
658      if (specPattern) {
659        specPattern = path.resolve(projectRoot, specPattern);
660      }
661      return Project(projectRoot).getConfig().then(function(cfg) {
662        return specsUtil.find(cfg, specPattern);
663      }).then(R.prop("integration")).then(R.map(R.prop("name")));
664    };
665
666    return Project;
667
668  })(EE);
669
670  module.exports = Project;
671
672}).call(this);
673
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)