How to use watchPluginsFile method in Cypress

Best JavaScript code snippet using cypress

project_spec.js

Source:project_spec.js Github

copy

Full Screen

...451      }452    })453    it('does nothing when {pluginsFile: false}', function () {454      this.config.pluginsFile = false455      return this.project.watchPluginsFile(this.config, {}).then(() => {456        expect(this.project.watchers.watchTree).not.to.be.called457      })458    })459    it('does nothing if pluginsFile does not exist', function () {460      fs.pathExists.resolves(false)461      return this.project.watchPluginsFile(this.config, {}).then(() => {462        expect(this.project.watchers.watchTree).not.to.be.called463      })464    })465    it('does nothing if in run mode', function () {466      return this.project.watchPluginsFile(this.config, {467        isTextTerminal: true,468      }).then(() => {469        expect(this.project.watchers.watchTree).not.to.be.called470      })471    })472    it('watches the pluginsFile', function () {473      return this.project.watchPluginsFile(this.config, {}).then(() => {474        expect(this.project.watchers.watchTree).to.be.calledWith(this.config.pluginsFile)475        expect(this.project.watchers.watchTree.lastCall.args[1]).to.be.an('object')476        expect(this.project.watchers.watchTree.lastCall.args[1].onChange).to.be.a('function')477      })478    })479    it('calls plugins.init when file changes', function () {480      return this.project.watchPluginsFile(this.config, {}).then(() => {481        this.project.watchers.watchTree.firstCall.args[1].onChange()482        expect(plugins.init).to.be.calledWith(this.config)483      })484    })485    it('handles errors from calling plugins.init', function (done) {486      const error = { name: 'foo', message: 'foo' }487      plugins.init.rejects(error)488      this.project.watchPluginsFile(this.config, {489        onError (err) {490          expect(err).to.eql(error)491          done()492        },493      })494      .then(() => {495        this.project.watchers.watchTree.firstCall.args[1].onChange()496      })497    })498  })499  context('#watchSettingsAndStartWebsockets', () => {500    beforeEach(function () {501      this.project = new ProjectE2E('/_test-output/path/to/project-e2e')502      this.project.watchers = {}...

Full Screen

Full Screen

project-base.js

Source:project-base.js Github

copy

Full Screen

...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: () => {...

Full Screen

Full Screen

project.js

Source:project.js Github

copy

Full Screen

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

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Visits the Kitchen Sink', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1require('cypress-watch-and-reload/plugins');2module.exports = (on, config) => {3  require('cypress-watch-and-reload/plugins');4};5const { watchPluginsFile } = require('cypress-watch-and-reload/plugins');6module.exports = (on, config) => {7  watchPluginsFile(on, config);8};9const { watchPluginsFile } = require('cypress-watch-and-reload/plugins');10module.exports = (on, config) => {11  watchPluginsFile(on, config);12};13const { watchPluginsFile } = require('cypress-watch-and-reload/plugins');14module.exports = (on, config) => {15  watchPluginsFile(on, config);16};17const { watchPluginsFile } = require('cypress-watch-and-reload/plugins');18module.exports = (on, config) => {19  watchPluginsFile(on, config);20};21const { watchPluginsFile } = require('cypress-watch-and-reload/plugins');22module.exports = (on, config) => {23  watchPluginsFile(on, config);24};25const { watchPluginsFile } = require('cypress-watch-and-reload/plugins');26module.exports = (on, config) => {27  watchPluginsFile(on, config);28};29const { watchPluginsFile } = require('cypress-watch-and-reload/plugins');

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs');2const path = require('path');3module.exports = (on, config) => {4  on('task', {5    watchPluginsFile() {6      return new Promise((resolve) => {7        fs.watchFile(path.resolve(__dirname, '../plugins/index.js'), () => {8          console.log('plugins file changed!');9          resolve(null);10        });11      });12    },13  });14};15const { watchPluginsFile } = require('../test');16module.exports = (on, config) => {17  on('task', {18    pluginsFileChanged() {19      watchPluginsFile();20      return null;21    },22  });23};24const { pluginsFileChanged } = require('../test');25module.exports = (on, config) => {26  on('task', {27    pluginsFileChanged() {28      pluginsFileChanged();29      return null;30    },31  });32};33const { pluginsFileChanged } = require('../test');34module.exports = (on, config) => {35  on('task', {36    pluginsFileChanged() {37      pluginsFileChanged();38      return null;39    },40  });41};42describe('test', () => {43  it('test', () => {44    cy.task('pluginsFileChanged');45  });46});47{48}

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('cypress watchPluginsFile', () => {2  it('watchPluginsFile', () => {3    cy.watchPluginsFile('cypress/plugins/index.js', () => {4      cy.log('plugins file has changed')5    })6  })7})8module.exports = (on, config) => {9  on('file:preprocessor', (file) => {10    console.log('file preprocessor', file.filePath)11  })12}

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2  it('should watch the file', () => {3    cy.watchPluginsFile('plugins/index.js')4  })5})6module.exports = (on, config) => {7  on('watch:file:changed', (filePath) => {8    if (filePath === 'plugins/index.js') {9      console.log('plugins/index.js was changed')10    }11  })12}13describe('Test', () => {14  it('should watch the file', () => {15    cy.watchPluginsFile('plugins/index.js').then(() => {16      console.log('plugins/index.js was changed')17    })18  })19})20describe('Test', () => {21  it('should watch the file', () => {22    cy.watchPluginsFile(['plugins/index.js', 'cypress.json']).then(() => {23      console.log('plugins/index.js or cypress.json was changed')24    })25  })26})27describe('Test', () => {28  it('should watch the file', () => {29    cy.watchPluginsFile(['plugins/index.js', 'cypress.json'], 'unlink').then(() => {30      console.log('plugins/index.js or cypress.json was changed')31    })32  })33})

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