All files / wdio-utils/src initialisePlugin.js

100% Statements 16/16
100% Branches 7/7
100% Functions 2/2
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58              16x 16x   8x     8x 8x   1x                           10x 2x 2x           8x 8x 2x           6x 5x 3x     2x            
/**
 * Allows to safely require a package, it only throws if the package was found
 * but failed to load due to syntax errors
 * @param  {string} name  of package
 * @return {object}       package content
 */
function safeRequire (name) {
    try {
        require.resolve(name)
    } catch (e) {
        return null
    }
 
    try {
        return require(name)
    } catch (e) {
        throw new Error(`Couldn't initialise "${name}".\n${e.stack}`)
    }
}
 
/**
 * initialise WebdriverIO compliant plugins like reporter or services in the following way:
 * 1. if package name is scoped (starts with "@"), require scoped package name
 * 2. otherwise try to require "@wdio/<name>-<type>"
 * 3. otherwise try to require "wdio-<name>-<type>"
 */
export default function initialisePlugin (name, type, target = 'default') {
    /**
     * directly import packages that are scoped
     */
    if (name[0] === '@') {
        const service = safeRequire(name)
        return service[target]
    }
 
    /**
     * check for scoped version of plugin first (e.g. @wdio/sauce-service)
     */
    const scopedPlugin = safeRequire(`@wdio/${name.toLowerCase()}-${type}`)
    if (scopedPlugin) {
        return scopedPlugin[target]
    }
 
    /**
     * check for old type of
     */
    const plugin = safeRequire(`wdio-${name.toLowerCase()}-${type}`)
    if (plugin) {
        return plugin[target]
    }
 
    throw new Error(
        `Couldn't find plugin "${name}" ${type}, neither as wdio scoped package `+
        `"@wdio/${name.toLowerCase()}-${type}" nor as community package ` +
        `"wdio-${name.toLowerCase()}-${type}". Please make sure you have it installed!`
    )
}