How to use setPluginResolvedOn method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

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

config.js

Source: config.js Github

copy
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.getNameFromRoot = exports.getResolvedRuntimeConfig = exports.parseEnv = exports.setUrls = exports.setAbsolutePaths = exports.setParentTestsPaths = exports.setPluginsFile = exports.setSupportFileAndFolder = exports.setScaffoldPaths = exports.setNodeBinary = exports.resolveConfigValues = exports.updateWithPluginValues = exports.setPluginResolvedOn = exports.setResolvedConfigValues = exports.mergeDefaults = exports.set = exports.get = exports.isValidCypressInternalEnvValue = exports.utils = exports.RESOLVED_FROM = void 0;
4const tslib_1 = require("tslib");
5const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
6const path_1 = (0, tslib_1.__importDefault)(require("path"));
7const bluebird_1 = (0, tslib_1.__importDefault)(require("bluebird"));
8const return_deep_diff_1 = (0, tslib_1.__importDefault)(require("return-deep-diff"));
9const config_1 = (0, tslib_1.__importDefault)(require("../../config"));
10const errors_1 = (0, tslib_1.__importDefault)(require("./errors"));
11const scaffold_1 = (0, tslib_1.__importDefault)(require("./scaffold"));
12const fs_1 = require("./util/fs");
13const keys_1 = (0, tslib_1.__importDefault)(require("./util/keys"));
14const origin_1 = (0, tslib_1.__importDefault)(require("./util/origin"));
15const settings = (0, tslib_1.__importStar)(require("./util/settings"));
16const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
17const path_helpers_1 = (0, tslib_1.__importDefault)(require("./util/path_helpers"));
18const debug = (0, debug_1.default)('cypress:server:config');
19const config_2 = require("./util/config");
20exports.RESOLVED_FROM = ['plugin', 'env', 'default', 'runtime', 'config'];
21const folders = (0, lodash_1.default)(config_1.default.options).filter({ isFolder: true }).map('name').value();
22const convertRelativeToAbsolutePaths = (projectRoot, obj) => {
23    return lodash_1.default.reduce(folders, (memo, folder) => {
24        const val = obj[folder];
25        if ((val != null) && (val !== false)) {
26            memo[folder] = path_1.default.resolve(projectRoot, val);
27        }
28        return memo;
29    }, {});
30};
31const validateFile = (file) => {
32    return (settings) => {
33        return config_1.default.validate(settings, (errMsg) => {
34            return errors_1.default.throw('SETTINGS_VALIDATION_ERROR', file, errMsg);
35        });
36    };
37};
38const hideSpecialVals = function (val, key) {
39    if (lodash_1.default.includes(config_2.CYPRESS_SPECIAL_ENV_VARS, key)) {
40        return keys_1.default.hide(val);
41    }
42    return val;
43};
44// an object with a few utility methods for easy stubbing from unit tests
45exports.utils = {
46    resolveModule(name) {
47        return require.resolve(name);
48    },
49    // tries to find support or plugins file
50    // returns:
51    //   false - if the file should not be set
52    //   string - found filename
53    //   null - if there is an error finding the file
54    discoverModuleFile(options) {
55        debug('discover module file %o', options);
56        const { filename, isDefault } = options;
57        if (!isDefault) {
58            // they have it explicitly set, so it should be there
59            return fs_1.fs.pathExists(filename)
60                .then((found) => {
61                if (found) {
62                    debug('file exists, assuming it will load');
63                    return filename;
64                }
65                debug('could not find %o', { filename });
66                return null;
67            });
68        }
69        // support or plugins file doesn't exist on disk?
70        debug(`support file is default, check if ${path_1.default.dirname(filename)} exists`);
71        return fs_1.fs.pathExists(filename)
72            .then((found) => {
73            if (found) {
74                debug('is there index.ts in the support or plugins folder %s?', filename);
75                const tsFilename = path_1.default.join(filename, 'index.ts');
76                return fs_1.fs.pathExists(tsFilename)
77                    .then((foundTsFile) => {
78                    if (foundTsFile) {
79                        debug('found index TS file %s', tsFilename);
80                        return tsFilename;
81                    }
82                    // if the directory exists, set it to false so it's ignored
83                    debug('setting support or plugins file to false');
84                    return false;
85                });
86            }
87            debug('folder does not exist, set to default index.js');
88            // otherwise, set it up to be scaffolded later
89            return path_1.default.join(filename, 'index.js');
90        });
91    },
92};
93function isValidCypressInternalEnvValue(value) {
94    // names of config environments, see "config/app.yml"
95    const names = ['development', 'test', 'staging', 'production'];
96    return lodash_1.default.includes(names, value);
97}
98exports.isValidCypressInternalEnvValue = isValidCypressInternalEnvValue;
99function get(projectRoot, options = {}) {
100    return bluebird_1.default.all([
101        settings.read(projectRoot, options).then(validateFile('cypress.json')),
102        settings.readEnv(projectRoot).then(validateFile('cypress.env.json')),
103    ])
104        .spread((settings, envFile) => {
105        return set({
106            projectName: getNameFromRoot(projectRoot),
107            projectRoot,
108            config: lodash_1.default.cloneDeep(settings),
109            envFile: lodash_1.default.cloneDeep(envFile),
110            options,
111        });
112    });
113}
114exports.get = get;
115function set(obj = {}) {
116    debug('setting config object');
117    let { projectRoot, projectName, config, envFile, options } = obj;
118    // just force config to be an object so we dont have to do as much
119    // work in our tests
120    if (config == null) {
121        config = {};
122    }
123    debug('config is %o', config);
124    // flatten the object's properties into the master config object
125    config.envFile = envFile;
126    config.projectRoot = projectRoot;
127    config.projectName = projectName;
128    return mergeDefaults(config, options);
129}
130exports.set = set;
131function mergeDefaults(config = {}, options = {}) {
132    var _a, _b;
133    const resolved = {};
134    config.rawJson = lodash_1.default.cloneDeep(config);
135    lodash_1.default.extend(config, lodash_1.default.pick(options, 'configFile', 'morgan', 'isTextTerminal', 'socketId', 'report', 'browsers'));
136    debug('merged config with options, got %o', config);
137    lodash_1.default
138        .chain(config_1.default.allowed(options))
139        .omit('env')
140        .omit('browsers')
141        .each((val, key) => {
142        resolved[key] = 'cli';
143        config[key] = val;
144    }).value();
145    let url = config.baseUrl;
146    if (url) {
147        // replace multiple slashes at the end of string to single slash
148        // so http://localhost/// will be http://localhost/
149        // https://regexr.com/48rvt
150        config.baseUrl = url.replace(/\/\/+$/, '/');
151    }
152    const defaultsForRuntime = config_1.default.getDefaultValues(options);
153    lodash_1.default.defaultsDeep(config, defaultsForRuntime);
154    // split out our own app wide env from user env variables
155    // and delete envFile
156    config.env = parseEnv(config, options.env, resolved);
157    config.cypressEnv = process.env.CYPRESS_INTERNAL_ENV;
158    debug('using CYPRESS_INTERNAL_ENV %s', config.cypressEnv);
159    if (!isValidCypressInternalEnvValue(config.cypressEnv)) {
160        errors_1.default.throw('INVALID_CYPRESS_INTERNAL_ENV', config.cypressEnv);
161    }
162    delete config.envFile;
163    // when headless
164    if (config.isTextTerminal && !process.env.CYPRESS_INTERNAL_FORCE_FILEWATCH) {
165        // dont ever watch for file changes
166        config.watchForFileChanges = false;
167        // and forcibly reset numTestsKeptInMemory
168        // to zero
169        config.numTestsKeptInMemory = 0;
170    }
171    config = setResolvedConfigValues(config, defaultsForRuntime, resolved);
172    if (config.port) {
173        config = setUrls(config);
174    }
175    config = setAbsolutePaths(config);
176    config = setParentTestsPaths(config);
177    config = (0, exports.setNodeBinary)(config, (_a = options.args) === null || _a === void 0 ? void 0 : _a.userNodePath, (_b = options.args) === null || _b === void 0 ? void 0 : _b.userNodeVersion);
178    // validate config again here so that we catch configuration errors coming
179    // from the CLI overrides or env var overrides
180    config_1.default.validate(lodash_1.default.omit(config, 'browsers'), (errMsg) => {
181        return errors_1.default.throw('CONFIG_VALIDATION_ERROR', errMsg);
182    });
183    config_1.default.validateNoBreakingConfig(config, errors_1.default.warning, errors_1.default.throw);
184    return setSupportFileAndFolder(config, defaultsForRuntime)
185        .then((obj) => (0, exports.setPluginsFile)(obj, defaultsForRuntime))
186        .then(setScaffoldPaths);
187}
188exports.mergeDefaults = mergeDefaults;
189function setResolvedConfigValues(config, defaults, resolved) {
190    const obj = lodash_1.default.clone(config);
191    obj.resolved = resolveConfigValues(config, defaults, resolved);
192    debug('resolved config is %o', obj.resolved.browsers);
193    return obj;
194}
195exports.setResolvedConfigValues = setResolvedConfigValues;
196// Given an object "resolvedObj" and a list of overrides in "obj"
197// marks all properties from "obj" inside "resolvedObj" using
198// {value: obj.val, from: "plugin"}
199function setPluginResolvedOn(resolvedObj, obj) {
200    return lodash_1.default.each(obj, (val, key) => {
201        if (lodash_1.default.isObject(val) && !lodash_1.default.isArray(val) && resolvedObj[key]) {
202            // recurse setting overrides
203            // inside of objected
204            return setPluginResolvedOn(resolvedObj[key], val);
205        }
206        const valueFrom = {
207            value: val,
208            from: 'plugin',
209        };
210        resolvedObj[key] = valueFrom;
211    });
212}
213exports.setPluginResolvedOn = setPluginResolvedOn;
214function updateWithPluginValues(cfg, overrides) {
215    if (!overrides) {
216        overrides = {};
217    }
218    debug('updateWithPluginValues %o', { cfg, overrides });
219    // make sure every option returned from the plugins file
220    // passes our validation functions
221    config_1.default.validate(overrides, (errMsg) => {
222        if (cfg.pluginsFile && cfg.projectRoot) {
223            const relativePluginsPath = path_1.default.relative(cfg.projectRoot, cfg.pluginsFile);
224            return errors_1.default.throw('PLUGINS_CONFIG_VALIDATION_ERROR', relativePluginsPath, errMsg);
225        }
226        return errors_1.default.throw('CONFIG_VALIDATION_ERROR', errMsg);
227    });
228    let originalResolvedBrowsers = cfg && cfg.resolved && cfg.resolved.browsers && lodash_1.default.cloneDeep(cfg.resolved.browsers);
229    if (!originalResolvedBrowsers) {
230        // have something to resolve with if plugins return nothing
231        originalResolvedBrowsers = {
232            value: cfg.browsers,
233            from: 'default',
234        };
235    }
236    const diffs = (0, return_deep_diff_1.default)(cfg, overrides, true);
237    debug('config diffs %o', diffs);
238    const userBrowserList = diffs && diffs.browsers && lodash_1.default.cloneDeep(diffs.browsers);
239    if (userBrowserList) {
240        debug('user browser list %o', userBrowserList);
241    }
242    // for each override go through
243    // and change the resolved values of cfg
244    // to point to the plugin
245    if (diffs) {
246        debug('resolved config before diffs %o', cfg.resolved);
247        setPluginResolvedOn(cfg.resolved, diffs);
248        debug('resolved config object %o', cfg.resolved);
249    }
250    // merge cfg into overrides
251    const merged = lodash_1.default.defaultsDeep(diffs, cfg);
252    debug('merged config object %o', merged);
253    // the above _.defaultsDeep combines arrays,
254    // if diffs.browsers = [1] and cfg.browsers = [1, 2]
255    // then the merged result merged.browsers = [1, 2]
256    // which is NOT what we want
257    if (Array.isArray(userBrowserList) && userBrowserList.length) {
258        merged.browsers = userBrowserList;
259        merged.resolved.browsers.value = userBrowserList;
260    }
261    if (overrides.browsers === null) {
262        // null breaks everything when merging lists
263        debug('replacing null browsers with original list %o', originalResolvedBrowsers);
264        merged.browsers = cfg.browsers;
265        if (originalResolvedBrowsers) {
266            merged.resolved.browsers = originalResolvedBrowsers;
267        }
268    }
269    debug('merged plugins config %o', merged);
270    return merged;
271}
272exports.updateWithPluginValues = updateWithPluginValues;
273// combines the default configuration object with values specified in the
274// configuration file like "cypress.json". Values in configuration file
275// overwrite the defaults.
276function resolveConfigValues(config, defaults, resolved = {}) {
277    // pick out only known configuration keys
278    return lodash_1.default
279        .chain(config)
280        .pick(config_1.default.getPublicConfigKeys())
281        .mapValues((val, key) => {
282        let r;
283        const source = (s) => {
284            return {
285                value: val,
286                from: s,
287            };
288        };
289        r = resolved[key];
290        if (r) {
291            if (lodash_1.default.isObject(r)) {
292                return r;
293            }
294            return source(r);
295        }
296        if (!(!lodash_1.default.isEqual(config[key], defaults[key]) && key !== 'browsers')) {
297            // "browsers" list is special, since it is dynamic by default
298            // and can only be overwritten via plugins file
299            return source('default');
300        }
301        return source('config');
302    }).value();
303}
304exports.resolveConfigValues = resolveConfigValues;
305// instead of the built-in Node process, specify a path to 3rd party Node
306const setNodeBinary = (obj, userNodePath, userNodeVersion) => {
307    // if execPath isn't found we weren't executed from the CLI and should used the bundled node version.
308    if (userNodePath && userNodeVersion && obj.nodeVersion !== 'bundled') {
309        obj.resolvedNodePath = userNodePath;
310        obj.resolvedNodeVersion = userNodeVersion;
311        return obj;
312    }
313    obj.resolvedNodeVersion = process.versions.node;
314    return obj;
315};
316exports.setNodeBinary = setNodeBinary;
317function setScaffoldPaths(obj) {
318    obj = lodash_1.default.clone(obj);
319    debug('set scaffold paths');
320    return scaffold_1.default.fileTree(obj)
321        .then((fileTree) => {
322        debug('got file tree');
323        obj.scaffoldedFiles = fileTree;
324        return obj;
325    });
326}
327exports.setScaffoldPaths = setScaffoldPaths;
328// async function
329function setSupportFileAndFolder(obj, defaults) {
330    if (!obj.supportFile) {
331        return bluebird_1.default.resolve(obj);
332    }
333    obj = lodash_1.default.clone(obj);
334    // TODO move this logic to find support file into util/path_helpers
335    const sf = obj.supportFile;
336    debug(`setting support file ${sf}`);
337    debug(`for project root ${obj.projectRoot}`);
338    return bluebird_1.default
339        .try(() => {
340        // resolve full path with extension
341        obj.supportFile = exports.utils.resolveModule(sf);
342        return debug('resolved support file %s', obj.supportFile);
343    }).then(() => {
344        if (!path_helpers_1.default.checkIfResolveChangedRootFolder(obj.supportFile, sf)) {
345            return;
346        }
347        debug('require.resolve switched support folder from %s to %s', sf, obj.supportFile);
348        // this means the path was probably symlinked, like
349        // /tmp/foo -> /private/tmp/foo
350        // which can confuse the rest of the code
351        // switch it back to "normal" file
352        obj.supportFile = path_1.default.join(sf, path_1.default.basename(obj.supportFile));
353        return fs_1.fs.pathExists(obj.supportFile)
354            .then((found) => {
355            if (!found) {
356                errors_1.default.throw('SUPPORT_FILE_NOT_FOUND', obj.supportFile, obj.configFile || defaults.configFile);
357            }
358            return debug('switching to found file %s', obj.supportFile);
359        });
360    }).catch({ code: 'MODULE_NOT_FOUND' }, () => {
361        debug('support JS module %s does not load', sf);
362        const loadingDefaultSupportFile = sf === path_1.default.resolve(obj.projectRoot, defaults.supportFile);
363        return exports.utils.discoverModuleFile({
364            filename: sf,
365            isDefault: loadingDefaultSupportFile,
366            projectRoot: obj.projectRoot,
367        })
368            .then((result) => {
369            if (result === null) {
370                const configFile = obj.configFile || defaults.configFile;
371                return errors_1.default.throw('SUPPORT_FILE_NOT_FOUND', path_1.default.resolve(obj.projectRoot, sf), configFile);
372            }
373            debug('setting support file to %o', { result });
374            obj.supportFile = result;
375            return obj;
376        });
377    })
378        .then(() => {
379        if (obj.supportFile) {
380            // set config.supportFolder to its directory
381            obj.supportFolder = path_1.default.dirname(obj.supportFile);
382            debug(`set support folder ${obj.supportFolder}`);
383        }
384        return obj;
385    });
386}
387exports.setSupportFileAndFolder = setSupportFileAndFolder;
388// set pluginsFile to an absolute path with the following rules:
389// - do nothing if pluginsFile is falsey
390// - look up the absolute path via node, so 'cypress/plugins' can resolve
391//   to 'cypress/plugins/index.js' or 'cypress/plugins/index.coffee'
392// - if not found
393//   * and the pluginsFile is set to the default
394//     - and the path to the pluginsFile directory exists
395//       * assume the user doesn't need a pluginsFile, set it to false
396//         so it's ignored down the pipeline
397//     - and the path to the pluginsFile directory does not exist
398//       * set it to cypress/plugins/index.js, it will get scaffolded
399//   * and the pluginsFile is NOT set to the default
400//     - throw an error, because it should be there if the user
401//       explicitly set it
402exports.setPluginsFile = bluebird_1.default.method((obj, defaults) => {
403    if (!obj.pluginsFile) {
404        return obj;
405    }
406    obj = lodash_1.default.clone(obj);
407    const { pluginsFile, } = obj;
408    debug(`setting plugins file ${pluginsFile}`);
409    debug(`for project root ${obj.projectRoot}`);
410    return bluebird_1.default
411        .try(() => {
412        // resolve full path with extension
413        obj.pluginsFile = exports.utils.resolveModule(pluginsFile);
414        return debug(`set pluginsFile to ${obj.pluginsFile}`);
415    }).catch({ code: 'MODULE_NOT_FOUND' }, () => {
416        debug('plugins module does not exist %o', { pluginsFile });
417        const isLoadingDefaultPluginsFile = pluginsFile === path_1.default.resolve(obj.projectRoot, defaults.pluginsFile);
418        return exports.utils.discoverModuleFile({
419            filename: pluginsFile,
420            isDefault: isLoadingDefaultPluginsFile,
421            projectRoot: obj.projectRoot,
422        })
423            .then((result) => {
424            if (result === null) {
425                return errors_1.default.throw('PLUGINS_FILE_ERROR', path_1.default.resolve(obj.projectRoot, pluginsFile));
426            }
427            debug('setting plugins file to %o', { result });
428            obj.pluginsFile = result;
429            return obj;
430        });
431    }).return(obj);
432});
433function setParentTestsPaths(obj) {
434    // projectRoot:              "/path/to/project"
435    // integrationFolder:        "/path/to/project/cypress/integration"
436    // componentFolder:          "/path/to/project/cypress/components"
437    // parentTestsFolder:        "/path/to/project/cypress"
438    // parentTestsFolderDisplay: "project/cypress"
439    obj = lodash_1.default.clone(obj);
440    const ptfd = (obj.parentTestsFolder = path_1.default.dirname(obj.integrationFolder));
441    const prd = path_1.default.dirname(obj.projectRoot != null ? obj.projectRoot : '');
442    obj.parentTestsFolderDisplay = path_1.default.relative(prd, ptfd);
443    return obj;
444}
445exports.setParentTestsPaths = setParentTestsPaths;
446function setAbsolutePaths(obj) {
447    let pr;
448    obj = lodash_1.default.clone(obj);
449    // if we have a projectRoot
450    pr = obj.projectRoot;
451    if (pr) {
452        // reset fileServerFolder to be absolute
453        // obj.fileServerFolder = path.resolve(pr, obj.fileServerFolder)
454        // and do the same for all the rest
455        lodash_1.default.extend(obj, convertRelativeToAbsolutePaths(pr, obj));
456    }
457    return obj;
458}
459exports.setAbsolutePaths = setAbsolutePaths;
460function setUrls(obj) {
461    obj = lodash_1.default.clone(obj);
462    // TODO: rename this to be proxyServer
463    const proxyUrl = `http://localhost:${obj.port}`;
464    const rootUrl = obj.baseUrl ?
465        (0, origin_1.default)(obj.baseUrl)
466        :
467            proxyUrl;
468    lodash_1.default.extend(obj, {
469        proxyUrl,
470        browserUrl: rootUrl + obj.clientRoute,
471        reporterUrl: rootUrl + obj.reporterRoute,
472        xhrUrl: obj.namespace + obj.xhrRoute,
473    });
474    return obj;
475}
476exports.setUrls = setUrls;
477function parseEnv(cfg, envCLI, resolved = {}) {
478    const envVars = (resolved.env = {});
479    const resolveFrom = (from, obj = {}) => {
480        return lodash_1.default.each(obj, (val, key) => {
481            return envVars[key] = {
482                value: val,
483                from,
484            };
485        });
486    };
487    const envCfg = cfg.env != null ? cfg.env : {};
488    const envFile = cfg.envFile != null ? cfg.envFile : {};
489    let envProc = (0, config_2.getProcessEnvVars)(process.env) || {};
490    envCLI = envCLI != null ? envCLI : {};
491    const configFromEnv = lodash_1.default.reduce(envProc, (memo, val, key) => {
492        let cfgKey;
493        cfgKey = config_1.default.matchesConfigKey(key);
494        if (cfgKey) {
495            // only change the value if it hasn't been
496            // set by the CLI. override default + config
497            if (resolved[cfgKey] !== 'cli') {
498                cfg[cfgKey] = val;
499                resolved[cfgKey] = {
500                    value: val,
501                    from: 'env',
502                };
503            }
504            memo.push(key);
505        }
506        return memo;
507    }, []);
508    envProc = lodash_1.default.chain(envProc)
509        .omit(configFromEnv)
510        .mapValues(hideSpecialVals)
511        .value();
512    resolveFrom('config', envCfg);
513    resolveFrom('envFile', envFile);
514    resolveFrom('env', envProc);
515    resolveFrom('cli', envCLI);
516    // envCfg is from cypress.json
517    // envFile is from cypress.env.json
518    // envProc is from process env vars
519    // envCLI is from CLI arguments
520    return lodash_1.default.extend(envCfg, envFile, envProc, envCLI);
521}
522exports.parseEnv = parseEnv;
523function getResolvedRuntimeConfig(config, runtimeConfig) {
524    const resolvedRuntimeFields = lodash_1.default.mapValues(runtimeConfig, (v) => ({ value: v, from: 'runtime' }));
525    return Object.assign(Object.assign(Object.assign({}, config), runtimeConfig), { resolved: Object.assign(Object.assign({}, config.resolved), resolvedRuntimeFields) });
526}
527exports.getResolvedRuntimeConfig = getResolvedRuntimeConfig;
528function getNameFromRoot(root = '') {
529    return path_1.default.basename(root);
530}
531exports.getNameFromRoot = getNameFromRoot;
532
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

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

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

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

Test now for Free
LambdaTestX

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

Allow Cookie
Sarah

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

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

Sarah Elson (Product & Growth Lead)