How to use getDefaultConfigFilePath method in Cypress

Best JavaScript code snippet using cypress

project-base.js

Source:project-base.js Github

copy

Full Screen

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}...

Full Screen

Full Screen

project_static.js

Source:project_static.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3exports.createCiProject = exports.writeProjectId = exports.getId = exports.add = exports.remove = exports.getProjectStatus = exports.getProjectStatuses = exports._getProject = exports._mergeState = exports._mergeDetails = exports.getDashboardProjects = exports.getPathsAndIds = exports.paths = exports.getOrgs = void 0;4const tslib_1 = require("tslib");5const debug_1 = (0, tslib_1.__importDefault)(require("debug"));6const commit_info_1 = (0, tslib_1.__importDefault)(require("@cypress/commit-info"));7const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));8const logger_1 = (0, tslib_1.__importDefault)(require("./logger"));9const api_1 = (0, tslib_1.__importDefault)(require("./api"));10const cache_1 = (0, tslib_1.__importDefault)(require("./cache"));11const user_1 = (0, tslib_1.__importDefault)(require("./user"));12const keys_1 = (0, tslib_1.__importDefault)(require("./util/keys"));13const settings = (0, tslib_1.__importStar)(require("./util/settings"));14const project_base_1 = require("./project-base");15const project_utils_1 = require("./project_utils");16const debug = (0, debug_1.default)('cypress:server:project_static');17function getOrgs() {18    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {19        const authToken = yield user_1.default.ensureAuthToken();20        return api_1.default.getOrgs(authToken);21    });22}23exports.getOrgs = getOrgs;24function paths() {25    return cache_1.default.getProjectRoots();26}27exports.paths = paths;28function getPathsAndIds() {29    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {30        const projectRoots = yield cache_1.default.getProjectRoots();31        // this assumes that the configFile for a cached project is 'cypress.json'32        // https://git.io/JeGyF33        return Promise.all(projectRoots.map((projectRoot) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {34            return {35                path: projectRoot,36                id: yield settings.id(projectRoot),37            };38        })));39    });40}41exports.getPathsAndIds = getPathsAndIds;42function getDashboardProjects() {43    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {44        const authToken = yield user_1.default.ensureAuthToken();45        debug('got auth token: %o', { authToken: keys_1.default.hide(authToken) });46        return api_1.default.getProjects(authToken);47    });48}49exports.getDashboardProjects = getDashboardProjects;50function _mergeDetails(clientProject, project) {51    return lodash_1.default.extend({}, clientProject, project, { state: 'VALID' });52}53exports._mergeDetails = _mergeDetails;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        }135        try {136            yield cache_1.default.insertProject(path);137            const id = yield getId(path);138            return {139                id,140                path,141            };142        }143        catch (e) {144            return { path };145        }146    });147}148exports.add = add;149function getId(path) {150    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {151        const configFile = yield (0, project_utils_1.getDefaultConfigFilePath)(path);152        return new project_base_1.ProjectBase({ projectRoot: path, testingType: 'e2e', options: { configFile } }).getProjectId();153    });154}155exports.getId = getId;156function writeProjectId({ id, projectRoot, configFile }) {157    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {158        const attrs = { projectId: id };159        logger_1.default.info('Writing Project ID', lodash_1.default.clone(attrs));160        // TODO: We need to set this161        // this.generatedProjectIdTimestamp = new Date()162        yield settings.write(projectRoot, attrs, { configFile });163        return id;164    });165}166exports.writeProjectId = writeProjectId;167function createCiProject(_a) {168    var { projectRoot, configFile } = _a, projectDetails = (0, tslib_1.__rest)(_a, ["projectRoot", "configFile"]);169    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {170        debug('create CI project with projectDetails %o projectRoot %s', projectDetails);171        const authToken = yield user_1.default.ensureAuthToken();172        const remoteOrigin = yield commit_info_1.default.getRemoteOrigin(projectRoot);173        debug('found remote origin at projectRoot %o', {174            remoteOrigin,175            projectRoot,176        });177        const newProject = yield api_1.default.createProject(projectDetails, remoteOrigin, authToken);178        yield writeProjectId({179            configFile,180            projectRoot,181            id: newProject.id,182        });183        return newProject;184    });185}...

Full Screen

Full Screen

project_utils.js

Source:project_utils.js Github

copy

Full Screen

...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];...

Full Screen

Full Screen

index.ts

Source:index.ts Github

copy

Full Screen

...6import * as path from 'path';7import * as errors from './errors';8import * as program from './program';9const initConfigFilename = '.directoryvalidator.json';10function getDefaultConfigFilePath(dirPath: string) {11  let absDirPath = path.resolve(dirPath);12  const homeDirPath = os.homedir();13  while (true) {14    const configPath = path.join(absDirPath, initConfigFilename);15    if (fs.existsSync(configPath)) {16      return configPath;17    }18    if (absDirPath === homeDirPath) {19      break;20    }21    absDirPath = path.resolve(absDirPath, '..');22  }23  throw new Error('configuration file was not provided/found');24}25export function writeDefaultConfigFile(parentPath: string) {26  fs.copyFileSync(27    path.join(__dirname, './resources/defaultConfig.json'),28    parentPath29  );30}31commanderProgram.version(32  JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'))33    .version34);35commanderProgram36  .arguments('<dirPath>')37  .option('-i, --init', 'Create a configuration file')38  .option('-p, --print', 'Print the directory structure validated')39  .option(40    '-f, --ignore-files <files>',41    'Ignore files (glob string) eg: -f "*.js"'42  )43  .option(44    '-d, --ignore-dirs <dirs>',45    'Ignore directories (glob string) eg: -d "**/tests"'46  )47  .option('-c, --config-file <path>', 'Path to the configuration file')48  .parse(process.argv);49const selectedOptions = commanderProgram.opts();50if (selectedOptions.init) {51  fs.copyFileSync(52    path.join(__dirname, './resources/defaultConfig.json'),53    path.join(process.cwd(), initConfigFilename)54  );55  console.log('\n\t', initConfigFilename.red, 'created', '\n');56} else if (!commanderProgram.args.length) {57  commanderProgram.help();58} else {59  const dirPath = path.resolve(commanderProgram.args[0]);60  try {61    const configPath =62      (selectedOptions.configFile as string) ||63      getDefaultConfigFilePath(dirPath);64    const results = program.run(dirPath, configPath, {65      ignoreDirsGlob: selectedOptions.ignoreDirs,66      ignoreFilesGlob: selectedOptions.ignoreFiles,67    });68    console.log('Directory successfully validated!');69    if (selectedOptions.print && results.asciiTree) {70      console.log(71        '\n',72        results.asciiTree73          .replace(/\/fileIgnored/g, '[File Ignored]'.dim)74          .replace(/\/directoryIgnored/g, '[Directory Ignored]'.dim)75          .replace(/\/emptyDirectory/g, '[Empty Directory]'.dim)76      );77    }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path')2const fs = require('fs-extra')3const cypress = require('cypress')4const defaultConfigFilePath = cypress.config.getDefaultConfigFilePath()5const config = fs.readJsonSync(defaultConfigFilePath)6const path = require('path')7const fs = require('fs-extra')8const cypress = require('cypress')9const defaultConfigFilePath = cypress.config.getDefaultConfigFilePath()10const config = fs.readJsonSync(defaultConfigFilePath)11const path = require('path')12const fs = require('fs-extra')13const cypress = require('cypress')14const defaultConfigFilePath = cypress.config.getDefaultConfigFilePath()15const config = fs.readJsonSync(defaultConfigFilePath)16const path = require('path')17const fs = require('fs-extra')18const cypress = require('cypress')19const defaultConfigFilePath = cypress.config.getDefaultConfigFilePath()20const config = fs.readJsonSync(defaultConfigFilePath)21const path = require('path')22const fs = require('fs-extra')23const cypress = require('cypress')24const defaultConfigFilePath = cypress.config.getDefaultConfigFilePath()25const config = fs.readJsonSync(defaultConfigFilePath)26const path = require('path')27const fs = require('fs-extra')28const cypress = require('cypress')29const defaultConfigFilePath = cypress.config.getDefaultConfigFilePath()30const config = fs.readJsonSync(defaultConfigFilePath)31const path = require('path')32const fs = require('fs-extra')33const cypress = require('cypress')34const defaultConfigFilePath = cypress.config.getDefaultConfigFilePath()35const config = fs.readJsonSync(defaultConfigFilePath)36const path = require('path')37const fs = require('fs-extra')38const cypress = require('cypress')39const defaultConfigFilePath = cypress.config.getDefaultConfigFilePath()40const config = fs.readJsonSync(defaultConfigFilePath)41const path = require('path')42const fs = require('fs-extra')43const cypress = require('cypress')

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress')2const path = require('path')3const configFilePath = cypress.getDefaultConfigFilePath()4console.log(path.dirname(configFilePath))5{6}7describe('My First Test', function() {8  it('Does not do much!', function() {9    cy.visit('/')10  })11})12module.exports = (on, config) => {13}14import './commands'15module.exports = (on, config) => {16}17import './commands'18Cypress.Commands.add('login', (email, password) => {19  cy.visit('/login')20  cy.get('input[name=email]').type(email)21  cy.get('input[name=password]').type(password)22  cy.get('button[type=submit]').click()23})24describe('My First Test', function

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path');2const fs = require('fs');3const defaultConfigFilePath = Cypress.config('defaultConfigFilePath');4const cypressConfigFilePath = Cypress.config('configFile');5const cypressConfigFile = Cypress.config('config');6const cypressConfigFileDir = Cypress.config('configFileDir');7const cypressConfigFileDirName = Cypress.config('configFileDirName');8const cypressConfigFileName = Cypress.config('configFileName');9const cypressConfigFileExt = Cypress.config('configFileExt');10const cypressConfigFileBase = Cypress.config('configFileBase');11const cypressConfigFileRoot = Cypress.config('configFileRoot');12const cypressConfigFileRelative = Cypress.config('configFileRelative');13const cypressConfigFileAbsolute = Cypress.config('configFileAbsolute');14const cypressConfigFileFolder = Cypress.config('configFileFolder');15const cypressConfigFileFolderName = Cypress.config('configFileFolderName');16const cypressConfigFileFolderRoot = Cypress.config('configFileFolderRoot');17const cypressConfigFileFolderRelative = Cypress.config('configFileFolderRelative');18const cypressConfigFileFolderAbsolute = Cypress.config('configFileFolderAbsolute');19const cypressConfigFileFolderBase = Cypress.config('configFileFolderBase');20const cypressConfigFileFolderExt = Cypress.config('configFileFolderExt');21const cypressConfigFileFolderParent = Cypress.config('configFileFolderParent');22const cypressConfigFileFolderParentName = Cypress.config('configFileFolderParentName');23const cypressConfigFileFolderParentRoot = Cypress.config('configFileFolderParentRoot');24const cypressConfigFileFolderParentRelative = Cypress.config('configFileFolderParentRelative');25const cypressConfigFileFolderParentAbsolute = Cypress.config('configFileFolderParentAbsolute');26const cypressConfigFileFolderParentBase = Cypress.config('configFileFolderParentBase');27const cypressConfigFileFolderParentExt = Cypress.config('configFileFolderParentExt');28const cypressConfigFileFolderParentFolder = Cypress.config('configFileFolderParentFolder');29const cypressConfigFileFolderParentFolderName = Cypress.config('configFileFolderParentFolderName');30const cypressConfigFileFolderParentFolderRoot = Cypress.config('configFileFolderParentFolderRoot');31const cypressConfigFileFolderParentFolderRelative = Cypress.config('configFileFolderParentFolderRelative');32const cypressConfigFileFolderParentFolderAbsolute = Cypress.config('configFileFolderParentFolderAbsolute');

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress')2cypress.getDefaultConfigFilePath()3  .then((path) => {4    console.log(path)5  })6const cypress = require('cypress')7cypress.getDefaultConfigFilePath('foo')8  .then((path) => {9    console.log(path)10  })11const cypress = require('cypress')12cypress.getDefaultConfigFilePath('foo', 'bar')13  .then((path) => {14    console.log(path)15  })16const cypress = require('cypress')17cypress.getDefaultConfigFilePath('foo', 'bar', 'baz')18  .then((path) => {19    console.log(path)20  })21const cypress = require('cypress')22cypress.getDefaultConfigFilePath('foo', 'bar', 'baz', 'qux')23  .then((path) => {24    console.log(path)25  })26const cypress = require('cypress')27cypress.getDefaultConfigFilePath('foo', 'bar', 'baz', 'qux', 'quux')28  .then((path) => {29    console.log(path)30  })31const cypress = require('cypress')32cypress.getDefaultConfigFilePath('foo', 'bar', 'baz', 'qux', 'quux', 'quuz')33  .then((path) => {34    console.log(path)35  })36const cypress = require('cypress

Full Screen

Cypress Tutorial

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.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

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.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful