Best JavaScript code snippet using cypress
project_spec.js
Source:project_spec.js
...469 supportFile: '/path/to/root/foo/bar.js',470 }471 })472 it('does nothing when {supportFile: false}', function () {473 const ret = this.project.checkSupportFile({ supportFile: false })474 expect(ret).to.be.undefined475 })476 it('throws when support file does not exist', function () {477 fs.pathExists.resolves(false)478 return this.project.checkSupportFile(this.config)479 .catch((e) => {480 expect(e.message).to.include('The support file is missing or invalid.')481 })482 })483 })484 context('#watchPluginsFile', () => {485 beforeEach(function () {486 sinon.stub(fs, 'pathExists').resolves(true)487 this.project = new Project('/_test-output/path/to/project')488 this.project.watchers = { watchTree: sinon.spy() }489 sinon.stub(plugins, 'init').resolves()490 this.config = {491 pluginsFile: '/path/to/plugins-file',492 }...
project-base.js
Source:project-base.js
1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3exports.ProjectBase = void 0;4const tslib_1 = require("tslib");5const check_more_types_1 = (0, tslib_1.__importDefault)(require("check-more-types"));6const debug_1 = (0, tslib_1.__importDefault)(require("debug"));7const events_1 = (0, tslib_1.__importDefault)(require("events"));8const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));9const path_1 = (0, tslib_1.__importDefault)(require("path"));10const browsers_1 = (0, tslib_1.__importDefault)(require("./browsers"));11const root_1 = (0, tslib_1.__importDefault)(require("../../root"));12const config_1 = require("../../config");13const server_ct_1 = require("./server-ct");14const socket_ct_1 = require("./socket-ct");15const socket_e2e_1 = require("./socket-e2e");16const api_1 = (0, tslib_1.__importDefault)(require("./api"));17const automation_1 = require("./automation");18const config = (0, tslib_1.__importStar)(require("./config"));19const cwd_1 = (0, tslib_1.__importDefault)(require("./cwd"));20const errors_1 = (0, tslib_1.__importDefault)(require("./errors"));21const reporter_1 = (0, tslib_1.__importDefault)(require("./reporter"));22const run_events_1 = (0, tslib_1.__importDefault)(require("./plugins/run_events"));23const saved_state_1 = (0, tslib_1.__importDefault)(require("./saved_state"));24const scaffold_1 = (0, tslib_1.__importDefault)(require("./scaffold"));25const server_e2e_1 = require("./server-e2e");26const system_1 = (0, tslib_1.__importDefault)(require("./util/system"));27const user_1 = (0, tslib_1.__importDefault)(require("./user"));28const class_helpers_1 = require("./util/class-helpers");29const fs_1 = require("./util/fs");30const settings = (0, tslib_1.__importStar)(require("./util/settings"));31const plugins_1 = (0, tslib_1.__importDefault)(require("./plugins"));32const specs_1 = (0, tslib_1.__importDefault)(require("./util/specs"));33const watchers_1 = (0, tslib_1.__importDefault)(require("./watchers"));34const dev_server_1 = (0, tslib_1.__importDefault)(require("./plugins/dev-server"));35const preprocessor_1 = (0, tslib_1.__importDefault)(require("./plugins/preprocessor"));36const specs_store_1 = require("./specs-store");37const project_utils_1 = require("./project_utils");38const localCwd = (0, cwd_1.default)();39const debug = (0, debug_1.default)('cypress:server:project');40const debugScaffold = (0, debug_1.default)('cypress:server:scaffold');41class ProjectBase extends events_1.default {42 constructor({ projectRoot, testingType, options, }) {43 super();44 this._recordTests = null;45 this._isServerOpen = false;46 this.ensureProp = class_helpers_1.ensureProp;47 this.shouldCorrelatePreRequests = () => {48 if (!this.browser) {49 return false;50 }51 const { family, majorVersion } = this.browser;52 return family === 'chromium' || (family === 'firefox' && majorVersion >= 86);53 };54 if (!projectRoot) {55 throw new Error('Instantiating lib/project requires a projectRoot!');56 }57 if (!check_more_types_1.default.unemptyString(projectRoot)) {58 throw new Error(`Expected project root path, not ${projectRoot}`);59 }60 this.testingType = testingType;61 this.projectRoot = path_1.default.resolve(projectRoot);62 this.watchers = new watchers_1.default();63 this.spec = null;64 this.browser = null;65 debug('Project created %o', {66 testingType: this.testingType,67 projectRoot: this.projectRoot,68 });69 this.options = Object.assign({ report: false, onFocusTests() { },70 onError() { },71 onWarning() { }, onSettingsChanged: false }, options);72 }73 setOnTestsReceived(fn) {74 this._recordTests = fn;75 }76 get server() {77 return this.ensureProp(this._server, 'open');78 }79 get automation() {80 return this.ensureProp(this._automation, 'open');81 }82 get cfg() {83 return this._cfg;84 }85 get state() {86 return this.cfg.state;87 }88 injectCtSpecificConfig(cfg) {89 var _a, _b;90 cfg.resolved.testingType = { value: 'component' };91 // This value is normally set up in the `packages/server/lib/plugins/index.js#110`92 // But if we don't return it in the plugins function, it never gets set93 // Since there is no chance that it will have any other value here, we set it to "component"94 // This allows users to not return config in the `cypress/plugins/index.js` file95 // https://github.com/cypress-io/cypress/issues/1686096 const rawJson = cfg.rawJson;97 return Object.assign(Object.assign({}, cfg), { componentTesting: true, viewportHeight: (_a = rawJson.viewportHeight) !== null && _a !== void 0 ? _a : 500, viewportWidth: (_b = rawJson.viewportWidth) !== null && _b !== void 0 ? _b : 500 });98 }99 createServer(testingType) {100 return testingType === 'e2e'101 ? new server_e2e_1.ServerE2E()102 : new server_ct_1.ServerCt();103 }104 open() {105 var _a;106 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {107 debug('opening project instance %s', this.projectRoot);108 debug('project open options %o', this.options);109 let cfg = this.getConfig();110 process.chdir(this.projectRoot);111 // TODO: we currently always scaffold the plugins file112 // even when headlessly or else it will cause an error when113 // we try to load it and it's not there. We must do this here114 // else initialing the plugins will instantly fail.115 if (cfg.pluginsFile) {116 debug('scaffolding with plugins file %s', cfg.pluginsFile);117 yield scaffold_1.default.plugins(path_1.default.dirname(cfg.pluginsFile), cfg);118 }119 this._server = this.createServer(this.testingType);120 cfg = yield this.initializePlugins(cfg, this.options);121 const { specsStore, startSpecWatcher, ctDevServerPort, } = yield this.initializeSpecStore(cfg);122 if (this.testingType === 'component') {123 cfg.baseUrl = `http://localhost:${ctDevServerPort}`;124 }125 const [port, warning] = yield this._server.open(cfg, {126 getCurrentBrowser: () => this.browser,127 getSpec: () => this.spec,128 exit: (_a = this.options.args) === null || _a === void 0 ? void 0 : _a.exit,129 onError: this.options.onError,130 onWarning: this.options.onWarning,131 shouldCorrelatePreRequests: this.shouldCorrelatePreRequests,132 testingType: this.testingType,133 SocketCtor: this.testingType === 'e2e' ? socket_e2e_1.SocketE2E : socket_ct_1.SocketCt,134 specsStore,135 });136 this._isServerOpen = true;137 // if we didnt have a cfg.port138 // then get the port once we139 // open the server140 if (!cfg.port) {141 cfg.port = port;142 // and set all the urls again143 lodash_1.default.extend(cfg, config.setUrls(cfg));144 }145 cfg.proxyServer = cfg.proxyUrl;146 // store the cfg from147 // opening the server148 this._cfg = cfg;149 debug('project config: %o', lodash_1.default.omit(cfg, 'resolved'));150 if (warning) {151 this.options.onWarning(warning);152 }153 // save the last time they opened the project154 // along with the first time they opened it155 const now = Date.now();156 const stateToSave = {157 lastOpened: now,158 };159 if (!cfg.state || !cfg.state.firstOpened) {160 stateToSave.firstOpened = now;161 }162 this.watchSettings({163 onSettingsChanged: this.options.onSettingsChanged,164 projectRoot: this.projectRoot,165 configFile: this.options.configFile,166 });167 this.startWebsockets({168 onReloadBrowser: this.options.onReloadBrowser,169 onFocusTests: this.options.onFocusTests,170 onSpecChanged: this.options.onSpecChanged,171 }, {172 socketIoCookie: cfg.socketIoCookie,173 namespace: cfg.namespace,174 screenshotsFolder: cfg.screenshotsFolder,175 report: cfg.report,176 reporter: cfg.reporter,177 reporterOptions: cfg.reporterOptions,178 projectRoot: this.projectRoot,179 });180 yield Promise.all([181 this.scaffold(cfg),182 this.saveState(stateToSave),183 ]);184 yield Promise.all([185 (0, project_utils_1.checkSupportFile)({ configFile: cfg.configFile, supportFile: cfg.supportFile }),186 this.watchPluginsFile(cfg, this.options),187 ]);188 if (cfg.isTextTerminal) {189 return;190 }191 // start watching specs192 // whenever a spec file is added or removed, we notify the193 // <SpecList>194 // This is only used for CT right now by general users.195 // It is is used with E2E if the CypressInternal_UseInlineSpecList flag is true.196 startSpecWatcher();197 if (!cfg.experimentalInteractiveRunEvents) {198 return;199 }200 const sys = yield system_1.default.info();201 const beforeRunDetails = {202 config: cfg,203 cypressVersion: root_1.default.version,204 system: lodash_1.default.pick(sys, 'osName', 'osVersion'),205 };206 return run_events_1.default.execute('before:run', cfg, beforeRunDetails);207 });208 }209 getRuns() {210 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {211 const [projectId, authToken] = yield Promise.all([212 this.getProjectId(),213 user_1.default.ensureAuthToken(),214 ]);215 return api_1.default.getProjectRuns(projectId, authToken);216 });217 }218 reset() {219 debug('resetting project instance %s', this.projectRoot);220 this.spec = null;221 this.browser = null;222 if (this._automation) {223 this._automation.reset();224 }225 if (this._server) {226 return this._server.reset();227 }228 return;229 }230 close() {231 var _a, _b, _c;232 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {233 debug('closing project instance %s', this.projectRoot);234 this.spec = null;235 this.browser = null;236 if (!this._isServerOpen) {237 return;238 }239 const closePreprocessor = (_a = (this.testingType === 'e2e' && preprocessor_1.default.close)) !== null && _a !== void 0 ? _a : undefined;240 yield Promise.all([241 (_b = this.server) === null || _b === void 0 ? void 0 : _b.close(),242 (_c = this.watchers) === null || _c === void 0 ? void 0 : _c.close(),243 closePreprocessor === null || closePreprocessor === void 0 ? void 0 : closePreprocessor(),244 ]);245 this._isServerOpen = false;246 process.chdir(localCwd);247 const config = this.getConfig();248 if (config.isTextTerminal || !config.experimentalInteractiveRunEvents)249 return;250 return run_events_1.default.execute('after:run', config);251 });252 }253 _onError(err, options) {254 debug('got plugins error', err.stack);255 browsers_1.default.close();256 options.onError(err);257 }258 initializeSpecStore(updatedConfig) {259 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {260 const allSpecs = yield specs_1.default.findSpecs({261 projectRoot: updatedConfig.projectRoot,262 fixturesFolder: updatedConfig.fixturesFolder,263 supportFile: updatedConfig.supportFile,264 testFiles: updatedConfig.testFiles,265 ignoreTestFiles: updatedConfig.ignoreTestFiles,266 componentFolder: updatedConfig.componentFolder,267 integrationFolder: updatedConfig.integrationFolder,268 });269 const specs = allSpecs.filter((spec) => {270 if (this.testingType === 'component') {271 return spec.specType === 'component';272 }273 if (this.testingType === 'e2e') {274 return spec.specType === 'integration';275 }276 throw Error(`Cannot return specType for testingType: ${this.testingType}`);277 });278 return this.initSpecStore({ specs, config: updatedConfig });279 });280 }281 initializePlugins(cfg, options) {282 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {283 // only init plugins with the284 // allowed config values to285 // prevent tampering with the286 // internals and breaking cypress287 const allowedCfg = (0, config_1.allowed)(cfg);288 const modifiedCfg = yield plugins_1.default.init(allowedCfg, {289 projectRoot: this.projectRoot,290 configFile: settings.pathToConfigFile(this.projectRoot, options),291 testingType: options.testingType,292 onError: (err) => this._onError(err, options),293 onWarning: options.onWarning,294 });295 debug('plugin config yielded: %o', modifiedCfg);296 return config.updateWithPluginValues(cfg, modifiedCfg);297 });298 }299 startCtDevServer(specs, config) {300 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {301 // CT uses a dev-server to build the bundle.302 // We start the dev server here.303 const devServerOptions = yield dev_server_1.default.start({ specs, config });304 if (!devServerOptions) {305 throw new Error([306 'It looks like nothing was returned from on(\'dev-server:start\', {here}).',307 'Make sure that the dev-server:start function returns an object.',308 'For example: on("dev-server:start", () => startWebpackDevServer({ webpackConfig }))',309 ].join('\n'));310 }311 return { port: devServerOptions.port };312 });313 }314 initSpecStore({ specs, config, }) {315 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {316 const specsStore = new specs_store_1.SpecsStore(config, this.testingType);317 const startSpecWatcher = () => {318 return specsStore.watch({319 onSpecsChanged: (specs) => {320 // both e2e and CT watch the specs and send them to the321 // client to be shown in the SpecList.322 this.server.sendSpecList(specs, this.testingType);323 if (this.testingType === 'component') {324 // ct uses the dev-server to build and bundle the speces.325 // send new files to dev server326 dev_server_1.default.updateSpecs(specs);327 }328 },329 });330 };331 let ctDevServerPort;332 if (this.testingType === 'component') {333 const { port } = yield this.startCtDevServer(specs, config);334 ctDevServerPort = port;335 }336 return specsStore.storeSpecFiles()337 .return({338 specsStore,339 ctDevServerPort,340 startSpecWatcher,341 });342 });343 }344 watchPluginsFile(cfg, options) {345 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {346 debug(`attempt watch plugins file: ${cfg.pluginsFile}`);347 if (!cfg.pluginsFile || options.isTextTerminal) {348 return Promise.resolve();349 }350 const found = yield fs_1.fs.pathExists(cfg.pluginsFile);351 debug(`plugins file found? ${found}`);352 // ignore if not found. plugins#init will throw the right error353 if (!found) {354 return;355 }356 debug('watch plugins file');357 return this.watchers.watchTree(cfg.pluginsFile, {358 onChange: () => {359 // TODO: completely re-open project instead?360 debug('plugins file changed');361 // re-init plugins after a change362 this.initializePlugins(cfg, options)363 .catch((err) => {364 options.onError(err);365 });366 },367 });368 });369 }370 watchSettings({ onSettingsChanged, configFile, projectRoot, }) {371 // bail if we havent been told to372 // watch anything (like in run mode)373 if (!onSettingsChanged) {374 return;375 }376 debug('watch settings files');377 const obj = {378 onChange: () => {379 // dont fire change events if we generated380 // a project id less than 1 second ago381 if (this.generatedProjectIdTimestamp &&382 ((Date.now() - this.generatedProjectIdTimestamp) < 1000)) {383 return;384 }385 // call our callback function386 // when settings change!387 onSettingsChanged();388 },389 };390 if (configFile !== false) {391 this.watchers.watchTree(settings.pathToConfigFile(projectRoot, { configFile }), obj);392 }393 return this.watchers.watch(settings.pathToCypressEnvJson(projectRoot), obj);394 }395 initializeReporter({ report, reporter, projectRoot, reporterOptions, }) {396 if (!report) {397 return;398 }399 try {400 reporter_1.default.loadReporter(reporter, projectRoot);401 }402 catch (err) {403 const paths = reporter_1.default.getSearchPathsForReporter(reporter, projectRoot);404 // only include the message if this is the standard MODULE_NOT_FOUND405 // else include the whole stack406 const errorMsg = err.code === 'MODULE_NOT_FOUND' ? err.message : err.stack;407 errors_1.default.throw('INVALID_REPORTER_NAME', {408 paths,409 error: errorMsg,410 name: reporter,411 });412 }413 return reporter_1.default.create(reporter, reporterOptions, projectRoot);414 }415 startWebsockets(options, { socketIoCookie, namespace, screenshotsFolder, report, reporter, reporterOptions, projectRoot }) {416 // if we've passed down reporter417 // then record these via mocha reporter418 const reporterInstance = this.initializeReporter({419 report,420 reporter,421 reporterOptions,422 projectRoot,423 });424 const onBrowserPreRequest = (browserPreRequest) => {425 this.server.addBrowserPreRequest(browserPreRequest);426 };427 const onRequestEvent = (eventName, data) => {428 this.server.emitRequestEvent(eventName, data);429 };430 this._automation = new automation_1.Automation(namespace, socketIoCookie, screenshotsFolder, onBrowserPreRequest, onRequestEvent);431 this.server.startWebsockets(this.automation, this.cfg, {432 onReloadBrowser: options.onReloadBrowser,433 onFocusTests: options.onFocusTests,434 onSpecChanged: options.onSpecChanged,435 onSavedStateChanged: (state) => this.saveState(state),436 onCaptureVideoFrames: (data) => {437 // TODO: move this to browser automation middleware438 this.emit('capture:video:frames', data);439 },440 onConnect: (id) => {441 debug('socket:connected');442 this.emit('socket:connected', id);443 },444 onTestsReceivedAndMaybeRecord: (runnables, cb) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {445 var _a;446 debug('received runnables %o', runnables);447 if (reporterInstance) {448 reporterInstance.setRunnables(runnables);449 }450 if (this._recordTests) {451 yield ((_a = this._recordTests) === null || _a === void 0 ? void 0 : _a.call(this, runnables, cb));452 this._recordTests = null;453 return;454 }455 cb();456 }),457 onMocha: (event, runnable) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {458 debug('onMocha', event);459 // bail if we dont have a460 // reporter instance461 if (!reporterInstance) {462 return;463 }464 reporterInstance.emit(event, runnable);465 if (event === 'end') {466 const [stats = {}] = yield Promise.all([467 (reporterInstance != null ? reporterInstance.end() : undefined),468 this.server.end(),469 ]);470 this.emit('end', stats);471 }472 return;473 }),474 });475 }476 changeToUrl(url) {477 this.server.changeToUrl(url);478 }479 setCurrentSpecAndBrowser(spec, browser) {480 this.spec = spec;481 this.browser = browser;482 }483 setBrowsers(browsers = []) {484 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {485 debug('getting config before setting browsers %o', browsers);486 const cfg = this.getConfig();487 debug('setting config browsers to %o', browsers);488 cfg.browsers = browsers;489 });490 }491 getAutomation() {492 return this.automation;493 }494 initializeConfig() {495 var _a, _b;496 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {497 // set default for "configFile" if undefined498 if (this.options.configFile === undefined499 || this.options.configFile === null) {500 this.options.configFile = yield (0, project_utils_1.getDefaultConfigFilePath)(this.projectRoot, !((_a = this.options.args) === null || _a === void 0 ? void 0 : _a.runProject));501 }502 let theCfg = yield config.get(this.projectRoot, this.options);503 if (theCfg.browsers) {504 theCfg.browsers = (_b = theCfg.browsers) === null || _b === void 0 ? void 0 : _b.map((browser) => {505 if (browser.family === 'chromium' || theCfg.chromeWebSecurity) {506 return browser;507 }508 return Object.assign(Object.assign({}, browser), { warning: browser.warning || errors_1.default.getMsgByType('CHROME_WEB_SECURITY_NOT_SUPPORTED', browser.name) });509 });510 }511 theCfg = this.testingType === 'e2e'512 ? theCfg513 : this.injectCtSpecificConfig(theCfg);514 if (theCfg.isTextTerminal) {515 this._cfg = theCfg;516 return this._cfg;517 }518 // decide if new project by asking scaffold519 // and looking at previously saved user state520 if (!theCfg.integrationFolder) {521 throw new Error('Missing integration folder');522 }523 const untouchedScaffold = yield this.determineIsNewProject(theCfg);524 const userHasSeenBanner = lodash_1.default.get(theCfg, 'state.showedNewProjectBanner', false);525 debugScaffold(`untouched scaffold ${untouchedScaffold} banner closed ${userHasSeenBanner}`);526 theCfg.isNewProject = untouchedScaffold && !userHasSeenBanner;527 const cfgWithSaved = yield this._setSavedState(theCfg);528 this._cfg = cfgWithSaved;529 return this._cfg;530 });531 }532 // returns project config (user settings + defaults + cypress.json)533 // with additional object "state" which are transient things like534 // window width and height, DevTools open or not, etc.535 getConfig() {536 if (!this._cfg) {537 throw Error('Must call #initializeConfig before accessing config.');538 }539 debug('project has config %o', this._cfg);540 return this._cfg;541 }542 // Saved state543 // forces saving of project's state by first merging with argument544 saveState(stateChanges = {}) {545 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {546 if (!this.cfg) {547 throw new Error('Missing project config');548 }549 if (!this.projectRoot) {550 throw new Error('Missing project root');551 }552 let state = yield saved_state_1.default.create(this.projectRoot, this.cfg.isTextTerminal);553 state.set(stateChanges);554 state = yield state.get();555 this.cfg.state = state;556 return state;557 });558 }559 _setSavedState(cfg) {560 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {561 debug('get saved state');562 let state = yield saved_state_1.default.create(this.projectRoot, cfg.isTextTerminal);563 state = yield state.get();564 cfg.state = state;565 return cfg;566 });567 }568 // Scaffolding569 removeScaffoldedFiles() {570 if (!this.cfg) {571 throw new Error('Missing project config');572 }573 return scaffold_1.default.removeIntegration(this.cfg.integrationFolder, this.cfg);574 }575 // do not check files again and again - keep previous promise576 // to refresh it - just close and open the project again.577 determineIsNewProject(folder) {578 return scaffold_1.default.isNewProject(folder);579 }580 scaffold(cfg) {581 debug('scaffolding project %s', this.projectRoot);582 const scaffolds = [];583 const push = scaffolds.push.bind(scaffolds);584 // TODO: we are currently always scaffolding support585 // even when headlessly - this is due to a major breaking586 // change of 0.18.0587 // we can later force this not to always happen when most588 // of our users go beyond 0.18.0589 //590 // ensure support dir is created591 // and example support file if dir doesnt exist592 push(scaffold_1.default.support(cfg.supportFolder, cfg));593 // if we're in headed mode add these other scaffolding tasks594 debug('scaffold flags %o', {595 isTextTerminal: cfg.isTextTerminal,596 CYPRESS_INTERNAL_FORCE_SCAFFOLD: process.env.CYPRESS_INTERNAL_FORCE_SCAFFOLD,597 });598 const scaffoldExamples = !cfg.isTextTerminal || process.env.CYPRESS_INTERNAL_FORCE_SCAFFOLD;599 if (scaffoldExamples) {600 debug('will scaffold integration and fixtures folder');601 push(scaffold_1.default.integration(cfg.integrationFolder, cfg));602 push(scaffold_1.default.fixture(cfg.fixturesFolder, cfg));603 }604 else {605 debug('will not scaffold integration or fixtures folder');606 }607 return Promise.all(scaffolds);608 }609 // These methods are not related to start server/sockets/runners610 getProjectId() {611 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {612 yield this.verifyExistence();613 const readSettings = yield settings.read(this.projectRoot, this.options);614 if (readSettings && readSettings.projectId) {615 return readSettings.projectId;616 }617 errors_1.default.throw('NO_PROJECT_ID', settings.configFile(this.options), this.projectRoot);618 });619 }620 verifyExistence() {621 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {622 try {623 yield fs_1.fs.statAsync(this.projectRoot);624 }625 catch (err) {626 errors_1.default.throw('NO_PROJECT_FOUND_AT_PROJECT_ROOT', this.projectRoot);627 }628 });629 }630 getRecordKeys() {631 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {632 const [projectId, authToken] = yield Promise.all([633 this.getProjectId(),634 user_1.default.ensureAuthToken(),635 ]);636 return api_1.default.getProjectRecordKeys(projectId, authToken);637 });638 }639 requestAccess(projectId) {640 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {641 const authToken = yield user_1.default.ensureAuthToken();642 return api_1.default.requestAccess(projectId, authToken);643 });644 }645 // For testing646 // Do not use this method outside of testing647 // pass all your options when you create a new instance!648 __setOptions(options) {649 this.options = options;650 }651 __setConfig(cfg) {652 this._cfg = cfg;653 }654}...
project.js
Source:project.js
...105 options.onSavedStateChanged = function(state) {106 return _this.saveState(state);107 };108 return Promise.join(_this.watchSettingsAndStartWebsockets(options, cfg), _this.scaffold(cfg)).then(function() {109 return Promise.join(_this.checkSupportFile(cfg), _this.watchPluginsFile(cfg, options));110 });111 });112 };113 })(this))["return"](this);114 };115 Project.prototype._initPlugins = function(cfg, options) {116 cfg = config.whitelist(cfg);117 return plugins.init(cfg, {118 onError: function(err) {119 debug('got plugins error', err.stack);120 browsers.close();121 return options.onError(err);122 }123 });...
project_utils.js
Source:project_utils.js
1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3exports.getDefaultConfigFilePath = exports.checkSupportFile = exports.getSpecUrl = void 0;4const tslib_1 = require("tslib");5const debug_1 = (0, tslib_1.__importDefault)(require("debug"));6const path_1 = (0, tslib_1.__importDefault)(require("path"));7const settings = (0, tslib_1.__importStar)(require("./util/settings"));8const errors_1 = (0, tslib_1.__importDefault)(require("./errors"));9const fs_1 = require("./util/fs");10const escape_filename_1 = require("./util/escape_filename");11const configFiles_1 = require("./configFiles");12const debug = (0, debug_1.default)('cypress:server:project_utils');13const multipleForwardSlashesRe = /[^:\/\/](\/{2,})/g;14const backSlashesRe = /\\/g;15const normalizeSpecUrl = (browserUrl, specUrl) => {16 const replacer = (match) => match.replace('//', '/');17 return [18 browserUrl,19 '#/tests',20 (0, escape_filename_1.escapeFilenameInUrl)(specUrl),21 ].join('/')22 .replace(multipleForwardSlashesRe, replacer);23};24const getPrefixedPathToSpec = ({ integrationFolder, componentFolder, projectRoot, type, pathToSpec, }) => {25 type !== null && type !== void 0 ? type : (type = 'integration');26 // for now hard code the 'type' as integration27 // but in the future accept something different here28 // strip out the integration folder and prepend with "/"29 // example:30 //31 // /Users/bmann/Dev/cypress-app/.projects/cypress/integration32 // /Users/bmann/Dev/cypress-app/.projects/cypress/integration/foo.js33 //34 // becomes /integration/foo.js35 const folderToUse = type === 'integration' ? integrationFolder : componentFolder;36 // To avoid having invalid urls from containing backslashes,37 // we normalize specUrls to posix by replacing backslash by slash38 // Indeed, path.realtive will return something different on windows39 // than on posix systems which can lead to problems40 const url = `/${path_1.default.join(type, path_1.default.relative(folderToUse, path_1.default.resolve(projectRoot, pathToSpec))).replace(backSlashesRe, '/')}`;41 debug('prefixed path for spec %o', { pathToSpec, type, url });42 return url;43};44const getSpecUrl = ({ absoluteSpecPath, specType, browserUrl, integrationFolder, componentFolder, projectRoot, }) => {45 specType !== null && specType !== void 0 ? specType : (specType = 'integration');46 browserUrl !== null && browserUrl !== void 0 ? browserUrl : (browserUrl = '');47 debug('get spec url: %s for spec type %s', absoluteSpecPath, specType);48 // if we don't have a absoluteSpecPath or its __all49 if (!absoluteSpecPath || (absoluteSpecPath === '__all')) {50 const url = normalizeSpecUrl(browserUrl, '/__all');51 debug('returning url to run all specs: %s', url);52 return url;53 }54 // TODO:55 // to handle both unit + integration tests we need56 // to figure out (based on the config) where this absoluteSpecPath57 // lives. does it live in the integrationFolder or58 // the unit folder?59 // once we determine that we can then prefix it correctly60 // with either integration or unit61 const prefixedPath = getPrefixedPathToSpec({62 integrationFolder,63 componentFolder,64 projectRoot,65 pathToSpec: absoluteSpecPath,66 type: specType,67 });68 const url = normalizeSpecUrl(browserUrl, prefixedPath);69 debug('return path to spec %o', { specType, absoluteSpecPath, prefixedPath, url });70 return url;71};72exports.getSpecUrl = getSpecUrl;73const checkSupportFile = ({ supportFile, configFile, }) => (0, tslib_1.__awaiter)(void 0, void 0, void 0, function* () {74 if (supportFile && typeof supportFile === 'string') {75 const found = yield fs_1.fs.pathExists(supportFile);76 if (!found) {77 errors_1.default.throw('SUPPORT_FILE_NOT_FOUND', supportFile, settings.configFile({ configFile }));78 }79 }80 return;81});82exports.checkSupportFile = checkSupportFile;83function getDefaultConfigFilePath(projectRoot, returnDefaultValueIfNotFound = true) {84 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {85 const filesInProjectDir = yield fs_1.fs.readdir(projectRoot);86 const foundConfigFiles = configFiles_1.CYPRESS_CONFIG_FILES.filter((file) => filesInProjectDir.includes(file));87 // if we only found one default file, it is the one88 if (foundConfigFiles.length === 1) {89 return foundConfigFiles[0];90 }91 // if we found more than one, throw a language conflict92 if (foundConfigFiles.length > 1) {93 throw errors_1.default.throw('CONFIG_FILES_LANGUAGE_CONFLICT', projectRoot, ...foundConfigFiles);94 }95 if (returnDefaultValueIfNotFound) {96 // Default is to create a new `cypress.json` file if one does not exist.97 return configFiles_1.CYPRESS_CONFIG_FILES[0];98 }99 throw errors_1.default.get('NO_DEFAULT_CONFIG_FILE_FOUND', projectRoot);100 });101}...
file-stream.js
Source:file-stream.js
...79 if (isSupportedTemplate) {80 loadTemplate(res, isSupportedTemplate.path)81 }82 else if (!urlQuery) {83 const isSupportedFile = checkSupportFile(pathname)84 if (isSupportedFile) {85 loadFile(res, pathname)86 }87 }88}...
Using AI Code Generation
1describe('My First Test', () => {2 it('Does not do much!', () => {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1describe('My First Test', () => {2 it('Does not do much!', () => {3 expect(true).to.equal(true)4 })5 it('Check Support File', () => {6 cy.checkSupportFile()7 })8})9Cypress.Commands.add('checkSupportFile', () => {10 cy.log('Support File is loaded')11})12Browser: Electron 59 (headless)13 √ Does not do much! (25ms)14 √ Check Support File (4ms)15 2 passing (43ms)16cy.window().then((win) => {17 expect(win.Cypress).to.exist18})
Using AI Code Generation
1describe('My First Test', () => {2 it('Does not do much!', () => {3 expect(true).to.equal(true)4 })5 it('Check if support file exists', () => {6 cy.checkSupportFile()7 })8})9Cypress.Commands.add('checkSupportFile', () => {10 cy.log('Checking if support file exists')11 cy.readFile('cypress/support/index.js').should('exist')12})13Cypress.Commands.add('checkSupportFile', () => {14 cy.log('Checking if support file exists')15 cy.readFile('cypress/support/index.js').should('exist')16})17Cypress.Commands.add('checkSupportFile', () => {18 cy.log('Checking if support file exists')19 cy.readFile('cypress/support/index.js').should('exist')20})21Cypress.Commands.add('checkSupportFile', () => {22 cy.log('Checking if support file exists')23 cy.readFile('cypress/support/index.js').should('exist')24})25Cypress.Commands.add('checkSupportFile', () => {26 cy.log('Checking if support file exists')27 cy.readFile('cypress/support/index.js').should('exist')28})29Cypress.Commands.add('checkSupportFile', () => {30 cy.log('Checking if support file exists')31 cy.readFile('cypress/support/index.js').should('exist')32})33Cypress.Commands.add('checkSupportFile', () => {34 cy.log('Checking if support file exists')35 cy.readFile('cypress/support/index.js').should('exist')36})37Cypress.Commands.add('checkSupportFile', () => {38 cy.log('
Using AI Code Generation
1cy.checkSupportFile('cypress/support/index.js')2cy.checkSupportFile('cypress/support/index.js')3cy.checkSupportFile('cypress/support/index.js')4cy.checkSupportFile('cypress/support/index.js')5cy.checkSupportFile('cypress/support/index.js')6"dependencies": {7 },8 "devDependencies": {9 "eslint-plugin-import": "^2.17.2",
Using AI Code Generation
1describe('Test', () => {2 it('Test', () => {3 cy.checkSupportFile();4 });5});6Cypress.Commands.add('checkSupportFile', () => {7 cy.log('Support file is working');8});9describe('Test', () => {10 it('Test', () => {11 cy.checkSupportFile();12 });13});14Cypress.Commands.add('checkSupportFile', () => {15 cy.log('Support file is working');16});17Cypress.Commands.add('checkSupportFile', () => {18 cy.log('Support file is working');19});20describe('Test', () => {21 it('Test', () => {22 cy.checkSupportFile();23 });24});25Cypress.Commands.add('checkSupportFile', () => {26 cy.log('Support file is working');27});28Cypress.Commands.add('checkSupportFile', () => {29 cy.log('Support file is working');30});31describe('Test', () => {32 it('Test', () => {33 cy.checkSupportFile();34 });35});36Cypress.Commands.add('checkSupportFile', () => {37 cy.log('Support file is working');38});39Cypress.Commands.add('checkSupportFile', () => {40 cy.log('Support file is working');41});42describe('Test', () => {43 it('Test', () => {44 cy.checkSupportFile();
Using AI Code Generation
1describe('Cypress Demo', function() {2 it('Cypress Demo', function() {3 cy.get('#alertbtn').click()4 cy.get('[value="Confirm"]').click()5 cy.on('window:alert', (str) => {6 expect(str).to.equal('Hello , share this practice page and share your knowledge')7 })8 cy.on('window:confirm', (str) => {9 expect(str).to.equal('Hello , Are you sure you want to confirm?')10 })11 })12})13{14 "reporterOptions": {15 "mochaJunitReportersReporterOptions": {16 },17 "mochawesomeReporterOptions": {18 }19 }20}21module.exports = (on, config) => {22 require('cypress-log-to-output').install(on, (type, event) => {23 if (type === 'task') {24 }25 })26 on('task', {27 log(message) {28 console.log(message)29 },30 table(message) {31 console.table(message)32 },33 })34}35import './commands'36import 'cypress-xpath'37import 'cypress
Using AI Code Generation
1cy.checkSupportFile('file.txt')2cy.readFile('file.txt').should('exist')3cy.readFile('file.txt').should('not.exist')4cy.readFile('file.txt').should('exist')5cy.readFile('file.txt').should('not.exist')6cy.readFile('file.txt').should('be.empty')7cy.readFile('file.txt').should('not.be.empty')8cy.readFile('file.txt').should('equal', 'Hello World')9cy.readFile('file.txt').should('contain', 'Hello World')10cy.readFile('file.txt').should('not.contain', 'Hello World')11We can use the cy.readFile() command to check if file
Using AI Code Generation
1describe('Check whether the support file is present or not', () => {2 it('Check whether the support file is present or not', () => {3 cy.checkSupportFile()4 })5})6Cypress.Commands.add('checkSupportFile', () => {7 cy.readFile('cypress/support/index.js').then((content) => {8 if (content.includes('supportFile')) {9 cy.log('Support file is present')10 } else {11 cy.log('Support file is not present')12 }13 })14})15describe('Check whether the support file is present or not', () => {16 it('Check whether the support file is present or not', () => {17 cy.checkSupportFile()18 })19})20Cypress.Commands.add('checkSupportFile', () => {21 cy.readFile('cypress/support/index.js').then((content) => {22 if (content.includes('supportFile')) {23 cy.log('Support file is present')24 } else {25 cy.log('Support file is not present')26 }27 })28})
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!!