All files / wdio-spec-reporter/src index.js

100% Statements 127/127
98.7% Branches 76/77
100% Functions 23/23
100% Lines 126/126

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367                  57x 57x     57x   57x 57x 57x 57x 57x           57x       1x 1x       1x 1x       2x 1x         1x       1x       1x       1x             7x 7x 7x     7x     7x 1x     6x                 6x 148x       6x             6x 4x     4x     2x                 8x     8x           8x                 43x                 8x                   9x 9x   9x   21x 2x       19x     19x   19x 19x 43x 43x 43x     43x       19x 19x       9x                 10x     10x 7x 7x 7x       10x 7x 7x 7x       10x 7x 7x     10x               9x 9x 9x   9x 22x 22x 22x 47x 33x     14x 14x   14x         14x 15x 15x 9x           9x               16x 9x     7x 7x 18x 39x 26x     13x       7x                 21x 21x                 47x   47x   25x 25x   7x 7x   14x 14x     47x                   69x   69x   32x 32x     15x 15x   21x 21x     69x                   26x 26x 26x 26x     26x 6x 6x   6x 2x     4x     20x 9x     11x          
import WDIOReporter from '@wdio/reporter'
import chalk from 'chalk'
import prettyMs from 'pretty-ms'
 
class SpecReporter extends WDIOReporter {
    constructor (options) {
        /**
         * make spec reporter to write to output stream by default
         */
        options = Object.assign({ stdout: true }, options)
        super(options)
 
        // Keep track of the order that suites were called
        this.suiteUids = []
 
        this.suites = []
        this.indents = 0
        this.suiteIndents = {}
        this.defaultTestIndent = '   '
        this.stateCounts = {
            passed : 0,
            failed : 0,
            skipped : 0
        }
 
        this.chalk = chalk
    }
 
    onSuiteStart (suite) {
        this.suiteUids.push(suite.uid)
        this.suiteIndents[suite.uid] = ++this.indents
    }
 
    onSuiteEnd (suite) {
        this.indents--
        this.suites.push(suite)
    }
 
    onHookEnd (hook) {
        if (hook.error) {
            this.stateCounts.failed++
        }
    }
 
    onTestPass () {
        this.stateCounts.passed++
    }
 
    onTestFail () {
        this.stateCounts.failed++
    }
 
    onTestSkip () {
        this.stateCounts.skipped++
    }
 
    onRunnerEnd (runner) {
        this.printReport(runner)
    }
 
    /**
     * Print the report to the screen
     */
    printReport(runner) {
        const duration = `(${prettyMs(runner._duration)})`
        const preface = `[${this.getEnviromentCombo(runner.capabilities, false, runner.isMultiremote).trim()} #${runner.cid}]`
        const divider = '------------------------------------------------------------------'
 
        // Get the results
        const results = this.getResultDisplay()
 
        // If there are no test results then return nothing
        if (results.length === 0) {
            return
        }
 
        const output = [
            ...this.getHeaderDisplay(runner),
            ...results,
            ...this.getCountDisplay(duration),
            ...this.getFailureDisplay(),
            ...this.getTestLink(runner)
        ]
 
        // Prefix all values with the browser information
        const prefacedOutput = output.map((value) => {
            return value ? `${preface} ${value}` : preface
        })
 
        // Output the results
        this.write(`${divider}\n${prefacedOutput.join('\n')}\n`)
    }
 
    /**
     * get link to saucelabs job
     */
    getTestLink ({ config, sessionId }) {
        if (config.hostname.includes('saucelabs')) {
            const dc = config.headless
                ? '.us-east-1'
                : ['eu', 'eu-central-1'].includes(config.region) ? '.eu-central-1' : ''
            return ['', `Check out job at https://app${dc}.saucelabs.com/tests/${sessionId}`]
        }
 
        return []
    }
 
    /**
     * Get the header display for the report
     * @param  {Object} runner Runner data
     * @return {Array}         Header data
     */
    getHeaderDisplay(runner) {
        const combo = this.getEnviromentCombo(runner.capabilities, undefined, runner.isMultiremote).trim()
 
        // Spec file name and enviroment information
        const output = [
            `Spec: ${runner.specs[0]}`,
            `Running: ${combo}`,
            '',
        ]
 
        return output
    }
 
    /**
     * returns everything worth reporting from a suite
     * @param  {Object}    suite  test suite containing tests and hooks
     * @return {Object[]}         list of events to report
     */
    getEventsToReport (suite) {
        return [
            /**
             * report all tests
             */
            ...suite.tests,
            /**
             * and only hooks that failed
             */
            ...suite.hooks
                .filter((hook) => Boolean(hook.error))
        ]
    }
 
    /**
     * Get the results from the tests
     * @param  {Array} suites Runner suites
     * @return {Array}        Display output list
     */
    getResultDisplay () {
        const output = []
        const suites = this.getOrderedSuites()
 
        for (const suite of suites) {
            // Don't do anything if a suite has no tests or sub suites
            if (suite.tests.length === 0 && suite.suites.length === 0 && suite.hooks.length === 0) {
                continue
            }
 
            // Get the indent/starting point for this suite
            const suiteIndent = this.indent(suite.uid)
 
            // Display the title of the suite
            output.push(`${suiteIndent}${suite.title}`)
 
            const eventsToReport = this.getEventsToReport(suite)
            for (const test of eventsToReport) {
                const testTitle = test.title
                const state = test.state
                const testIndent = `${this.defaultTestIndent}${suiteIndent}`
 
                // Output for a single test
                output.push(`${testIndent}${this.chalk[this.getColor(state)](this.getSymbol(state))} ${testTitle}`)
            }
 
            // Put a line break after each suite (only if tests exist in that suite)
            Eif (eventsToReport.length) {
                output.push('')
            }
        }
 
        return output
    }
 
    /**
     * Get the display for passing, failing and skipped
     * @param  {String} duration Duration string
     * @return {Array} Count display
     */
    getCountDisplay (duration) {
        const output = []
 
        // Get the passes
        if(this.stateCounts.passed > 0) {
            const text = `${this.stateCounts.passed} passing ${duration}`
            output.push(this.chalk[this.getColor('passed')](text))
            duration = ''
        }
 
        // Get the failures
        if(this.stateCounts.failed > 0) {
            const text = `${this.stateCounts.failed} failing ${duration}`.trim()
            output.push(this.chalk[this.getColor('failed')](text))
            duration = ''
        }
 
        // Get the skipped tests
        if(this.stateCounts.skipped > 0) {
            const text = `${this.stateCounts.skipped} skipped ${duration}`.trim()
            output.push(this.chalk[this.getColor('skipped')](text))
        }
 
        return output
    }
 
    /**
     * Get display for failed tests, e.g. stack trace
     * @return {Array} Stack trace output
     */
    getFailureDisplay () {
        let failureLength = 0
        const output = []
        const suites = this.getOrderedSuites()
 
        for (const suite of suites) {
            const suiteTitle = suite.title
            const eventsToReport = this.getEventsToReport(suite)
            for (const test of eventsToReport) {
                if(test.state !== 'failed') {
                    continue
                }
 
                const testTitle = test.title
                const errors = test.errors || [test.error]
                // If we get here then there is a failed test
                output.push(
                    '',
                    `${++failureLength}) ${suiteTitle} ${testTitle}`,
 
                )
                for (let error of errors) {
                    output.push(this.chalk.red(error.message))
                    if (error.stack) {
                        output.push(...error.stack.split(/\n/g).map(value => this.chalk.gray(value)))
                    }
                }
            }
        }
 
        return output
    }
 
    /**
     * Get suites in the order they were called
     * @return {Array} Ordered suites
     */
    getOrderedSuites () {
        if (this.orderedSuites) {
            return this.orderedSuites
        }
 
        this.orderedSuites = []
        for (const uid of this.suiteUids) {
            for (const suite of this.suites) {
                if (suite.uid !== uid) {
                    continue
                }
 
                this.orderedSuites.push(suite)
            }
        }
 
        return this.orderedSuites
    }
 
    /**
     * Indent a suite based on where how it's nested
     * @param  {String} uid Unique suite key
     * @return {String}     Spaces for indentation
     */
    indent (uid) {
        const indents = this.suiteIndents[uid]
        return indents === 0 ? '' : Array(indents).join('    ')
    }
 
    /**
     * Get a symbol based on state
     * @param  {String} state State of a test
     * @return {String}       Symbol to display
     */
    getSymbol (state) {
        let symbol = '?' // in case of an unknown state
 
        switch (state) {
        case 'passed':
            symbol = '✓'
            break
        case 'skipped':
            symbol = '-'
            break
        case 'failed':
            symbol = '✖'
            break
        }
 
        return symbol
    }
 
    /**
     * Get a color based on a given state
     * @param  {String} state Test state
     * @return {String}       State color
     */
    getColor (state) {
        // In case of an unknown state
        let color = null
 
        switch (state) {
        case 'passed':
            color = 'green'
            break
        case 'pending':
        case 'skipped':
            color = 'cyan'
            break
        case 'failed':
            color = 'red'
            break
        }
 
        return color
    }
 
    /**
     * Get information about the enviroment
     * @param  {Object}  caps    Enviroment details
     * @param  {Boolean} verbose
     * @return {String}          Enviroment string
     */
    getEnviromentCombo (caps, verbose = true, isMultiremote = false) {
        const device = caps.deviceName
        const browser = isMultiremote ? 'MultiremoteBrowser' : (caps.browserName || caps.browser)
        const version = caps.version || caps.platformVersion || caps.browser_version
        const platform = caps.os ? (caps.os + ' ' + caps.os_version) : (caps.platform || caps.platformName)
 
        // Mobile capabilities
        if (device) {
            const program = (caps.app || '').replace('sauce-storage:', '') || caps.browserName
            const executing = program ? `executing ${program}` : ''
 
            if (!verbose) {
                return `${device} ${platform} ${version}`
            }
 
            return `${device} on ${platform} ${version} ${executing}`.trim()
        }
 
        if (!verbose) {
            return (browser + ' ' + (version || '') + ' ' + (platform || '')).trim()
        }
 
        return browser + (version ? ` (v${version})` : '') + (platform ? ` on ${platform}` : '')
    }
}
 
export default SpecReporter