How to use buildNewConfigString method in Webdriverio

Best JavaScript code snippet using webdriverio-monorepo

Run Webdriverio automation tests on LambdaTest cloud grid

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

utils.js

Source: utils.js Github

copy
1import logger from '@wdio/logger'
2
3const log = logger('@wdio/cli:utils')
4
5/**
6 * run service launch sequences
7 */
8export async function runServiceHook (launcher, hookName, ...args) {
9    try {
10        return await Promise.all(launcher.map((service) => {
11            if (typeof service[hookName] === 'function') {
12                return service[hookName](...args)
13            }
14        }))
15    } catch (e) {
16        log.error(`A service failed in the '${hookName}' hook\n${e.stack}\n\nContinue...`)
17    }
18}
19
20/**
21 * Run onPrepareHook in Launcher
22 * @param {Array|Function} onPrepareHook - can be array of functions or single function
23 * @param {Object} config
24 * @param {Object} capabilities
25 */
26export async function runOnPrepareHook(onPrepareHook, config, capabilities) {
27    const catchFn = (e) => log.error(`Error in onPrepareHook: ${e.stack}`)
28
29    if (typeof onPrepareHook === 'function') {
30        onPrepareHook = [onPrepareHook]
31    }
32
33    return Promise.all(onPrepareHook.map((hook) => {
34        try {
35            return hook(config, capabilities)
36        } catch (e) {
37            return catchFn(e)
38        }
39    })).catch(catchFn)
40}
41
42/**
43 * Run onCompleteHook in Launcher
44 * @param {Array|Function} onCompleteHook - can be array of functions or single function
45 * @param {*} config
46 * @param {*} capabilities
47 * @param {*} exitCode
48 * @param {*} results
49 */
50export async function runOnCompleteHook(onCompleteHook, config, capabilities, exitCode, results) {
51    if (typeof onCompleteHook === 'function') {
52        onCompleteHook = [onCompleteHook]
53    }
54
55    return Promise.all(onCompleteHook.map(async (hook) => {
56        try {
57            await hook(exitCode, config, capabilities, results)
58            return 0
59        } catch (e) {
60            log.error(`Error in onCompleteHook: ${e.stack}`)
61            return 1
62        }
63    }))
64}
65
66/**
67 * map package names
68 * used in the CLI to find the name of the package for different questions
69 * answers.framework {String}
70 * answers.reporters | answer.services {Array<string>}
71 */
72export function getNpmPackageName(pkgLabels) {
73    if (typeof pkgLabels === 'string') {
74        return pkgLabels.split('/package/')[1]
75    }
76
77    return pkgLabels.map(pkgLabel => pkgLabel.split('/package/')[1])
78}
79
80export function getPackageName(pkg) {
81    return pkg.trim().split(' -')[0]
82}
83
84/**
85 * get runner identification by caps
86 */
87export function getRunnerName (caps = {}) {
88    let runner =
89        caps.browserName ||
90        caps.appPackage ||
91        caps.appWaitActivity ||
92        caps.app ||
93        caps.platformName
94
95    // MultiRemote
96    if (!runner) {
97        runner = Object.values(caps).length === 0 || Object.values(caps).some(cap => !cap.capabilities) ? 'undefined' : 'MultiRemote'
98    }
99
100    return runner
101}
102
103/**
104 * used by the install command to better find the package to install
105 */
106export function parseInstallNameAndPackage(list) {
107    const returnObj = {}
108
109    for(let item of list) {
110        returnObj[getPackageName(item)] = getNpmPackageName(item)
111    }
112
113    return returnObj
114}
115
116function buildNewConfigArray(str, type, change) {
117    const newStr = str
118        .split(`${type}s: `)[1]
119        .replace('\'', '')
120
121    let newArray = newStr.match(/(\w*)/gmi).filter(e => !!e).concat([change])
122
123    return str
124        .replace('// ', '')
125        .replace(
126            new RegExp(`(${type}s: )((.*\\s*)*)`), `$1[${newArray.map(e => `'${e}'`)}]`
127        )
128}
129
130function buildNewConfigString(str, type, change) {
131    return str.replace(new RegExp(`(${type}: )('\\w*')`), `$1'${change}'`)
132}
133
134export function findInConfig(config, type) {
135    let regexStr = `[\\/\\/]*[\\s]*${type}s: [\\s]*\\[([\\s]*['|"]\\w*['|"],*)*[\\s]*\\]`
136
137    if (type === 'framework') {
138        regexStr = `[\\/\\/]*[\\s]*${type}: ([\\s]*['|"]\\w*['|"])`
139    }
140
141    const regex = new RegExp(regexStr, 'gmi')
142
143    return config.match(regex)
144}
145
146export function replaceConfig(
147    config,
148    type,
149    name
150) {
151    const match = findInConfig(config, type)
152    if (match && match.length) {
153        if (type === 'framework') {
154            return buildNewConfigString(config, type, name)
155        }
156        const text = match.pop()
157
158        return config.replace(text, buildNewConfigArray(text, type, name))
159    }
160}
161
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 Webdriverio 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)