All files / wdio-jasmine-framework/src index.js

100% Statements 98/98
100% Branches 30/30
100% Functions 19/19
100% Lines 95/95

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            1x     1x 1x   1x             17x 17x 17x 17x 17x   17x       17x                 6x   6x 6x 6x   6x 6x 6x   6x 6x         6x         6x         6x                     6x         42x                     6x         6x 6x 1x 1x   6x 6x 1x 1x 1x     6x 6x 6x 6x 6x 6x   6x 6x   6x 6x       4x 4x 4x 2x   4x             26x     1x 1x 1x         4x   4x     1x     1x     1x     1x     4x       7x       7x 4x 4x 4x   4x 2x 2x     4x 1x 1x     4x 2x     4x 1x       7x       8x 8x   8x 6x     2x       4x 4x 4x 4x           2x 1x 1x               4x         1x 1x 1x 1x 1x          
import Jasmine from 'jasmine'
import { runTestInFiberContext, executeHooksWithArgs } from '@wdio/config'
import logger from '@wdio/logger'
 
import JasmineReporter from './reporter'
 
const INTERFACES = {
    bdd: ['beforeAll', 'beforeEach', 'it', 'xit', 'fit', 'afterEach', 'afterAll']
}
const NOOP = function noop () {}
const DEFAULT_TIMEOUT_INTERVAL = 60000
 
const log = logger('@wdio/jasmine-framework')
 
/**
 * Jasmine 2.x runner
 */
class JasmineAdapter {
    constructor (cid, config, specs, capabilities, reporter) {
        this.cid = cid
        this.config = config
        this.capabilities = capabilities
        this.specs = specs
        this.jrunner = {}
 
        this.jasmineNodeOpts = Object.assign({
            cleanStack: true
        }, config.jasmineNodeOpts)
 
        this.reporter = new JasmineReporter(reporter, {
            cid: this.cid,
            capabilities: this.capabilities,
            specs: this.specs,
            cleanStack: this.jasmineNodeOpts.cleanStack
        })
    }
 
    async run () {
        const self = this
 
        this.jrunner = new Jasmine()
        const { jasmine } = this.jrunner
        const jasmineEnv = jasmine.getEnv()
 
        this.jrunner.projectBaseDir = ''
        this.jrunner.specDir = ''
        this.jrunner.addSpecFiles(this.specs)
 
        jasmine.DEFAULT_TIMEOUT_INTERVAL = this.jasmineNodeOpts.defaultTimeoutInterval || DEFAULT_TIMEOUT_INTERVAL
        jasmineEnv.addReporter(this.reporter)
 
        /**
         * Set whether to stop suite execution when a spec fails
         */
        const stopOnSpecFailure = !!this.jasmineNodeOpts.stopOnSpecFailure
 
        /**
         * Set whether to stop spec execution when an expectation fails
        */
        const stopSpecOnExpectationFailure = !!this.jasmineNodeOpts.stopSpecOnExpectationFailure
 
        /**
         * Filter specs to run based on jasmineNodeOpts.grep and jasmineNodeOpts.invert
         */
        jasmineEnv.configure({
            specFilter: ::this.customSpecFilter,
            stopOnSpecFailure: stopOnSpecFailure,
            random: Boolean(this.jasmineNodeOpts.random),
            oneFailurePerSpec: stopSpecOnExpectationFailure,
            failFast: this.jasmineNodeOpts.failFast
        })
 
        /**
         * enable expectHandler
         */
        jasmine.Spec.prototype.addExpectationResult = this.getExpectationResultHandler(jasmine)
 
        /**
         * wrap commands with wdio-sync
         */
        INTERFACES['bdd'].forEach((fnName) => runTestInFiberContext(
            ['it', 'fit', 'xit'],
            this.config.beforeHook,
            this.config.afterHook,
            fnName
        ))
 
        /**
         * for a clean stdout we need to avoid that Jasmine initialises the
         * default reporter
         */
        Jasmine.prototype.configureDefaultReporter = NOOP
 
        /**
         * wrap Suite and Spec prototypes to get access to their data
         */
        let beforeAllMock = jasmine.Suite.prototype.beforeAll
        jasmine.Suite.prototype.beforeAll = function (...args) {
            self.lastSpec = this.result
            beforeAllMock.apply(this, args)
        }
        let executeMock = jasmine.Spec.prototype.execute
        jasmine.Spec.prototype.execute = function (...args) {
            self.lastTest = this.result
            self.lastTest.start = new Date().getTime()
            executeMock.apply(this, args)
        }
 
        await executeHooksWithArgs(this.config.before, [this.capabilities, this.specs])
        let result = await new Promise((resolve) => {
            this.jrunner.env.beforeAll(this.wrapHook('beforeSuite'))
            this.jrunner.env.beforeEach(this.wrapHook('beforeTest'))
            this.jrunner.env.afterEach(this.wrapHook('afterTest'))
            this.jrunner.env.afterAll(this.wrapHook('afterSuite'))
 
            this.jrunner.onComplete(() => resolve(this.reporter.getFailedCount()))
            this.jrunner.execute()
        })
        await executeHooksWithArgs(this.config.after, [result, this.capabilities, this.specs])
        return result
    }
 
    customSpecFilter (spec) {
        const { grep, invertGrep } = this.jasmineNodeOpts
        const grepMatch = !grep || spec.getFullName().match(new RegExp(grep)) !== null
        if (grepMatch === Boolean(invertGrep)) {
            spec.pend()
        }
        return true
    }
 
    /**
     * Hooks which are added as true Mocha hooks need to call done() to notify async
     */
    wrapHook (hookName) {
        return (done) => executeHooksWithArgs(
            this.config[hookName],
            this.prepareMessage(hookName)
        ).then(() => done(), (e) => {
            log.info(`Error in ${hookName} hook: ${e.stack.slice(7)}`)
            done()
        })
    }
 
    prepareMessage (hookName) {
        const params = { type: hookName }
 
        switch (hookName) {
        case 'beforeSuite':
        case 'afterSuite':
            params.payload = Object.assign({
                file: this.jrunner.specFiles[0]
            }, this.lastSpec)
            break
        case 'beforeTest':
        case 'afterTest':
            params.payload = Object.assign({
                file: this.jrunner.specFiles[0]
            }, this.lastTest)
            break
        }
 
        return this.formatMessage(params)
    }
 
    formatMessage (params) {
        let message = {
            type: params.type
        }
 
        if (params.payload) {
            message.title = params.payload.description
            message.fullName = params.payload.fullName || null
            message.file = params.payload.file
 
            if (params.payload.failedExpectations && params.payload.failedExpectations.length) {
                message.errors = params.payload.failedExpectations
                message.error = params.payload.failedExpectations[0]
            }
 
            if (params.payload.id && params.payload.id.startsWith('spec')) {
                message.parent = this.lastSpec.description
                message.passed = params.payload.failedExpectations.length === 0
            }
 
            if (params.type === 'afterTest') {
                message.duration = new Date().getTime() - params.payload.start
            }
 
            if (typeof params.payload.duration === 'number') {
                message.duration = params.payload.duration
            }
        }
 
        return message
    }
 
    getExpectationResultHandler (jasmine) {
        let { expectationResultHandler } = this.jasmineNodeOpts
        const origHandler = jasmine.Spec.prototype.addExpectationResult
 
        if (typeof expectationResultHandler !== 'function') {
            return origHandler
        }
 
        return this.expectationResultHandler(origHandler)
    }
 
    expectationResultHandler (origHandler) {
        const { expectationResultHandler } = this.jasmineNodeOpts
        return function (passed, data) {
            try {
                expectationResultHandler.call(this, passed, data)
            } catch (e) {
                /**
                 * propagate expectationResultHandler error if actual assertion passed
                 * but the custom handler decides to throw
                 */
                if (passed) {
                    passed = false
                    data = {
                        passed: false,
                        message: 'expectationResultHandlerError: ' + e.message,
                        error: e
                    }
                }
            }
 
            return origHandler.call(this, passed, data)
        }
    }
}
 
const adapterFactory = {}
adapterFactory.run = async function (...args) {
    const adapter = new JasmineAdapter(...args)
    const result = await adapter.run()
    return result
}
 
export default adapterFactory
export { JasmineAdapter, adapterFactory }