From b4cbe9850fbe192eaffeae450669f96e79a574ed Mon Sep 17 00:00:00 2001 From: Gregg Van Hove Date: Tue, 21 May 2019 17:44:38 -0700 Subject: [PATCH] add prettier and eslint --- .gitattributes | 1 + .jshintrc | 17 - Gruntfile.js | 7 +- grunt/config/jshint.js | 11 - lib/jasmine-core/jasmine-html.js | 355 +++-- lib/jasmine-core/jasmine.js | 1364 +++++++++++++------- package.json | 45 +- spec/core/AsyncExpectationSpec.js | 167 ++- spec/core/CallTrackerSpec.js | 62 +- spec/core/ClearStackSpec.js | 157 ++- spec/core/ClockSpec.js | 688 +++++++--- spec/core/DelayedFunctionSchedulerSpec.js | 77 +- spec/core/EnvSpec.js | 141 +- spec/core/ExceptionFormatterSpec.js | 83 +- spec/core/ExceptionsSpec.js | 27 +- spec/core/ExpectationFilterChainSpec.js | 32 +- spec/core/ExpectationResultSpec.js | 97 +- spec/core/ExpectationSpec.js | 373 +++--- spec/core/GlobalErrorsSpec.js | 136 +- spec/core/JsApiReporterSpec.js | 123 +- spec/core/MockDateSpec.js | 60 +- spec/core/PrettyPrintSpec.js | 343 +++-- spec/core/QueueRunnerSpec.js | 409 +++--- spec/core/ReportDispatcherSpec.js | 120 +- spec/core/SpecSpec.js | 276 ++-- spec/core/SpyRegistrySpec.js | 305 +++-- spec/core/SpySpec.js | 168 ++- spec/core/SpyStrategySpec.js | 261 ++-- spec/core/StackTraceSpec.js | 55 +- spec/core/SuiteSpec.js | 63 +- spec/core/TimerSpec.js | 10 +- spec/core/TreeProcessorSpec.js | 676 +++++----- spec/core/UserContextSpec.js | 7 +- spec/core/UtilSpec.js | 125 +- spec/core/baseSpec.js | 9 +- spec/core/formatErrorMsgSpec.js | 2 +- spec/helpers/BrowserFlags.js | 5 +- spec/helpers/asyncAwait.js | 7 +- spec/helpers/checkForMap.js | 33 +- spec/helpers/checkForSet.js | 33 +- spec/helpers/checkForSymbol.js | 3 +- spec/helpers/checkForTypedArrays.js | 13 +- spec/helpers/integrationMatchers.js | 30 +- spec/helpers/nodeDefineJasmineUnderTest.js | 22 +- spec/helpers/promises.js | 3 +- spec/html/HtmlReporterSpec.js | 1027 +++++++++------ spec/html/HtmlSpecFilterSpec.js | 19 +- spec/html/MatchersHtmlSpec.js | 13 +- spec/html/PrettyPrintHtmlSpec.js | 30 +- spec/html/QueryStringSpec.js | 70 +- spec/html/ResultsNodeSpec.js | 42 +- spec/html/SpyRegistryHtmlSpec.js | 6 +- spec/npmPackage/npmPackageSpec.js | 37 +- spec/performance/large_object_test.js | 20 +- spec/performance/performance_test.js | 6 +- src/core/CallTracker.js | 6 +- src/core/ClearStack.js | 6 +- src/core/Clock.js | 69 +- src/core/DelayedFunctionScheduler.js | 41 +- src/core/Env.js | 416 +++--- src/core/ExceptionFormatter.js | 17 +- src/core/Expectation.js | 21 +- src/core/ExpectationFilterChain.js | 9 +- src/core/ExpectationResult.js | 2 +- src/core/Expector.js | 47 +- src/core/GlobalErrors.js | 11 +- src/core/JsApiReporter.js | 3 +- src/core/MockDate.js | 39 +- src/core/Order.js | 15 +- src/core/PrettyPrinter.js | 94 +- src/core/QueueRunner.js | 47 +- src/core/ReportDispatcher.js | 10 +- src/core/Spec.js | 67 +- src/core/Spy.js | 73 +- src/core/SpyFactory.js | 4 +- src/core/SpyRegistry.js | 86 +- src/core/SpyStrategy.js | 26 +- src/core/StackTrace.js | 31 +- src/core/Suite.js | 22 +- src/core/Timer.js | 10 +- src/core/TreeProcessor.js | 97 +- src/core/UserContext.js | 5 +- src/core/base.js | 59 +- src/core/errors.js | 2 +- src/core/requireCore.js | 16 +- src/core/requireInterface.js | 2 +- src/core/util.js | 13 +- src/html/HtmlReporter.js | 339 +++-- src/html/HtmlSpecFilter.js | 5 +- src/html/QueryString.js | 11 +- 90 files changed, 6345 insertions(+), 3647 deletions(-) create mode 100644 .gitattributes delete mode 100644 .jshintrc delete mode 100644 grunt/config/jshint.js diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..6313b56c --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index 6c4da922..00000000 --- a/.jshintrc +++ /dev/null @@ -1,17 +0,0 @@ -{ - "bitwise": true, - "curly": true, - "globals": { - "clearTimeout": false, - "console": false, - "getJasmineRequireObj": true, - "jasmineRequire": true, - "setTimeout": false - }, - "immed": true, - "newcap": true, - "trailing": true, - "loopfunc": true, - "quotmark": "single", - "undef": true -} diff --git a/Gruntfile.js b/Gruntfile.js index fa22201d..14077d78 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -4,7 +4,6 @@ module.exports = function(grunt) { grunt.initConfig({ pkg: pkg, - jshint: require('./grunt/config/jshint.js'), concat: require('./grunt/config/concat.js'), sass: require('./grunt/config/sass.js'), compress: require('./grunt/config/compress.js'), @@ -15,7 +14,7 @@ module.exports = function(grunt) { grunt.loadTasks('grunt/tasks'); - grunt.registerTask('default', ['jshint:all', 'sass:dist', "cssUrlEmbed"]); + grunt.registerTask('default', ['sass:dist', "cssUrlEmbed"]); var version = require('./grunt/tasks/version.js'); @@ -28,9 +27,7 @@ module.exports = function(grunt) { [ 'sass:dist', "cssUrlEmbed", - 'jshint:beforeConcat', - 'concat', - 'jshint:afterConcat' + 'concat' ] ); diff --git a/grunt/config/jshint.js b/grunt/config/jshint.js deleted file mode 100644 index 253c739d..00000000 --- a/grunt/config/jshint.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = { - beforeConcat: ['src/**/*.js'], - afterConcat: [ - 'lib/jasmine-core/jasmine-html.js', - 'lib/jasmine-core/jasmine.js' - ], - options: { - jshintrc: '.jshintrc' - }, - all: ['src/**/*.js'] -}; diff --git a/lib/jasmine-core/jasmine-html.js b/lib/jasmine-core/jasmine-html.js index 3e6950d5..be86ad18 100644 --- a/lib/jasmine-core/jasmine-html.js +++ b/lib/jasmine-core/jasmine-html.js @@ -52,8 +52,7 @@ jasmineRequire.HtmlReporter = function(j$) { } }; - ResultsStateBuilder.prototype.specStarted = function(result) { - }; + ResultsStateBuilder.prototype.specStarted = function(result) {}; ResultsStateBuilder.prototype.specDone = function(result) { this.currentParent.addChild(result, 'spec'); @@ -71,15 +70,16 @@ jasmineRequire.HtmlReporter = function(j$) { } }; - - function HtmlReporter(options) { - var config = function() { return (options.env && options.env.configuration()) || {}; }, + var config = function() { + return (options.env && options.env.configuration()) || {}; + }, getContainer = options.getContainer, createElement = options.createElement, createTextNode = options.createTextNode, navigateWithNewParam = options.navigateWithNewParam || function() {}, - addToExistingQueryString = options.addToExistingQueryString || defaultQueryString, + addToExistingQueryString = + options.addToExistingQueryString || defaultQueryString, filterSpecs = options.filterSpecs, timer = options.timer || j$.noopTimer, htmlReporterMain, @@ -88,15 +88,25 @@ jasmineRequire.HtmlReporter = function(j$) { this.initialize = function() { clearPrior(); - htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'}, - createDom('div', {className: 'jasmine-banner'}, - createDom('a', {className: 'jasmine-title', href: 'http://jasmine.github.io/', target: '_blank'}), - createDom('span', {className: 'jasmine-version'}, j$.version) + htmlReporterMain = createDom( + 'div', + { className: 'jasmine_html-reporter' }, + createDom( + 'div', + { className: 'jasmine-banner' }, + createDom('a', { + className: 'jasmine-title', + href: 'http://jasmine.github.io/', + target: '_blank' + }), + createDom('span', { className: 'jasmine-version' }, j$.version) ), - createDom('ul', {className: 'jasmine-symbol-summary'}), - createDom('div', {className: 'jasmine-alert'}), - createDom('div', {className: 'jasmine-results'}, - createDom('div', {className: 'jasmine-failures'}) + createDom('ul', { className: 'jasmine-symbol-summary' }), + createDom('div', { className: 'jasmine-alert' }), + createDom( + 'div', + { className: 'jasmine-results' }, + createDom('div', { className: 'jasmine-failures' }) ) ); getContainer().appendChild(htmlReporterMain); @@ -108,7 +118,7 @@ jasmineRequire.HtmlReporter = function(j$) { timer.start(); }; - var summary = createDom('div', {className: 'jasmine-summary'}); + var summary = createDom('div', { className: 'jasmine-summary' }); var stateBuilder = new ResultsStateBuilder(); @@ -133,20 +143,25 @@ jasmineRequire.HtmlReporter = function(j$) { this.specDone = function(result) { stateBuilder.specDone(result); - if(noExpectations(result) && typeof console !== 'undefined' && typeof console.error !== 'undefined') { - console.error('Spec \'' + result.fullName + '\' has no expectations.'); + if ( + noExpectations(result) && + typeof console !== 'undefined' && + typeof console.error !== 'undefined' + ) { + console.error("Spec '" + result.fullName + "' has no expectations."); } if (!symbols) { symbols = find('.jasmine-symbol-summary'); } - symbols.appendChild(createDom('li', { + symbols.appendChild( + createDom('li', { className: this.displaySpecInCorrectFormat(result), id: 'spec_' + result.id, title: result.fullName - } - )); + }) + ); if (result.status === 'failed') { failures.push(failureDom(result)); @@ -156,12 +171,16 @@ jasmineRequire.HtmlReporter = function(j$) { }; this.displaySpecInCorrectFormat = function(result) { - return noExpectations(result) ? 'jasmine-empty' : this.resultStatus(result.status); + return noExpectations(result) + ? 'jasmine-empty' + : this.resultStatus(result.status); }; this.resultStatus = function(status) { - if(status === 'excluded') { - return config().hideDisabled ? 'jasmine-excluded-no-display' : 'jasmine-excluded'; + if (status === 'excluded') { + return config().hideDisabled + ? 'jasmine-excluded-no-display' + : 'jasmine-excluded'; } return 'jasmine-' + status; }; @@ -171,16 +190,33 @@ jasmineRequire.HtmlReporter = function(j$) { var alert = find('.jasmine-alert'); var order = doneResult && doneResult.order; var i; - alert.appendChild(createDom('span', {className: 'jasmine-duration'}, 'finished in ' + timer.elapsed() / 1000 + 's')); + alert.appendChild( + createDom( + 'span', + { className: 'jasmine-duration' }, + 'finished in ' + timer.elapsed() / 1000 + 's' + ) + ); banner.appendChild(optionsMenu(config())); if (stateBuilder.specsExecuted < totalSpecsDefined) { - var skippedMessage = 'Ran ' + stateBuilder.specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all'; + var skippedMessage = + 'Ran ' + + stateBuilder.specsExecuted + + ' of ' + + totalSpecsDefined + + ' specs - run all'; var skippedLink = addToExistingQueryString('spec', ''); alert.appendChild( - createDom('span', {className: 'jasmine-bar jasmine-skipped'}, - createDom('a', {href: skippedLink, title: 'Run all specs'}, skippedMessage) + createDom( + 'span', + { className: 'jasmine-bar jasmine-skipped' }, + createDom( + 'a', + { href: skippedLink, title: 'Run all specs' }, + skippedMessage + ) ) ); } @@ -190,34 +226,66 @@ jasmineRequire.HtmlReporter = function(j$) { var failed = stateBuilder.failureCount + globalFailures.length > 0; if (totalSpecsDefined > 0 || failed) { - statusBarMessage += pluralize('spec', stateBuilder.specsExecuted) + ', ' + pluralize('failure', stateBuilder.failureCount); - if (stateBuilder.pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', stateBuilder.pendingSpecCount); } + statusBarMessage += + pluralize('spec', stateBuilder.specsExecuted) + + ', ' + + pluralize('failure', stateBuilder.failureCount); + if (stateBuilder.pendingSpecCount) { + statusBarMessage += + ', ' + pluralize('pending spec', stateBuilder.pendingSpecCount); + } } if (doneResult.overallStatus === 'passed') { statusBarClassName += ' jasmine-passed '; } else if (doneResult.overallStatus === 'incomplete') { statusBarClassName += ' jasmine-incomplete '; - statusBarMessage = 'Incomplete: ' + doneResult.incompleteReason + ', ' + statusBarMessage; + statusBarMessage = + 'Incomplete: ' + + doneResult.incompleteReason + + ', ' + + statusBarMessage; } else { statusBarClassName += ' jasmine-failed '; } var seedBar; if (order && order.random) { - seedBar = createDom('span', {className: 'jasmine-seed-bar'}, + seedBar = createDom( + 'span', + { className: 'jasmine-seed-bar' }, ', randomized with seed ', - createDom('a', {title: 'randomized with seed ' + order.seed, href: seedHref(order.seed)}, order.seed) + createDom( + 'a', + { + title: 'randomized with seed ' + order.seed, + href: seedHref(order.seed) + }, + order.seed + ) ); } - alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage, seedBar)); + alert.appendChild( + createDom( + 'span', + { className: statusBarClassName }, + statusBarMessage, + seedBar + ) + ); var errorBarClassName = 'jasmine-bar jasmine-errored'; var afterAllMessagePrefix = 'AfterAll '; - for(i = 0; i < globalFailures.length; i++) { - alert.appendChild(createDom('span', {className: errorBarClassName}, globalFailureMessage(globalFailures[i]))); + for (i = 0; i < globalFailures.length; i++) { + alert.appendChild( + createDom( + 'span', + { className: errorBarClassName }, + globalFailureMessage(globalFailures[i]) + ) + ); } function globalFailureMessage(failure) { @@ -225,7 +293,9 @@ jasmineRequire.HtmlReporter = function(j$) { var prefix = 'Error during loading: ' + failure.message; if (failure.filename) { - return prefix + ' in ' + failure.filename + ' line ' + failure.lineno; + return ( + prefix + ' in ' + failure.filename + ' line ' + failure.lineno + ); } else { return prefix; } @@ -237,9 +307,15 @@ jasmineRequire.HtmlReporter = function(j$) { addDeprecationWarnings(doneResult); var warningBarClassName = 'jasmine-bar jasmine-warning'; - for(i = 0; i < deprecationWarnings.length; i++) { + for (i = 0; i < deprecationWarnings.length; i++) { var warning = deprecationWarnings[i]; - alert.appendChild(createDom('span', {className: warningBarClassName}, 'DEPRECATION: ' + warning)); + alert.appendChild( + createDom( + 'span', + { className: warningBarClassName }, + 'DEPRECATION: ' + warning + ) + ); } var results = find('.jasmine-results'); @@ -249,13 +325,29 @@ jasmineRequire.HtmlReporter = function(j$) { if (failures.length) { alert.appendChild( - createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-spec-list'}, + createDom( + 'span', + { className: 'jasmine-menu jasmine-bar jasmine-spec-list' }, createDom('span', {}, 'Spec List | '), - createDom('a', {className: 'jasmine-failures-menu', href: '#'}, 'Failures'))); + createDom( + 'a', + { className: 'jasmine-failures-menu', href: '#' }, + 'Failures' + ) + ) + ); alert.appendChild( - createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-failure-list'}, - createDom('a', {className: 'jasmine-spec-list-menu', href: '#'}, 'Spec List'), - createDom('span', {}, ' | Failures '))); + createDom( + 'span', + { className: 'jasmine-menu jasmine-bar jasmine-failure-list' }, + createDom( + 'a', + { className: 'jasmine-spec-list-menu', href: '#' }, + 'Spec List' + ), + createDom('span', {}, ' | Failures ') + ) + ); find('.jasmine-failures-menu').onclick = function() { setMenuModeTo('jasmine-failure-list'); @@ -276,17 +368,30 @@ jasmineRequire.HtmlReporter = function(j$) { return this; function failureDom(result) { - var failure = - createDom('div', {className: 'jasmine-spec-detail jasmine-failed'}, - failureDescription(result, stateBuilder.currentParent), - createDom('div', {className: 'jasmine-messages'}) - ); + var failure = createDom( + 'div', + { className: 'jasmine-spec-detail jasmine-failed' }, + failureDescription(result, stateBuilder.currentParent), + createDom('div', { className: 'jasmine-messages' }) + ); var messages = failure.childNodes[1]; for (var i = 0; i < result.failedExpectations.length; i++) { var expectation = result.failedExpectations[i]; - messages.appendChild(createDom('div', {className: 'jasmine-result-message'}, expectation.message)); - messages.appendChild(createDom('div', {className: 'jasmine-stack-trace'}, expectation.stack)); + messages.appendChild( + createDom( + 'div', + { className: 'jasmine-result-message' }, + expectation.message + ) + ); + messages.appendChild( + createDom( + 'div', + { className: 'jasmine-stack-trace' }, + expectation.stack + ) + ); } return failure; @@ -300,9 +405,20 @@ jasmineRequire.HtmlReporter = function(j$) { continue; } if (resultNode.type === 'suite') { - var suiteListNode = createDom('ul', {className: 'jasmine-suite', id: 'suite-' + resultNode.result.id}, - createDom('li', {className: 'jasmine-suite-detail jasmine-' + resultNode.result.status}, - createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description) + var suiteListNode = createDom( + 'ul', + { className: 'jasmine-suite', id: 'suite-' + resultNode.result.id }, + createDom( + 'li', + { + className: + 'jasmine-suite-detail jasmine-' + resultNode.result.status + }, + createDom( + 'a', + { href: specHref(resultNode.result) }, + resultNode.result.description + ) ) ); @@ -311,22 +427,34 @@ jasmineRequire.HtmlReporter = function(j$) { } if (resultNode.type === 'spec') { if (domParent.getAttribute('class') !== 'jasmine-specs') { - specListNode = createDom('ul', {className: 'jasmine-specs'}); + specListNode = createDom('ul', { className: 'jasmine-specs' }); domParent.appendChild(specListNode); } var specDescription = resultNode.result.description; - if(noExpectations(resultNode.result)) { + if (noExpectations(resultNode.result)) { specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; } - if(resultNode.result.status === 'pending' && resultNode.result.pendingReason !== '') { - specDescription = specDescription + ' PENDING WITH MESSAGE: ' + resultNode.result.pendingReason; + if ( + resultNode.result.status === 'pending' && + resultNode.result.pendingReason !== '' + ) { + specDescription = + specDescription + + ' PENDING WITH MESSAGE: ' + + resultNode.result.pendingReason; } specListNode.appendChild( - createDom('li', { + createDom( + 'li', + { className: 'jasmine-' + resultNode.result.status, id: 'spec-' + resultNode.result.id }, - createDom('a', {href: specHref(resultNode.result)}, specDescription) + createDom( + 'a', + { href: specHref(resultNode.result) }, + specDescription + ) ) ); } @@ -334,37 +462,69 @@ jasmineRequire.HtmlReporter = function(j$) { } function optionsMenu(config) { - var optionsMenuDom = createDom('div', { className: 'jasmine-run-options' }, + var optionsMenuDom = createDom( + 'div', + { className: 'jasmine-run-options' }, createDom('span', { className: 'jasmine-trigger' }, 'Options'), - createDom('div', { className: 'jasmine-payload' }, - createDom('div', { className: 'jasmine-stop-on-failure' }, + createDom( + 'div', + { className: 'jasmine-payload' }, + createDom( + 'div', + { className: 'jasmine-stop-on-failure' }, createDom('input', { className: 'jasmine-fail-fast', id: 'jasmine-fail-fast', type: 'checkbox' }), - createDom('label', { className: 'jasmine-label', 'for': 'jasmine-fail-fast' }, 'stop execution on spec failure')), - createDom('div', { className: 'jasmine-throw-failures' }, + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-fail-fast' }, + 'stop execution on spec failure' + ) + ), + createDom( + 'div', + { className: 'jasmine-throw-failures' }, createDom('input', { className: 'jasmine-throw', id: 'jasmine-throw-failures', type: 'checkbox' }), - createDom('label', { className: 'jasmine-label', 'for': 'jasmine-throw-failures' }, 'stop spec on expectation failure')), - createDom('div', { className: 'jasmine-random-order' }, + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-throw-failures' }, + 'stop spec on expectation failure' + ) + ), + createDom( + 'div', + { className: 'jasmine-random-order' }, createDom('input', { className: 'jasmine-random', id: 'jasmine-random-order', type: 'checkbox' }), - createDom('label', { className: 'jasmine-label', 'for': 'jasmine-random-order' }, 'run tests in random order')), - createDom('div', { className: 'jasmine-hide-disabled' }, + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-random-order' }, + 'run tests in random order' + ) + ), + createDom( + 'div', + { className: 'jasmine-hide-disabled' }, createDom('input', { className: 'jasmine-disabled', id: 'jasmine-hide-disabled', type: 'checkbox' }), - createDom('label', { className: 'jasmine-label', 'for': 'jasmine-hide-disabled' }, 'hide disabled tests')) + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-hide-disabled' }, + 'hide disabled tests' + ) + ) ) ); @@ -374,13 +534,17 @@ jasmineRequire.HtmlReporter = function(j$) { navigateWithNewParam('failFast', !config.failFast); }; - var throwCheckbox = optionsMenuDom.querySelector('#jasmine-throw-failures'); + var throwCheckbox = optionsMenuDom.querySelector( + '#jasmine-throw-failures' + ); throwCheckbox.checked = config.oneFailurePerSpec; throwCheckbox.onclick = function() { navigateWithNewParam('throwFailures', !config.oneFailurePerSpec); }; - var randomCheckbox = optionsMenuDom.querySelector('#jasmine-random-order'); + var randomCheckbox = optionsMenuDom.querySelector( + '#jasmine-random-order' + ); randomCheckbox.checked = config.random; randomCheckbox.onclick = function() { navigateWithNewParam('random', !config.random); @@ -398,7 +562,10 @@ jasmineRequire.HtmlReporter = function(j$) { optionsTrigger.onclick = function() { if (isOpen.test(optionsPayload.className)) { - optionsPayload.className = optionsPayload.className.replace(isOpen, ''); + optionsPayload.className = optionsPayload.className.replace( + isOpen, + '' + ); } else { optionsPayload.className += ' jasmine-open'; } @@ -408,14 +575,24 @@ jasmineRequire.HtmlReporter = function(j$) { } function failureDescription(result, suite) { - var wrapper = createDom('div', {className: 'jasmine-description'}, - createDom('a', {title: result.description, href: specHref(result)}, result.description) + var wrapper = createDom( + 'div', + { className: 'jasmine-description' }, + createDom( + 'a', + { title: result.description, href: specHref(result) }, + result.description + ) ); var suiteLink; while (suite && suite.parent) { wrapper.insertBefore(createTextNode(' > '), wrapper.firstChild); - suiteLink = createDom('a', {href: suiteHref(suite)}, suite.result.description); + suiteLink = createDom( + 'a', + { href: suiteHref(suite) }, + suite.result.description + ); wrapper.insertBefore(suiteLink, wrapper.firstChild); suite = suite.parent; @@ -437,7 +614,7 @@ jasmineRequire.HtmlReporter = function(j$) { function addDeprecationWarnings(result) { if (result && result.deprecationWarnings) { - for(var i = 0; i < result.deprecationWarnings.length; i++) { + for (var i = 0; i < result.deprecationWarnings.length; i++) { var warning = result.deprecationWarnings[i].message; if (!j$.util.arrayContains(warning)) { deprecationWarnings.push(warning); @@ -454,7 +631,7 @@ jasmineRequire.HtmlReporter = function(j$) { // return the reporter var oldReporter = find(''); - if(oldReporter) { + if (oldReporter) { getContainer().removeChild(oldReporter); } } @@ -486,7 +663,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function pluralize(singular, count) { - var word = (count == 1 ? singular : singular + 's'); + var word = count == 1 ? singular : singular + 's'; return '' + count + ' ' + word; } @@ -508,8 +685,10 @@ jasmineRequire.HtmlReporter = function(j$) { } function noExpectations(result) { - return (result.failedExpectations.length + result.passedExpectations.length) === 0 && - result.status === 'passed'; + return ( + result.failedExpectations.length + result.passedExpectations.length === + 0 && result.status === 'passed' + ); } function hasActiveSpec(resultNode) { @@ -532,7 +711,10 @@ jasmineRequire.HtmlReporter = function(j$) { jasmineRequire.HtmlSpecFilter = function() { function HtmlSpecFilter(options) { - var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); + var filterString = + options && + options.filterString() && + options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); var filterPattern = new RegExp(filterString); this.matches = function(specName) { @@ -569,9 +751,11 @@ jasmineRequire.ResultsNode = function() { jasmineRequire.QueryString = function() { function QueryString(options) { - this.navigateWithNewParam = function(key, value) { - options.getWindowLocation().search = this.fullStringWithNewParam(key, value); + options.getWindowLocation().search = this.fullStringWithNewParam( + key, + value + ); }; this.fullStringWithNewParam = function(key, value) { @@ -589,7 +773,9 @@ jasmineRequire.QueryString = function() { function toQueryString(paramMap) { var qStrPairs = []; for (var prop in paramMap) { - qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop])); + qStrPairs.push( + encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]) + ); } return '?' + qStrPairs.join('&'); } @@ -613,7 +799,6 @@ jasmineRequire.QueryString = function() { return paramMap; } - } return QueryString; diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index 89c7e0c6..3bd8dd93 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -20,11 +20,15 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -var getJasmineRequireObj = (function (jasmineGlobal) { - /* globals exports, global, module, window */ +// eslint-disable-next-line no-unused-vars +var getJasmineRequireObj = (function(jasmineGlobal) { var jasmineRequire; - if (typeof module !== 'undefined' && module.exports && typeof exports !== 'undefined') { + if ( + typeof module !== 'undefined' && + module.exports && + typeof exports !== 'undefined' + ) { if (typeof global !== 'undefined') { jasmineGlobal = global; } else { @@ -32,7 +36,11 @@ var getJasmineRequireObj = (function (jasmineGlobal) { } jasmineRequire = exports; } else { - if (typeof window !== 'undefined' && typeof window.toString === 'function' && window.toString() === '[object GjsGlobal]') { + if ( + typeof window !== 'undefined' && + typeof window.toString === 'function' && + window.toString() === '[object GjsGlobal]' + ) { jasmineGlobal = window; } jasmineRequire = jasmineGlobal.jasmineRequire = {}; @@ -187,7 +195,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @return {Env} */ j$.getEnv = function(options) { - var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options); + var env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); //jasmine. singletons in here (setTimeout blah blah). return env; }; @@ -197,7 +205,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; j$.isObject_ = function(value) { - return !j$.util.isUndefined(value) && value !== null && j$.isA_('Object', value); + return ( + !j$.util.isUndefined(value) && value !== null && j$.isA_('Object', value) + ); }; j$.isString_ = function(value) { @@ -217,7 +227,8 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; j$.isTypedArray_ = function(value) { - return j$.isA_('Float32Array', value) || + return ( + j$.isA_('Float32Array', value) || j$.isA_('Float64Array', value) || j$.isA_('Int16Array', value) || j$.isA_('Int32Array', value) || @@ -225,7 +236,8 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { j$.isA_('Uint16Array', value) || j$.isA_('Uint32Array', value) || j$.isA_('Uint8Array', value) || - j$.isA_('Uint8ClampedArray', value); + j$.isA_('Uint8ClampedArray', value) + ); }; j$.isA_ = function(typeName, value) { @@ -255,9 +267,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { j$.isDomNode = function(obj) { // Node is a function, because constructors - return typeof jasmineGlobal.Node !== 'undefined' ? - obj instanceof jasmineGlobal.Node : - obj !== null && + return typeof jasmineGlobal.Node !== 'undefined' + ? obj instanceof jasmineGlobal.Node + : obj !== null && typeof obj === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string'; @@ -265,15 +277,25 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; j$.isMap = function(obj) { - return typeof jasmineGlobal.Map !== 'undefined' && obj.constructor === jasmineGlobal.Map; + return ( + typeof jasmineGlobal.Map !== 'undefined' && + obj.constructor === jasmineGlobal.Map + ); }; j$.isSet = function(obj) { - return typeof jasmineGlobal.Set !== 'undefined' && obj.constructor === jasmineGlobal.Set; + return ( + typeof jasmineGlobal.Set !== 'undefined' && + obj.constructor === jasmineGlobal.Set + ); }; j$.isPromise = function(obj) { - return typeof jasmineGlobal.Promise !== 'undefined' && !!obj && obj.constructor === jasmineGlobal.Promise; + return ( + typeof jasmineGlobal.Promise !== 'undefined' && + !!obj && + obj.constructor === jasmineGlobal.Promise + ); }; j$.isPromiseLike = function(obj) { @@ -285,7 +307,8 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return func.name; } - var matches = func.toString().match(/^\s*function\s*(\w+)\s*\(/) || + var matches = + func.toString().match(/^\s*function\s*(\w+)\s*\(/) || func.toString().match(/^\s*\[object\s*(\w+)Constructor\]/); return matches ? matches[1] : ''; @@ -318,7 +341,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @name jasmine.truthy * @function */ - j$.truthy = function() { return new j$.Truthy(); }; + j$.truthy = function() { + return new j$.Truthy(); + }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), @@ -326,7 +351,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @name jasmine.falsy * @function */ - j$.falsy = function() { return new j$.Falsy(); }; + j$.falsy = function() { + return new j$.Falsy(); + }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), @@ -334,7 +361,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @name jasmine.empty * @function */ - j$.empty = function() { return new j$.Empty(); }; + j$.empty = function() { + return new j$.Empty(); + }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), @@ -342,7 +371,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @name jasmine.notEmpty * @function */ - j$.notEmpty = function() { return new j$.NotEmpty(); }; + j$.notEmpty = function() { + return new j$.NotEmpty(); + }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), @@ -392,18 +423,18 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { if (!putativeSpy) { return false; } - return putativeSpy.and instanceof j$.SpyStrategy && - putativeSpy.calls instanceof j$.CallTracker; + return ( + putativeSpy.and instanceof j$.SpyStrategy && + putativeSpy.calls instanceof j$.CallTracker + ); }; }; getJasmineRequireObj().util = function(j$) { - var util = {}; util.inherit = function(childClass, parentClass) { - var Subclass = function() { - }; + var Subclass = function() {}; Subclass.prototype = parentClass.prototype; childClass.prototype = new Subclass(); }; @@ -412,7 +443,8 @@ getJasmineRequireObj().util = function(j$) { if (!str) { return str; } - return str.replace(/&/g, '&') + return str + .replace(/&/g, '&') .replace(//g, '>'); }; @@ -457,7 +489,7 @@ getJasmineRequireObj().util = function(j$) { util.cloneArgs = function(args) { var clonedArgs = []; var argsAsArray = j$.util.argsToArray(args); - for(var i = 0; i < argsAsArray.length; i++) { + for (var i = 0; i < argsAsArray.length; i++) { var str = Object.prototype.toString.apply(argsAsArray[i]), primitives = /^\[object (Boolean|String|RegExp|Number)/; @@ -499,7 +531,7 @@ getJasmineRequireObj().util = function(j$) { return Object.prototype.hasOwnProperty.call(obj, key); }; - util.errorWithStack = function errorWithStack () { + util.errorWithStack = function errorWithStack() { // Don't throw and catch if we don't have to, because it makes it harder // for users to debug their code with exception breakpoints. var error = new Error(); @@ -531,7 +563,7 @@ getJasmineRequireObj().util = function(j$) { return result; }; - }()); + })(); return util; }; @@ -544,13 +576,30 @@ getJasmineRequireObj().Spec = function(j$) { this.id = attrs.id; this.description = attrs.description || ''; this.queueableFn = attrs.queueableFn; - this.beforeAndAfterFns = attrs.beforeAndAfterFns || function() { return {befores: [], afters: []}; }; - this.userContext = attrs.userContext || function() { return {}; }; + this.beforeAndAfterFns = + attrs.beforeAndAfterFns || + function() { + return { befores: [], afters: [] }; + }; + this.userContext = + attrs.userContext || + function() { + return {}; + }; this.onStart = attrs.onStart || function() {}; - this.getSpecName = attrs.getSpecName || function() { return ''; }; - this.expectationResultFactory = attrs.expectationResultFactory || function() { }; + this.getSpecName = + attrs.getSpecName || + function() { + return ''; + }; + this.expectationResultFactory = + attrs.expectationResultFactory || function() {}; this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; - this.catchingExceptions = attrs.catchingExceptions || function() { return true; }; + this.catchingExceptions = + attrs.catchingExceptions || + function() { + return true; + }; this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.timer = attrs.timer || j$.noopTimer; @@ -628,12 +677,15 @@ getJasmineRequireObj().Spec = function(j$) { isLeaf: true, queueableFns: regularFns, cleanupFns: fns.afters, - onException: function () { + onException: function() { self.onException.apply(self, arguments); }, onComplete: function() { self.result.duration = self.timer.elapsed(); - onComplete(self.result.status === 'failed' && new j$.StopExecutionError('spec failed')); + onComplete( + self.result.status === 'failed' && + new j$.StopExecutionError('spec failed') + ); }, userContext: this.userContext() }; @@ -659,13 +711,17 @@ getJasmineRequireObj().Spec = function(j$) { return; } - this.addExpectationResult(false, { - matcherName: '', - passed: false, - expected: '', - actual: '', - error: e - }, true); + this.addExpectationResult( + false, + { + matcherName: '', + passed: false, + expected: '', + actual: '', + error: e + }, + true + ); }; Spec.prototype.pend = function(message) { @@ -704,13 +760,16 @@ getJasmineRequireObj().Spec = function(j$) { if (typeof deprecation === 'string') { deprecation = { message: deprecation }; } - this.result.deprecationWarnings.push(this.expectationResultFactory(deprecation)); + this.result.deprecationWarnings.push( + this.expectationResultFactory(deprecation) + ); }; var extractCustomPendingMessage = function(e) { var fullMessage = e.toString(), - boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), - boilerplateEnd = boilerplateStart + Spec.pendingSpecExceptionMessage.length; + boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), + boilerplateEnd = + boilerplateStart + Spec.pendingSpecExceptionMessage.length; return fullMessage.substr(boilerplateEnd); }; @@ -718,7 +777,11 @@ getJasmineRequireObj().Spec = function(j$) { Spec.pendingSpecExceptionMessage = '=> marked Pending'; Spec.isPendingSpecException = function(e) { - return !!(e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1); + return !!( + e && + e.toString && + e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 + ); }; return Spec; @@ -734,7 +797,7 @@ if (typeof window == void 0 && typeof exports == 'object') { getJasmineRequireObj().Order = function() { function Order(options) { this.random = 'random' in options ? options.random : true; - var seed = this.seed = options.seed || generateSeed(); + var seed = (this.seed = options.seed || generateSeed()); this.sort = this.random ? randomOrder : naturalOrder; function naturalOrder(items) { @@ -760,17 +823,16 @@ getJasmineRequireObj().Order = function() { function jenkinsHash(key) { var hash, i; - for(hash = i = 0; i < key.length; ++i) { + for (hash = i = 0; i < key.length; ++i) { hash += key.charCodeAt(i); - hash += (hash << 10); - hash ^= (hash >> 6); + hash += hash << 10; + hash ^= hash >> 6; } - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); + hash += hash << 3; + hash ^= hash >> 11; + hash += hash << 15; return hash; } - } return Order; @@ -795,7 +857,13 @@ getJasmineRequireObj().Env = function(j$) { var realSetTimeout = global.setTimeout; var realClearTimeout = global.clearTimeout; var clearStack = j$.getClearStack(global); - this.clock = new j$.Clock(global, function () { return new j$.DelayedFunctionScheduler(); }, new j$.MockDate(global)); + this.clock = new j$.Clock( + global, + function() { + return new j$.DelayedFunctionScheduler(); + }, + new j$.MockDate(global) + ); var runnableResources = {}; @@ -888,7 +956,13 @@ getJasmineRequireObj().Env = function(j$) { if (!options.suppressLoadErrors) { installGlobalErrors(); - globalErrors.pushListener(function(message, filename, lineno, colNo, err) { + globalErrors.pushListener(function( + message, + filename, + lineno, + colNo, + err + ) { topSuite.result.failedExpectations.push({ passed: false, globalErrorType: 'load', @@ -932,11 +1006,15 @@ getJasmineRequireObj().Env = function(j$) { } if (configuration.hasOwnProperty('Promise')) { - if (typeof configuration.Promise.resolve === 'function' && - typeof configuration.Promise.reject === 'function') { + if ( + typeof configuration.Promise.resolve === 'function' && + typeof configuration.Promise.reject === 'function' + ) { customPromise = configuration.Promise; } else { - throw new Error('Custom promise library missing `resolve`/`reject` functions'); + throw new Error( + 'Custom promise library missing `resolve`/`reject` functions' + ); } } }; @@ -957,34 +1035,47 @@ getJasmineRequireObj().Env = function(j$) { Object.defineProperty(this, 'specFilter', { get: function() { - self.deprecated('Getting specFilter directly from Env is deprecated and will be removed in a future version of Jasmine, please check the specFilter option from `configuration`'); + self.deprecated( + 'Getting specFilter directly from Env is deprecated and will be removed in a future version of Jasmine, please check the specFilter option from `configuration`' + ); return config.specFilter; }, set: function(val) { - self.deprecated('Setting specFilter directly on Env is deprecated and will be removed in a future version of Jasmine, please use the specFilter option in `configure`'); + self.deprecated( + 'Setting specFilter directly on Env is deprecated and will be removed in a future version of Jasmine, please use the specFilter option in `configure`' + ); config.specFilter = val; } }); this.addSpyStrategy = function(name, fn) { - if(!currentRunnable()) { - throw new Error('Custom spy strategies must be added in a before function or a spec'); + if (!currentRunnable()) { + throw new Error( + 'Custom spy strategies must be added in a before function or a spec' + ); } runnableResources[currentRunnable().id].customSpyStrategies[name] = fn; }; this.addCustomEqualityTester = function(tester) { - if(!currentRunnable()) { - throw new Error('Custom Equalities must be added in a before function or a spec'); + if (!currentRunnable()) { + throw new Error( + 'Custom Equalities must be added in a before function or a spec' + ); } - runnableResources[currentRunnable().id].customEqualityTesters.push(tester); + runnableResources[currentRunnable().id].customEqualityTesters.push( + tester + ); }; this.addMatchers = function(matchersToAdd) { - if(!currentRunnable()) { - throw new Error('Matchers must be added in a before function or a spec'); + if (!currentRunnable()) { + throw new Error( + 'Matchers must be added in a before function or a spec' + ); } - var customMatchers = runnableResources[currentRunnable().id].customMatchers; + var customMatchers = + runnableResources[currentRunnable().id].customMatchers; for (var matcherName in matchersToAdd) { customMatchers[matcherName] = matchersToAdd[matcherName]; } @@ -1031,19 +1122,28 @@ getJasmineRequireObj().Env = function(j$) { }; var defaultResourcesForRunnable = function(id, parentRunnableId) { - var resources = {spies: [], customEqualityTesters: [], customMatchers: {}, customSpyStrategies: {}}; + var resources = { + spies: [], + customEqualityTesters: [], + customMatchers: {}, + customSpyStrategies: {} + }; - if(runnableResources[parentRunnableId]) { - resources.customEqualityTesters = j$.util.clone(runnableResources[parentRunnableId].customEqualityTesters); - resources.customMatchers = j$.util.clone(runnableResources[parentRunnableId].customMatchers); + if (runnableResources[parentRunnableId]) { + resources.customEqualityTesters = j$.util.clone( + runnableResources[parentRunnableId].customEqualityTesters + ); + resources.customMatchers = j$.util.clone( + runnableResources[parentRunnableId].customMatchers + ); } runnableResources[id] = resources; }; var clearResourcesForRunnable = function(id) { - spyRegistry.clearSpies(); - delete runnableResources[id]; + spyRegistry.clearSpies(); + delete runnableResources[id]; }; var beforeAndAfterFns = function(suite) { @@ -1051,7 +1151,7 @@ getJasmineRequireObj().Env = function(j$) { var befores = [], afters = []; - while(suite) { + while (suite) { befores = befores.concat(suite.beforeFns); afters = afters.concat(suite.afterFns); @@ -1067,7 +1167,7 @@ getJasmineRequireObj().Env = function(j$) { var getSpecName = function(spec, suite) { var fullName = [spec.description], - suiteFullName = suite.getFullName(); + suiteFullName = suite.getFullName(); if (suiteFullName !== '') { fullName.unshift(suiteFullName); @@ -1077,13 +1177,13 @@ getJasmineRequireObj().Env = function(j$) { // TODO: we may just be able to pass in the fn instead of wrapping here var buildExpectationResult = j$.buildExpectationResult, - exceptionFormatter = new j$.ExceptionFormatter(), - expectationResultFactory = function(attrs) { - attrs.messageFormatter = exceptionFormatter.message; - attrs.stackFormatter = exceptionFormatter.stack; + exceptionFormatter = new j$.ExceptionFormatter(), + expectationResultFactory = function(attrs) { + attrs.messageFormatter = exceptionFormatter.message; + attrs.stackFormatter = exceptionFormatter.stack; - return buildExpectationResult(attrs); - }; + return buildExpectationResult(attrs); + }; /** * Sets whether Jasmine should throw an Error when an expectation fails. @@ -1094,12 +1194,16 @@ getJasmineRequireObj().Env = function(j$) { * @deprecated Use the `oneFailurePerSpec` option with {@link Env#configure} */ this.throwOnExpectationFailure = function(value) { - this.deprecated('Setting throwOnExpectationFailure directly on Env is deprecated and will be removed in a future version of Jasmine, please use the oneFailurePerSpec option in `configure`'); - this.configure({oneFailurePerSpec: !!value}); + this.deprecated( + 'Setting throwOnExpectationFailure directly on Env is deprecated and will be removed in a future version of Jasmine, please use the oneFailurePerSpec option in `configure`' + ); + this.configure({ oneFailurePerSpec: !!value }); }; this.throwingExpectationFailures = function() { - this.deprecated('Getting throwingExpectationFailures directly from Env is deprecated and will be removed in a future version of Jasmine, please check the oneFailurePerSpec option from `configuration`'); + this.deprecated( + 'Getting throwingExpectationFailures directly from Env is deprecated and will be removed in a future version of Jasmine, please check the oneFailurePerSpec option from `configuration`' + ); return config.oneFailurePerSpec; }; @@ -1111,12 +1215,16 @@ getJasmineRequireObj().Env = function(j$) { * @deprecated Use the `failFast` option with {@link Env#configure} */ this.stopOnSpecFailure = function(value) { - this.deprecated('Setting stopOnSpecFailure directly is deprecated and will be removed in a future version of Jasmine, please use the failFast option in `configure`'); - this.configure({failFast: !!value}); + this.deprecated( + 'Setting stopOnSpecFailure directly is deprecated and will be removed in a future version of Jasmine, please use the failFast option in `configure`' + ); + this.configure({ failFast: !!value }); }; this.stoppingOnSpecFailure = function() { - this.deprecated('Getting stoppingOnSpecFailure directly from Env is deprecated and will be removed in a future version of Jasmine, please check the failFast option from `configuration`'); + this.deprecated( + 'Getting stoppingOnSpecFailure directly from Env is deprecated and will be removed in a future version of Jasmine, please check the failFast option from `configuration`' + ); return config.failFast; }; @@ -1128,12 +1236,16 @@ getJasmineRequireObj().Env = function(j$) { * @deprecated Use the `random` option with {@link Env#configure} */ this.randomizeTests = function(value) { - this.deprecated('Setting randomizeTests directly is deprecated and will be removed in a future version of Jasmine, please use the random option in `configure`'); + this.deprecated( + 'Setting randomizeTests directly is deprecated and will be removed in a future version of Jasmine, please use the random option in `configure`' + ); config.random = !!value; }; this.randomTests = function() { - this.deprecated('Getting randomTests directly from Env is deprecated and will be removed in a future version of Jasmine, please check the random option from `configuration`'); + this.deprecated( + 'Getting randomTests directly from Env is deprecated and will be removed in a future version of Jasmine, please check the random option from `configuration`' + ); return config.random; }; @@ -1145,7 +1257,9 @@ getJasmineRequireObj().Env = function(j$) { * @deprecated Use the `seed` option with {@link Env#configure} */ this.seed = function(value) { - this.deprecated('Setting seed directly is deprecated and will be removed in a future version of Jasmine, please use the seed option in `configure`'); + this.deprecated( + 'Setting seed directly is deprecated and will be removed in a future version of Jasmine, please use the seed option in `configure`' + ); if (value) { config.seed = value; } @@ -1153,7 +1267,9 @@ getJasmineRequireObj().Env = function(j$) { }; this.hidingDisabled = function(value) { - this.deprecated('Getting hidingDisabled directly from Env is deprecated and will be removed in a future version of Jasmine, please check the hideDisabled option from `configuration`'); + this.deprecated( + 'Getting hidingDisabled directly from Env is deprecated and will be removed in a future version of Jasmine, please check the hideDisabled option from `configuration`' + ); return config.hideDisabled; }; @@ -1162,14 +1278,19 @@ getJasmineRequireObj().Env = function(j$) { * @function */ this.hideDisabled = function(value) { - this.deprecated('Setting hideDisabled directly is deprecated and will be removed in a future version of Jasmine, please use the hideDisabled option in `configure`'); + this.deprecated( + 'Setting hideDisabled directly is deprecated and will be removed in a future version of Jasmine, please use the hideDisabled option in `configure`' + ); config.hideDisabled = !!value; }; this.deprecated = function(deprecation) { var runnable = currentRunnable() || topSuite; runnable.addDeprecationWarning(deprecation); - if(typeof console !== 'undefined' && typeof console.error === 'function') { + if ( + typeof console !== 'undefined' && + typeof console.error === 'function' + ) { console.error('DEPRECATION:', deprecation); } }; @@ -1182,13 +1303,18 @@ getJasmineRequireObj().Env = function(j$) { failFast = config.failFast; } options.clearStack = options.clearStack || clearStack; - options.timeout = {setTimeout: realSetTimeout, clearTimeout: realClearTimeout}; + options.timeout = { + setTimeout: realSetTimeout, + clearTimeout: realClearTimeout + }; options.fail = self.fail; options.globalErrors = globalErrors; options.completeOnFirstError = failFast; - options.onException = options.onException || function(e) { - (currentRunnable() || topSuite).onException(e); - }; + options.onException = + options.onException || + function(e) { + (currentRunnable() || topSuite).onException(e); + }; options.deprecated = self.deprecated; new j$.QueueRunner(options).execute(args); @@ -1214,78 +1340,80 @@ getJasmineRequireObj().Env = function(j$) { * @interface Reporter * @see custom_reporter */ - var reporter = new j$.ReportDispatcher([ - /** - * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. - * @function - * @name Reporter#jasmineStarted - * @param {JasmineStartedInfo} suiteInfo Information about the full Jasmine suite that is being run - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'jasmineStarted', - /** - * When the entire suite has finished execution `jasmineDone` is called - * @function - * @name Reporter#jasmineDone - * @param {JasmineDoneInfo} suiteInfo Information about the full Jasmine suite that just finished running. - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'jasmineDone', - /** - * `suiteStarted` is invoked when a `describe` starts to run - * @function - * @name Reporter#suiteStarted - * @param {SuiteResult} result Information about the individual {@link describe} being run - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'suiteStarted', - /** - * `suiteDone` is invoked when all of the child specs and suites for a given suite have been run - * - * While jasmine doesn't require any specific functions, not defining a `suiteDone` will make it impossible for a reporter to know when a suite has failures in an `afterAll`. - * @function - * @name Reporter#suiteDone - * @param {SuiteResult} result - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'suiteDone', - /** - * `specStarted` is invoked when an `it` starts to run (including associated `beforeEach` functions) - * @function - * @name Reporter#specStarted - * @param {SpecResult} result Information about the individual {@link it} being run - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'specStarted', - /** - * `specDone` is invoked when an `it` and its associated `beforeEach` and `afterEach` functions have been run. - * - * While jasmine doesn't require any specific functions, not defining a `specDone` will make it impossible for a reporter to know when a spec has failed. - * @function - * @name Reporter#specDone - * @param {SpecResult} result - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'specDone' - ], queueRunnerFactory); + var reporter = new j$.ReportDispatcher( + [ + /** + * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. + * @function + * @name Reporter#jasmineStarted + * @param {JasmineStartedInfo} suiteInfo Information about the full Jasmine suite that is being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'jasmineStarted', + /** + * When the entire suite has finished execution `jasmineDone` is called + * @function + * @name Reporter#jasmineDone + * @param {JasmineDoneInfo} suiteInfo Information about the full Jasmine suite that just finished running. + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'jasmineDone', + /** + * `suiteStarted` is invoked when a `describe` starts to run + * @function + * @name Reporter#suiteStarted + * @param {SuiteResult} result Information about the individual {@link describe} being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'suiteStarted', + /** + * `suiteDone` is invoked when all of the child specs and suites for a given suite have been run + * + * While jasmine doesn't require any specific functions, not defining a `suiteDone` will make it impossible for a reporter to know when a suite has failures in an `afterAll`. + * @function + * @name Reporter#suiteDone + * @param {SuiteResult} result + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'suiteDone', + /** + * `specStarted` is invoked when an `it` starts to run (including associated `beforeEach` functions) + * @function + * @name Reporter#specStarted + * @param {SpecResult} result Information about the individual {@link it} being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'specStarted', + /** + * `specDone` is invoked when an `it` and its associated `beforeEach` and `afterEach` functions have been run. + * + * While jasmine doesn't require any specific functions, not defining a `specDone` will make it impossible for a reporter to know when a spec has failed. + * @function + * @name Reporter#specDone + * @param {SpecResult} result + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'specDone' + ], + queueRunnerFactory + ); this.execute = function(runnablesToRun) { - var self = this; installGlobalErrors(); - if(!runnablesToRun) { + if (!runnablesToRun) { if (focusedRunnables.length) { runnablesToRun = focusedRunnables; } else { @@ -1330,8 +1458,10 @@ getJasmineRequireObj().Env = function(j$) { } }); - if(!processor.processTree().valid) { - throw new Error('Invalid order: would cause a beforeAll or afterAll to be run multiple times'); + if (!processor.processTree().valid) { + throw new Error( + 'Invalid order: would cause a beforeAll or afterAll to be run multiple times' + ); } /** @@ -1340,47 +1470,53 @@ getJasmineRequireObj().Env = function(j$) { * @property {Int} totalSpecsDefined - The total number of specs defined in this suite. * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. */ - reporter.jasmineStarted({ - totalSpecsDefined: totalSpecsDefined, - order: order - }, function() { - currentlyExecutingSuites.push(topSuite); + reporter.jasmineStarted( + { + totalSpecsDefined: totalSpecsDefined, + order: order + }, + function() { + currentlyExecutingSuites.push(topSuite); - processor.execute(function () { - clearResourcesForRunnable(topSuite.id); - currentlyExecutingSuites.pop(); - var overallStatus, incompleteReason; + processor.execute(function() { + clearResourcesForRunnable(topSuite.id); + currentlyExecutingSuites.pop(); + var overallStatus, incompleteReason; - if (hasFailures || topSuite.result.failedExpectations.length > 0) { - overallStatus = 'failed'; - } else if (focusedRunnables.length > 0) { - overallStatus = 'incomplete'; - incompleteReason = 'fit() or fdescribe() was found'; - } else if (totalSpecsDefined === 0) { - overallStatus = 'incomplete'; - incompleteReason = 'No specs found'; - } else { - overallStatus = 'passed'; - } + if (hasFailures || topSuite.result.failedExpectations.length > 0) { + overallStatus = 'failed'; + } else if (focusedRunnables.length > 0) { + overallStatus = 'incomplete'; + incompleteReason = 'fit() or fdescribe() was found'; + } else if (totalSpecsDefined === 0) { + overallStatus = 'incomplete'; + incompleteReason = 'No specs found'; + } else { + overallStatus = 'passed'; + } - /** - * Information passed to the {@link Reporter#jasmineDone} event. - * @typedef JasmineDoneInfo - * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. - * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. - * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. - * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. - * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. - */ - reporter.jasmineDone({ - overallStatus: overallStatus, - incompleteReason: incompleteReason, - order: order, - failedExpectations: topSuite.result.failedExpectations, - deprecationWarnings: topSuite.result.deprecationWarnings - }, function() {}); - }); - }); + /** + * Information passed to the {@link Reporter#jasmineDone} event. + * @typedef JasmineDoneInfo + * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. + * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. + * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. + * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. + * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. + */ + reporter.jasmineDone( + { + overallStatus: overallStatus, + incompleteReason: incompleteReason, + order: order, + failedExpectations: topSuite.result.failedExpectations, + deprecationWarnings: topSuite.result.deprecationWarnings + }, + function() {} + ); + }); + } + ); }; /** @@ -1431,8 +1567,10 @@ getJasmineRequireObj().Env = function(j$) { var spyRegistry = new j$.SpyRegistry({ currentSpies: function() { - if(!currentRunnable()) { - throw new Error('Spies must be created in a before function or a spec'); + if (!currentRunnable()) { + throw new Error( + 'Spies must be created in a before function or a spec' + ); } return runnableResources[currentRunnable().id].spies; }, @@ -1472,20 +1610,26 @@ getJasmineRequireObj().Env = function(j$) { var ensureIsFunction = function(fn, caller) { if (!j$.isFunction_(fn)) { - throw new Error(caller + ' expects a function argument; received ' + j$.getType_(fn)); + throw new Error( + caller + ' expects a function argument; received ' + j$.getType_(fn) + ); } }; var ensureIsFunctionOrAsync = function(fn, caller) { if (!j$.isFunction_(fn) && !j$.isAsyncFunction_(fn)) { - throw new Error(caller + ' expects a function argument; received ' + j$.getType_(fn)); + throw new Error( + caller + ' expects a function argument; received ' + j$.getType_(fn) + ); } }; function ensureIsNotNested(method) { var runnable = currentRunnable(); if (runnable !== null && runnable !== undefined) { - throw new Error('\'' + method + '\' should only be used in \'describe\' function'); + throw new Error( + "'" + method + "' should only be used in 'describe' function" + ); } } @@ -1599,7 +1743,9 @@ getJasmineRequireObj().Env = function(j$) { description: description, expectationResultFactory: expectationResultFactory, queueRunnerFactory: queueRunnerFactory, - userContext: function() { return suite.clonedSharedUserContext(); }, + userContext: function() { + return suite.clonedSharedUserContext(); + }, queueableFn: { fn: fn, timeout: timeout || 0 @@ -1666,7 +1812,9 @@ getJasmineRequireObj().Env = function(j$) { this.expect = function(actual) { if (!currentRunnable()) { - throw new Error('\'expect\' was used when there was no current spec, this could be because an asynchronous test timed out'); + throw new Error( + "'expect' was used when there was no current spec, this could be because an asynchronous test timed out" + ); } return currentRunnable().expect(actual); @@ -1674,7 +1822,9 @@ getJasmineRequireObj().Env = function(j$) { this.expectAsync = function(actual) { if (!currentRunnable()) { - throw new Error('\'expectAsync\' was used when there was no current spec, this could be because an asynchronous test timed out'); + throw new Error( + "'expectAsync' was used when there was no current spec, this could be because an asynchronous test timed out" + ); } return currentRunnable().expectAsync(actual); @@ -1719,7 +1869,7 @@ getJasmineRequireObj().Env = function(j$) { this.pending = function(message) { var fullMessage = j$.Spec.pendingSpecExceptionMessage; - if(message) { + if (message) { fullMessage += message; } throw fullMessage; @@ -1727,7 +1877,9 @@ getJasmineRequireObj().Env = function(j$) { this.fail = function(error) { if (!currentRunnable()) { - throw new Error('\'fail\' was used when there was no current spec, this could be because an asynchronous test timed out'); + throw new Error( + "'fail' was used when there was no current spec, this could be because an asynchronous test timed out" + ); } var message = 'Failed'; @@ -1770,7 +1922,7 @@ getJasmineRequireObj().JsApiReporter = function(j$) { */ function JsApiReporter(options) { var timer = options.timer || j$.noopTimer, - status = 'loaded'; + status = 'loaded'; this.started = false; this.finished = false; @@ -1880,7 +2032,6 @@ getJasmineRequireObj().JsApiReporter = function(j$) { this.executionTime = function() { return executionTime; }; - } return JsApiReporter; @@ -2165,7 +2316,6 @@ getJasmineRequireObj().Truthy = function(j$) { }; getJasmineRequireObj().CallTracker = function(j$) { - /** * @namespace Spy#calls */ @@ -2174,7 +2324,7 @@ getJasmineRequireObj().CallTracker = function(j$) { var opts = {}; this.track = function(context) { - if(opts.cloneArgs) { + if (opts.cloneArgs) { context.args = j$.util.cloneArgs(context.args); } calls.push(context); @@ -2230,7 +2380,7 @@ getJasmineRequireObj().CallTracker = function(j$) { */ this.allArgs = function() { var callArgs = []; - for(var i = 0; i < calls.length; i++) { + for (var i = 0; i < calls.length; i++) { callArgs.push(calls[i].args); } @@ -2274,7 +2424,6 @@ getJasmineRequireObj().CallTracker = function(j$) { this.saveArgumentsByValue = function() { opts.cloneArgs = true; }; - } return CallTracker; @@ -2285,8 +2434,8 @@ getJasmineRequireObj().clearStack = function(j$) { function messageChannelImpl(global, setTimeout) { var channel = new global.MessageChannel(), - head = {}, - tail = head; + head = {}, + tail = head; var taskRunning = false; channel.port1.onmessage = function() { @@ -2324,7 +2473,7 @@ getJasmineRequireObj().clearStack = function(j$) { var currentCallCount = 0; var realSetTimeout = global.setTimeout; var setTimeoutImpl = function clearStack(fn) { - Function.prototype.apply.apply(realSetTimeout, [global, [fn, 0]]); + Function.prototype.apply.apply(realSetTimeout, [global, [fn, 0]]); }; if (j$.isFunction_(global.setImmediate)) { @@ -2351,9 +2500,11 @@ getJasmineRequireObj().clearStack = function(j$) { }; getJasmineRequireObj().Clock = function() { - /* global process */ - var NODE_JS = typeof process !== 'undefined' && process.versions && typeof process.versions.node === 'string'; + var NODE_JS = + typeof process !== 'undefined' && + process.versions && + typeof process.versions.node === 'string'; /** * _Note:_ Do not construct this directly, Jasmine will make one during booting. You can get the current clock with {@link jasmine.clock}. @@ -2387,8 +2538,10 @@ getJasmineRequireObj().Clock = function() { * @return {Clock} */ self.install = function() { - if(!originalTimingFunctionsIntact()) { - throw new Error('Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?'); + if (!originalTimingFunctionsIntact()) { + throw new Error( + 'Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?' + ); } replace(global, fakeTimingFunctions); timer = fakeTimingFunctions; @@ -2440,11 +2593,17 @@ getJasmineRequireObj().Clock = function() { }; self.setTimeout = function(fn, delay, params) { - return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]); + return Function.prototype.apply.apply(timer.setTimeout, [ + global, + arguments + ]); }; self.setInterval = function(fn, delay, params) { - return Function.prototype.apply.apply(timer.setInterval, [global, arguments]); + return Function.prototype.apply.apply(timer.setInterval, [ + global, + arguments + ]); }; self.clearTimeout = function(id) { @@ -2463,19 +2622,25 @@ getJasmineRequireObj().Clock = function() { */ self.tick = function(millis) { if (installed) { - delayedFunctionScheduler.tick(millis, function(millis) { mockDate.tick(millis); }); + delayedFunctionScheduler.tick(millis, function(millis) { + mockDate.tick(millis); + }); } else { - throw new Error('Mock clock is not installed, use jasmine.clock().install()'); + throw new Error( + 'Mock clock is not installed, use jasmine.clock().install()' + ); } }; return self; function originalTimingFunctionsIntact() { - return global.setTimeout === realTimingFunctions.setTimeout && + return ( + global.setTimeout === realTimingFunctions.setTimeout && global.clearTimeout === realTimingFunctions.clearTimeout && global.setInterval === realTimingFunctions.setInterval && - global.clearInterval === realTimingFunctions.clearInterval; + global.clearInterval === realTimingFunctions.clearInterval + ); } function replace(dest, source) { @@ -2486,12 +2651,22 @@ getJasmineRequireObj().Clock = function() { function setTimeout(fn, delay) { if (!NODE_JS) { - return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2)); + return delayedFunctionScheduler.scheduleFunction( + fn, + delay, + argSlice(arguments, 2) + ); } var timeout = new FakeTimeout(); - delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2), false, timeout); + delayedFunctionScheduler.scheduleFunction( + fn, + delay, + argSlice(arguments, 2), + false, + timeout + ); return timeout; } @@ -2502,12 +2677,23 @@ getJasmineRequireObj().Clock = function() { function setInterval(fn, interval) { if (!NODE_JS) { - return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true); + return delayedFunctionScheduler.scheduleFunction( + fn, + interval, + argSlice(arguments, 2), + true + ); } var timeout = new FakeTimeout(); - delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true, timeout); + delayedFunctionScheduler.scheduleFunction( + fn, + interval, + argSlice(arguments, 2), + true, + timeout + ); return timeout; } @@ -2526,11 +2712,11 @@ getJasmineRequireObj().Clock = function() { */ function FakeTimeout() {} - FakeTimeout.prototype.ref = function () { + FakeTimeout.prototype.ref = function() { return this; }; - FakeTimeout.prototype.unref = function () { + FakeTimeout.prototype.unref = function() { return this; }; @@ -2554,11 +2740,20 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { currentTime = endTime; }; - self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) { + self.scheduleFunction = function( + funcToCall, + millis, + params, + recurring, + timeoutKey, + runAtMillis + ) { var f; - if (typeof(funcToCall) === 'string') { + if (typeof funcToCall === 'string') { /* jshint evil: true */ - f = function() { return eval(funcToCall); }; + f = function() { + return eval(funcToCall); + }; /* jshint evil: false */ } else { f = funcToCall; @@ -2566,7 +2761,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { millis = millis || 0; timeoutKey = timeoutKey || ++delayedFnCount; - runAtMillis = runAtMillis || (currentTime + millis); + runAtMillis = runAtMillis || currentTime + millis; var funcToSchedule = { runAtMillis: runAtMillis, @@ -2582,7 +2777,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { } else { scheduledFunctions[runAtMillis] = [funcToSchedule]; scheduledLookup.push(runAtMillis); - scheduledLookup.sort(function (a, b) { + scheduledLookup.sort(function(a, b) { return a - b; }); } @@ -2595,7 +2790,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { for (var runAtMillis in scheduledFunctions) { var funcs = scheduledFunctions[runAtMillis]; - var i = indexOfFirstToPass(funcs, function (func) { + var i = indexOfFirstToPass(funcs, function(func) { return func.timeoutKey === timeoutKey; }); @@ -2631,7 +2826,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { function deleteFromLookup(key) { var value = Number(key); - var i = indexOfFirstToPass(scheduledLookup, function (millis) { + var i = indexOfFirstToPass(scheduledLookup, function(millis) { return millis === value; }); @@ -2641,12 +2836,14 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { } function reschedule(scheduledFn) { - self.scheduleFunction(scheduledFn.funcToCall, + self.scheduleFunction( + scheduledFn.funcToCall, scheduledFn.millis, scheduledFn.params, true, scheduledFn.timeoutKey, - scheduledFn.runAtMillis + scheduledFn.millis); + scheduledFn.runAtMillis + scheduledFn.millis + ); } function forEachFunction(funcsToRun, callback) { @@ -2687,11 +2884,13 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { funcToRun.funcToCall.apply(null, funcToRun.params || []); }); deletedKeys = []; - } while (scheduledLookup.length > 0 && - // checking first if we're out of time prevents setTimeout(0) - // scheduled in a funcToRun from forcing an extra iteration - currentTime !== endTime && - scheduledLookup[0] <= endTime); + } while ( + scheduledLookup.length > 0 && + // checking first if we're out of time prevents setTimeout(0) + // scheduled in a funcToRun from forcing an extra iteration + currentTime !== endTime && + scheduledLookup[0] <= endTime + ); // ran out of functions to call, but still time left on the clock if (currentTime !== endTime) { @@ -2713,9 +2912,20 @@ getJasmineRequireObj().errors = function() { ExpectationFailed: ExpectationFailed }; }; -getJasmineRequireObj().ExceptionFormatter = function(j$) { - var ignoredProperties = ['name', 'message', 'stack', 'fileName', 'sourceURL', 'line', 'lineNumber', 'column', 'description', 'jasmineMessage']; +getJasmineRequireObj().ExceptionFormatter = function(j$) { + var ignoredProperties = [ + 'name', + 'message', + 'stack', + 'fileName', + 'sourceURL', + 'line', + 'lineNumber', + 'column', + 'description', + 'jasmineMessage' + ]; function ExceptionFormatter(options) { var jasmineFile = (options && options.jasmineFile) || j$.util.jasmineFile(); @@ -2764,7 +2974,8 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { function filterJasmine(stackTrace) { var result = [], - jasmineMarker = stackTrace.style === 'webkit' ? '' : ' at '; + jasmineMarker = + stackTrace.style === 'webkit' ? '' : ' at '; stackTrace.frames.forEach(function(frame) { if (frame.file && frame.file !== jasmineFile) { @@ -2806,7 +3017,9 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { getJasmineRequireObj().Expectation = function(j$) { var promiseForMessage = { - jasmineToString: function() { return 'a promise'; } + jasmineToString: function() { + return 'a promise'; + } }; /** @@ -2818,7 +3031,10 @@ getJasmineRequireObj().Expectation = function(j$) { var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { - this[matcherName] = wrapSyncCompare(matcherName, customMatchers[matcherName]); + this[matcherName] = wrapSyncCompare( + matcherName, + customMatchers[matcherName] + ); } } @@ -2856,7 +3072,9 @@ getJasmineRequireObj().Expectation = function(j$) { this.expector = new j$.Expector(options); if (!global.Promise) { - throw new Error('expectAsync is unavailable because the environment does not support promises.'); + throw new Error( + 'expectAsync is unavailable because the environment does not support promises.' + ); } if (!j$.isPromiseLike(this.expector.actual)) { @@ -2906,9 +3124,11 @@ getJasmineRequireObj().Expectation = function(j$) { // frames that are relevant to the user instead of just parts of Jasmine. var errorForStack = j$.util.errorWithStack(); - return this.expector.compare(name, matcherFactory, arguments).then(function(result) { - self.expector.processResult(result, errorForStack, promiseForMessage); - }); + return this.expector + .compare(name, matcherFactory, arguments) + .then(function(result) { + self.expector.processResult(result, errorForStack, promiseForMessage); + }); }; } @@ -3005,7 +3225,12 @@ getJasmineRequireObj().ExpectationFilterChain = function() { return this.callFirst_('selectComparisonFunc', arguments).result; }; - ExpectationFilterChain.prototype.buildFailureMessage = function(result, matcherName, args, util) { + ExpectationFilterChain.prototype.buildFailureMessage = function( + result, + matcherName, + args, + util + ) { return this.callFirst_('buildFailureMessage', arguments).result; }; @@ -3032,7 +3257,7 @@ getJasmineRequireObj().ExpectationFilterChain = function() { }; } - return {found: false}; + return { found: false }; }; return ExpectationFilterChain; @@ -3060,7 +3285,7 @@ getJasmineRequireObj().buildExpectationResult = function() { passed: options.passed }; - if(!result.passed) { + if (!result.passed) { result.expected = options.expected; result.actual = options.actual; } @@ -3113,7 +3338,11 @@ getJasmineRequireObj().Expector = function(j$) { this.filters = new j$.ExpectationFilterChain(); } - Expector.prototype.instantiateMatcher = function(matcherName, matcherFactory, args) { + Expector.prototype.instantiateMatcher = function( + matcherName, + matcherFactory, + args + ) { this.matcherName = matcherName; this.args = Array.prototype.slice.call(args, 0); this.expected = this.args.slice(0); @@ -3132,7 +3361,13 @@ getJasmineRequireObj().Expector = function(j$) { return ''; } - var msg = this.filters.buildFailureMessage(result, this.matcherName, this.args, this.util, defaultMessage); + var msg = this.filters.buildFailureMessage( + result, + this.matcherName, + this.args, + this.util, + defaultMessage + ); return this.filters.modifyFailureMessage(msg || defaultMessage()); function defaultMessage() { @@ -3150,7 +3385,11 @@ getJasmineRequireObj().Expector = function(j$) { }; Expector.prototype.compare = function(matcherName, matcherFactory, args) { - var matcherCompare = this.instantiateMatcher(matcherName, matcherFactory, args); + var matcherCompare = this.instantiateMatcher( + matcherName, + matcherFactory, + args + ); return matcherCompare.apply(null, this.args); }; @@ -3160,7 +3399,11 @@ getJasmineRequireObj().Expector = function(j$) { return result; }; - Expector.prototype.processResult = function(result, errorForStack, actualOverride) { + Expector.prototype.processResult = function( + result, + errorForStack, + actualOverride + ) { this.args[0] = actualOverride || this.args[0]; var message = this.buildMessage(result); @@ -3168,18 +3411,15 @@ getJasmineRequireObj().Expector = function(j$) { this.expected = this.expected[0]; } - this.addExpectationResult( - result.pass, - { - matcherName: this.matcherName, - passed: result.pass, - message: message, - error: errorForStack ? undefined : result.error, - errorForStack: errorForStack || undefined, - actual: this.actual, - expected: this.expected // TODO: this may need to be arrayified/sliced - } - ); + this.addExpectationResult(result.pass, { + matcherName: this.matcherName, + passed: result.pass, + message: message, + error: errorForStack ? undefined : result.error, + errorForStack: errorForStack || undefined, + actual: this.actual, + expected: this.expected // TODO: this may need to be arrayified/sliced + }); }; return Expector; @@ -3237,7 +3477,10 @@ getJasmineRequireObj().GlobalErrors = function(j$) { var errorTypes = Object.keys(this.originalHandlers); for (var iType = 0; iType < errorTypes.length; iType++) { var errorType = errorTypes[iType]; - global.process.removeListener(errorType, this.jasmineHandlers[errorType]); + global.process.removeListener( + errorType, + this.jasmineHandlers[errorType] + ); for (var i = 0; i < this.originalHandlers[errorType].length; i++) { global.process.on(errorType, this.originalHandlers[errorType][i]); } @@ -3248,7 +3491,11 @@ getJasmineRequireObj().GlobalErrors = function(j$) { }; this.install = function install() { - if (global.process && global.process.listeners && j$.isFunction_(global.process.on)) { + if ( + global.process && + global.process.listeners && + j$.isFunction_(global.process.on) + ) { this.installOne_('uncaughtException', 'Uncaught exception'); this.installOne_('unhandledRejection', 'Unhandled promise rejection'); } else { @@ -5185,7 +5432,7 @@ getJasmineRequireObj().MockDate = function() { return self; function FakeDate() { - switch(arguments.length) { + switch (arguments.length) { case 0: return new GlobalDate(currentTime); case 1: @@ -5195,16 +5442,39 @@ getJasmineRequireObj().MockDate = function() { case 3: return new GlobalDate(arguments[0], arguments[1], arguments[2]); case 4: - return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3]); + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3] + ); case 5: - return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], - arguments[4]); + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4] + ); case 6: - return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], - arguments[4], arguments[5]); + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4], + arguments[5] + ); default: - return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], - arguments[4], arguments[5], arguments[6]); + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4], + arguments[5], + arguments[6] + ); } } @@ -5230,7 +5500,6 @@ getJasmineRequireObj().MockDate = function() { }; getJasmineRequireObj().pp = function(j$) { - function PrettyPrinter() { this.ppNestLevel_ = 0; this.seen = []; @@ -5241,7 +5510,11 @@ getJasmineRequireObj().pp = function(j$) { function hasCustomToString(value) { // value.toString !== Object.prototype.toString if value has no custom toString but is from another context (e.g. // iframe, web worker) - return j$.isFunction_(value.toString) && value.toString !== Object.prototype.toString && (value.toString() !== Object.prototype.toString.call(value)); + return ( + j$.isFunction_(value.toString) && + value.toString !== Object.prototype.toString && + value.toString() !== Object.prototype.toString.call(value) + ); } PrettyPrinter.prototype.format = function(value) { @@ -5251,7 +5524,7 @@ getJasmineRequireObj().pp = function(j$) { this.emitScalar('undefined'); } else if (value === null) { this.emitScalar('null'); - } else if (value === 0 && 1/value === -Infinity) { + } else if (value === 0 && 1 / value === -Infinity) { this.emitScalar('-0'); } else if (value === j$.getGlobal()) { this.emitScalar(''); @@ -5281,10 +5554,19 @@ getJasmineRequireObj().pp = function(j$) { this.emitMap(value); } else if (j$.isTypedArray_(value)) { this.emitTypedArray(value); - } else if (value.toString && typeof value === 'object' && !j$.isArray_(value) && hasCustomToString(value)) { + } else if ( + value.toString && + typeof value === 'object' && + !j$.isArray_(value) && + hasCustomToString(value) + ) { this.emitScalar(value.toString()); } else if (j$.util.arrayContains(this.seen, value)) { - this.emitScalar(''); + this.emitScalar( + '' + ); } else if (j$.isArray_(value) || j$.isA_('Object', value)) { this.seen.push(value); if (j$.isArray_(value)) { @@ -5314,7 +5596,6 @@ getJasmineRequireObj().pp = function(j$) { var getter = obj.__lookupGetter__(prop); return !j$.util.isUndefined(getter) && getter !== null; }; - } var length = Math.min(objKeys.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); for (var i = 0; i < length; i++) { @@ -5330,7 +5611,7 @@ getJasmineRequireObj().pp = function(j$) { }; PrettyPrinter.prototype.emitString = function(value) { - this.append('\'' + value + '\''); + this.append("'" + value + "'"); }; PrettyPrinter.prototype.emitArray = function(array) { @@ -5346,7 +5627,7 @@ getJasmineRequireObj().pp = function(j$) { } this.format(array[i]); } - if(array.length > length) { + if (array.length > length) { this.append(', ...'); } @@ -5362,7 +5643,9 @@ getJasmineRequireObj().pp = function(j$) { self.formatProperty(array, property, isGetter); }); - if (truncated) { this.append(', ...'); } + if (truncated) { + this.append(', ...'); + } this.append(' ]'); }; @@ -5375,7 +5658,7 @@ getJasmineRequireObj().pp = function(j$) { this.append('Set( '); var size = Math.min(set.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); var i = 0; - set.forEach( function( value, key ) { + set.forEach(function(value, key) { if (i >= size) { return; } @@ -5385,7 +5668,7 @@ getJasmineRequireObj().pp = function(j$) { this.format(value); i++; - }, this ); + }, this); if (set.size > size) { this.append(', ...'); } @@ -5400,17 +5683,17 @@ getJasmineRequireObj().pp = function(j$) { this.append('Map( '); var size = Math.min(map.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); var i = 0; - map.forEach( function( value, key ) { + map.forEach(function(value, key) { if (i >= size) { return; } if (i > 0) { this.append(', '); } - this.format([key,value]); + this.format([key, value]); i++; - }, this ); + }, this); if (map.size > size) { this.append(', ...'); } @@ -5419,11 +5702,12 @@ getJasmineRequireObj().pp = function(j$) { PrettyPrinter.prototype.emitObject = function(obj) { var ctor = obj.constructor, - constructorName; + constructorName; - constructorName = typeof ctor === 'function' && obj instanceof ctor ? - j$.fnNameFor(obj.constructor) : - 'null'; + constructorName = + typeof ctor === 'function' && obj instanceof ctor + ? j$.fnNameFor(obj.constructor) + : 'null'; this.append(constructorName); @@ -5445,14 +5729,20 @@ getJasmineRequireObj().pp = function(j$) { self.formatProperty(obj, property, isGetter); }); - if (truncated) { this.append(', ...'); } + if (truncated) { + this.append(', ...'); + } this.append(' })'); }; PrettyPrinter.prototype.emitTypedArray = function(arr) { var constructorName = j$.fnNameFor(arr.constructor), - limitedArray = Array.prototype.slice.call(arr, 0, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH), + limitedArray = Array.prototype.slice.call( + arr, + 0, + j$.MAX_PRETTY_PRINT_ARRAY_LENGTH + ), itemsString = Array.prototype.join.call(limitedArray, ', '); if (limitedArray.length !== arr.length) { @@ -5489,13 +5779,13 @@ getJasmineRequireObj().pp = function(j$) { }; PrettyPrinter.prototype.formatProperty = function(obj, property, isGetter) { - this.append(property); - this.append(': '); - if (isGetter) { - this.append(''); - } else { - this.format(obj[property]); - } + this.append(property); + this.append(': '); + if (isGetter) { + this.append(''); + } else { + this.format(obj[property]); + } }; PrettyPrinter.prototype.append = function(value) { @@ -5514,7 +5804,6 @@ getJasmineRequireObj().pp = function(j$) { } }; - function truncate(s, maxlen) { if (s.length <= maxlen) { return { value: s, truncated: false }; @@ -5525,30 +5814,33 @@ getJasmineRequireObj().pp = function(j$) { } function MaxCharsReachedError() { - this.message = 'Exceeded ' + j$.MAX_PRETTY_PRINT_CHARS + + this.message = + 'Exceeded ' + + j$.MAX_PRETTY_PRINT_CHARS + ' characters while pretty-printing a value'; } MaxCharsReachedError.prototype = new Error(); function keys(obj, isArray) { - var allKeys = Object.keys ? Object.keys(obj) : - (function(o) { + var allKeys = Object.keys + ? Object.keys(obj) + : (function(o) { var keys = []; for (var key in o) { - if (j$.util.has(o, key)) { - keys.push(key); - } + if (j$.util.has(o, key)) { + keys.push(key); + } } return keys; - })(obj); + })(obj); if (!isArray) { return allKeys; } if (allKeys.length === 0) { - return allKeys; + return allKeys; } var extraKeys = []; @@ -5591,16 +5883,26 @@ getJasmineRequireObj().QueueRunner = function(j$) { this.queueableFns = queueableFns.concat(attrs.cleanupFns || []); this.firstCleanupIx = queueableFns.length; this.onComplete = attrs.onComplete || emptyFn; - this.clearStack = attrs.clearStack || function(fn) { fn(); }; + this.clearStack = + attrs.clearStack || + function(fn) { + fn(); + }; this.onException = attrs.onException || emptyFn; this.userContext = attrs.userContext || new j$.UserContext(); - this.timeout = attrs.timeout || {setTimeout: setTimeout, clearTimeout: clearTimeout}; + this.timeout = attrs.timeout || { + setTimeout: setTimeout, + clearTimeout: clearTimeout + }; this.fail = attrs.fail || emptyFn; - this.globalErrors = attrs.globalErrors || { pushListener: emptyFn, popListener: emptyFn }; + this.globalErrors = attrs.globalErrors || { + pushListener: emptyFn, + popListener: emptyFn + }; this.completeOnFirstError = !!attrs.completeOnFirstError; this.errored = false; - if (typeof(this.onComplete) !== 'function') { + if (typeof this.onComplete !== 'function') { throw new Error('invalid onComplete ' + JSON.stringify(this.onComplete)); } this.deprecated = attrs.deprecated; @@ -5624,15 +5926,22 @@ getJasmineRequireObj().QueueRunner = function(j$) { }; QueueRunner.prototype.clearTimeout = function(timeoutId) { - Function.prototype.apply.apply(this.timeout.clearTimeout, [j$.getGlobal(), [timeoutId]]); + Function.prototype.apply.apply(this.timeout.clearTimeout, [ + j$.getGlobal(), + [timeoutId] + ]); }; QueueRunner.prototype.setTimeout = function(fn, timeout) { - return Function.prototype.apply.apply(this.timeout.setTimeout, [j$.getGlobal(), [fn, timeout]]); + return Function.prototype.apply.apply(this.timeout.setTimeout, [ + j$.getGlobal(), + [fn, timeout] + ]); }; QueueRunner.prototype.attempt = function attempt(iterativeIndex) { - var self = this, completedSynchronously = true, + var self = this, + completedSynchronously = true, handleError = function handleError(error) { onException(error); next(error); @@ -5683,8 +5992,12 @@ getJasmineRequireObj().QueueRunner = function(j$) { var timeoutInterval = queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL; timeoutId = self.setTimeout(function() { var error = new Error( - 'Timeout - Async callback was not invoked within ' + timeoutInterval + 'ms ' + - (queueableFn.timeout ? '(custom timeout)' : '(set by jasmine.DEFAULT_TIMEOUT_INTERVAL)') + 'Timeout - Async callback was not invoked within ' + + timeoutInterval + + 'ms ' + + (queueableFn.timeout + ? '(custom timeout)' + : '(set by jasmine.DEFAULT_TIMEOUT_INTERVAL)') ); onException(error); next(); @@ -5729,8 +6042,11 @@ getJasmineRequireObj().QueueRunner = function(j$) { self = this, iterativeIndex; - - for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) { + for ( + iterativeIndex = recursiveIndex; + iterativeIndex < length; + iterativeIndex++ + ) { var result = this.attempt(iterativeIndex); if (!result.completedSynchronously) { @@ -5749,7 +6065,6 @@ getJasmineRequireObj().QueueRunner = function(j$) { self.globalErrors.popListener(self.handleFinalError); self.onComplete(self.errored && new StopExecutionError()); }); - }; return QueueRunner; @@ -5757,7 +6072,6 @@ getJasmineRequireObj().QueueRunner = function(j$) { getJasmineRequireObj().ReportDispatcher = function(j$) { function ReportDispatcher(methods, queueRunnerFactory) { - var dispatchedMethods = methods || []; for (var i = 0; i < dispatchedMethods.length; i++) { @@ -5766,7 +6080,7 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { return function() { dispatch(m, arguments); }; - }(method)); + })(method); } var reporters = []; @@ -5788,7 +6102,7 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { function dispatch(method, args) { if (reporters.length === 0 && fallbackReporter !== null) { - reporters.push(fallbackReporter); + reporters.push(fallbackReporter); } var onComplete = args[args.length - 1]; args = j$.util.argsToArray(args).splice(0, args.length - 1); @@ -5814,13 +6128,13 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { var thisArgs = j$.util.cloneArgs(args); if (fn.length <= 1) { fns.push({ - fn: function () { + fn: function() { return fn.apply(reporter, thisArgs); } }); } else { fns.push({ - fn: function (done) { + fn: function(done) { return fn.apply(reporter, thisArgs.concat([done])); } }); @@ -5831,7 +6145,6 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { return ReportDispatcher; }; - getJasmineRequireObj().interface = function(jasmine, env) { var jasmineInterface = { /** @@ -6037,7 +6350,7 @@ getJasmineRequireObj().interface = function(jasmine, env) { * @function * @global * @param {String|Error} [error] - Reason for the failure. - */ + */ fail: function() { return env.fail.apply(env, arguments); }, @@ -6167,8 +6480,7 @@ getJasmineRequireObj().interface = function(jasmine, env) { return jasmineInterface; }; -getJasmineRequireObj().Spy = function (j$) { - +getJasmineRequireObj().Spy = function(j$) { var nextOrder = (function() { var order = 0; @@ -6183,21 +6495,21 @@ getJasmineRequireObj().Spy = function (j$) { * @name Spy */ function Spy(name, originalFn, customStrategies, getPromise) { - var numArgs = (typeof originalFn === 'function' ? originalFn.length : 0), - wrapper = makeFunc(numArgs, function () { + var numArgs = typeof originalFn === 'function' ? originalFn.length : 0, + wrapper = makeFunc(numArgs, function() { return spy.apply(this, Array.prototype.slice.call(arguments)); }), strategyDispatcher = new SpyStrategyDispatcher({ name: name, fn: originalFn, - getSpy: function () { + getSpy: function() { return wrapper; }, customStrategies: customStrategies, getPromise: getPromise }), callTracker = new j$.CallTracker(), - spy = function () { + spy = function() { /** * @name Spy.callData * @property {object} object - `this` context for the invocation. @@ -6219,22 +6531,54 @@ getJasmineRequireObj().Spy = function (j$) { function makeFunc(length, fn) { switch (length) { - case 1 : return function (a) { return fn.apply(this, arguments); }; - case 2 : return function (a,b) { return fn.apply(this, arguments); }; - case 3 : return function (a,b,c) { return fn.apply(this, arguments); }; - case 4 : return function (a,b,c,d) { return fn.apply(this, arguments); }; - case 5 : return function (a,b,c,d,e) { return fn.apply(this, arguments); }; - case 6 : return function (a,b,c,d,e,f) { return fn.apply(this, arguments); }; - case 7 : return function (a,b,c,d,e,f,g) { return fn.apply(this, arguments); }; - case 8 : return function (a,b,c,d,e,f,g,h) { return fn.apply(this, arguments); }; - case 9 : return function (a,b,c,d,e,f,g,h,i) { return fn.apply(this, arguments); }; - default : return function () { return fn.apply(this, arguments); }; + case 1: + return function(a) { + return fn.apply(this, arguments); + }; + case 2: + return function(a, b) { + return fn.apply(this, arguments); + }; + case 3: + return function(a, b, c) { + return fn.apply(this, arguments); + }; + case 4: + return function(a, b, c, d) { + return fn.apply(this, arguments); + }; + case 5: + return function(a, b, c, d, e) { + return fn.apply(this, arguments); + }; + case 6: + return function(a, b, c, d, e, f) { + return fn.apply(this, arguments); + }; + case 7: + return function(a, b, c, d, e, f, g) { + return fn.apply(this, arguments); + }; + case 8: + return function(a, b, c, d, e, f, g, h) { + return fn.apply(this, arguments); + }; + case 9: + return function(a, b, c, d, e, f, g, h, i) { + return fn.apply(this, arguments); + }; + default: + return function() { + return fn.apply(this, arguments); + }; } } for (var prop in originalFn) { if (prop === 'and' || prop === 'calls') { - throw new Error('Jasmine spies would overwrite the \'and\' and \'calls\' properties on the object being spied upon'); + throw new Error( + "Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon" + ); } wrapper[prop] = originalFn[prop]; @@ -6281,7 +6625,13 @@ getJasmineRequireObj().Spy = function (j$) { if (!strategy) { if (argsStrategies.any() && !baseStrategy.isConfigured()) { - throw new Error('Spy \'' + strategyArgs.name + '\' received a call with arguments ' + j$.pp(Array.prototype.slice.call(args)) + ' but all configured strategies specify other arguments.'); + throw new Error( + "Spy '" + + strategyArgs.name + + "' received a call with arguments " + + j$.pp(Array.prototype.slice.call(args)) + + ' but all configured strategies specify other arguments.' + ); } else { strategy = baseStrategy; } @@ -6332,7 +6682,6 @@ getJasmineRequireObj().Spy = function (j$) { }; getJasmineRequireObj().SpyFactory = function(j$) { - function SpyFactory(getCustomStrategies, getPromise) { var self = this; @@ -6341,7 +6690,8 @@ getJasmineRequireObj().SpyFactory = function(j$) { }; this.createSpyObj = function(baseName, methodNames) { - var baseNameIsCollection = j$.isObject_(baseName) || j$.isArray_(baseName); + var baseNameIsCollection = + j$.isObject_(baseName) || j$.isArray_(baseName); if (baseNameIsCollection && j$.util.isUndefined(methodNames)) { methodNames = baseName; @@ -6378,15 +6728,21 @@ getJasmineRequireObj().SpyFactory = function(j$) { }; getJasmineRequireObj().SpyRegistry = function(j$) { - var spyOnMsg = j$.formatErrorMsg('', 'spyOn(, )'); - var spyOnPropertyMsg = j$.formatErrorMsg('', 'spyOnProperty(, , [accessType])'); + var spyOnPropertyMsg = j$.formatErrorMsg( + '', + 'spyOnProperty(, , [accessType])' + ); function SpyRegistry(options) { options = options || {}; var global = options.global || j$.getGlobal(); var createSpy = options.createSpy; - var currentSpies = options.currentSpies || function() { return []; }; + var currentSpies = + options.currentSpies || + function() { + return []; + }; this.allowRespy = function(allow) { this.respy = allow; @@ -6396,7 +6752,11 @@ getJasmineRequireObj().SpyRegistry = function(j$) { var getErrorMsg = spyOnMsg; if (j$.util.isUndefined(obj) || obj === null) { - throw new Error(getErrorMsg('could not find an object to spy upon for ' + methodName + '()')); + throw new Error( + getErrorMsg( + 'could not find an object to spy upon for ' + methodName + '()' + ) + ); } if (j$.util.isUndefined(methodName) || methodName === null) { @@ -6407,25 +6767,32 @@ getJasmineRequireObj().SpyRegistry = function(j$) { throw new Error(getErrorMsg(methodName + '() method does not exist')); } - if (obj[methodName] && j$.isSpy(obj[methodName]) ) { + if (obj[methodName] && j$.isSpy(obj[methodName])) { if (this.respy) { return obj[methodName]; - }else { - throw new Error(getErrorMsg(methodName + ' has already been spied upon')); + } else { + throw new Error( + getErrorMsg(methodName + ' has already been spied upon') + ); } } var descriptor = Object.getOwnPropertyDescriptor(obj, methodName); if (descriptor && !(descriptor.writable || descriptor.set)) { - throw new Error(getErrorMsg(methodName + ' is not declared writable or has no setter')); + throw new Error( + getErrorMsg(methodName + ' is not declared writable or has no setter') + ); } var originalMethod = obj[methodName], spiedMethod = createSpy(methodName, originalMethod), restoreStrategy; - if (Object.prototype.hasOwnProperty.call(obj, methodName) || (obj === global && methodName === 'onerror')) { + if ( + Object.prototype.hasOwnProperty.call(obj, methodName) || + (obj === global && methodName === 'onerror') + ) { restoreStrategy = function() { obj[methodName] = originalMethod; }; @@ -6446,13 +6813,19 @@ getJasmineRequireObj().SpyRegistry = function(j$) { return spiedMethod; }; - this.spyOnProperty = function (obj, propertyName, accessType) { + this.spyOnProperty = function(obj, propertyName, accessType) { var getErrorMsg = spyOnPropertyMsg; accessType = accessType || 'get'; if (j$.util.isUndefined(obj)) { - throw new Error(getErrorMsg('spyOn could not find an object to spy upon for ' + propertyName + '')); + throw new Error( + getErrorMsg( + 'spyOn could not find an object to spy upon for ' + + propertyName + + '' + ) + ); } if (j$.util.isUndefined(propertyName)) { @@ -6466,18 +6839,31 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } if (!descriptor.configurable) { - throw new Error(getErrorMsg(propertyName + ' is not declared configurable')); + throw new Error( + getErrorMsg(propertyName + ' is not declared configurable') + ); } - if(!descriptor[accessType]) { - throw new Error(getErrorMsg('Property ' + propertyName + ' does not have access type ' + accessType)); + if (!descriptor[accessType]) { + throw new Error( + getErrorMsg( + 'Property ' + + propertyName + + ' does not have access type ' + + accessType + ) + ); } if (j$.isSpy(descriptor[accessType])) { if (this.respy) { return descriptor[accessType]; } else { - throw new Error(getErrorMsg(propertyName + '#' + accessType + ' has already been spied upon')); + throw new Error( + getErrorMsg( + propertyName + '#' + accessType + ' has already been spied upon' + ) + ); } } @@ -6508,19 +6894,27 @@ getJasmineRequireObj().SpyRegistry = function(j$) { this.spyOnAllFunctions = function(obj) { if (j$.util.isUndefined(obj)) { - throw new Error('spyOnAllFunctions could not find an object to spy upon'); + throw new Error( + 'spyOnAllFunctions could not find an object to spy upon' + ); } var pointer = obj, - props = [], - prop, - descriptor; + props = [], + prop, + descriptor; while (pointer) { for (prop in pointer) { - if (Object.prototype.hasOwnProperty.call(pointer, prop) && pointer[prop] instanceof Function) { + if ( + Object.prototype.hasOwnProperty.call(pointer, prop) && + pointer[prop] instanceof Function + ) { descriptor = Object.getOwnPropertyDescriptor(pointer, prop); - if ((descriptor.writable || descriptor.set) && descriptor.configurable) { + if ( + (descriptor.writable || descriptor.set) && + descriptor.configurable + ) { props.push(prop); } } @@ -6548,7 +6942,6 @@ getJasmineRequireObj().SpyRegistry = function(j$) { }; getJasmineRequireObj().SpyStrategy = function(j$) { - /** * @interface SpyStrategy */ @@ -6568,20 +6961,27 @@ getJasmineRequireObj().SpyStrategy = function(j$) { this.getSpy = options.getSpy || function() {}; this.plan = this._defaultPlan = function() {}; - var k, cs = options.customStrategies || {}; + var k, + cs = options.customStrategies || {}; for (k in cs) { if (j$.util.has(cs, k) && !this[k]) { this[k] = createCustomPlan(cs[k]); } } - var getPromise = (typeof options.getPromise === 'function') ? options.getPromise : function() {}; + var getPromise = + typeof options.getPromise === 'function' + ? options.getPromise + : function() {}; var requirePromise = function(name) { var Promise = getPromise(); if (!Promise) { - throw new Error(name + ' requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`'); + throw new Error( + name + + ' requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`' + ); } return Promise; @@ -6609,7 +7009,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { */ this.rejectWith = function(value) { var Promise = requirePromise('rejectWith'); - var error = (value instanceof Error) ? value : new Error(value); + var error = value instanceof Error ? value : new Error(value); self.plan = function() { return Promise.reject(error); @@ -6671,7 +7071,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { */ SpyStrategy.prototype.returnValues = function() { var values = Array.prototype.slice.call(arguments); - this.plan = function () { + this.plan = function() { return values.shift(); }; return this.getSpy(); @@ -6684,7 +7084,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {Error|String} something Thing to throw */ SpyStrategy.prototype.throwError = function(something) { - var error = (something instanceof Error) ? something : new Error(something); + var error = something instanceof Error ? something : new Error(something); this.plan = function() { throw error; }; @@ -6698,8 +7098,10 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {Function} fn The function to invoke with the passed parameters. */ SpyStrategy.prototype.callFake = function(fn) { - if(!(j$.isFunction_(fn) || j$.isAsyncFunction_(fn))) { - throw new Error('Argument passed to callFake should be a function, got ' + fn); + if (!(j$.isFunction_(fn) || j$.isAsyncFunction_(fn))) { + throw new Error( + 'Argument passed to callFake should be a function, got ' + fn + ); } this.plan = fn; return this.getSpy(); @@ -6724,9 +7126,9 @@ getJasmineRequireObj().SpyStrategy = function(j$) { getJasmineRequireObj().StackTrace = function(j$) { function StackTrace(error) { - var lines = error.stack - .split('\n') - .filter(function(line) { return line !== ''; }); + var lines = error.stack.split('\n').filter(function(line) { + return line !== ''; + }); var extractResult = extractMessage(error.message, lines); @@ -6745,7 +7147,12 @@ getJasmineRequireObj().StackTrace = function(j$) { // e.g. " at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)" // Note that the "function name" can include a surprisingly large set of // characters, including angle brackets and square brackets. - { re: /^\s*at ([^\)]+) \(([^\)]+)\)$/, fnIx: 1, fileLineColIx: 2, style: 'v8' }, + { + re: /^\s*at ([^\)]+) \(([^\)]+)\)$/, + fnIx: 1, + fileLineColIx: 2, + style: 'v8' + }, // NodeJS alternate form, often mixed in with the Chrome style // e.g. " at /some/path:4320:20 @@ -6754,7 +7161,12 @@ getJasmineRequireObj().StackTrace = function(j$) { // PhantomJS on OS X, Safari, Firefox // e.g. "run@http://localhost:8888/__jasmine__/jasmine.js:4320:27" // or "http://localhost:8888/__jasmine__/jasmine.js:4320:27" - { re: /^(([^@\s]+)@)?([^\s]+)$/, fnIx: 2, fileLineColIx: 3, style: 'webkit' } + { + re: /^(([^@\s]+)@)?([^\s]+)$/, + fnIx: 2, + fileLineColIx: 3, + style: 'webkit' + } ]; // regexes should capture the function name (if any) as group 1 @@ -6765,11 +7177,16 @@ getJasmineRequireObj().StackTrace = function(j$) { var convertedLine = first(framePatterns, function(pattern) { var overallMatch = line.match(pattern.re), fileLineColMatch; - if (!overallMatch) { return null; } + if (!overallMatch) { + return null; + } fileLineColMatch = overallMatch[pattern.fileLineColIx].match( - /^(.*):(\d+):\d+$/); - if (!fileLineColMatch) { return null; } + /^(.*):(\d+):\d+$/ + ); + if (!fileLineColMatch) { + return null; + } style = style || pattern.style; return { @@ -6882,7 +7299,11 @@ getJasmineRequireObj().Suite = function(j$) { Suite.prototype.getFullName = function() { var fullName = []; - for (var parentSuite = this; parentSuite; parentSuite = parentSuite.parentSuite) { + for ( + var parentSuite = this; + parentSuite; + parentSuite = parentSuite.parentSuite + ) { if (parentSuite.parentSuite) { fullName.unshift(parentSuite.description); } @@ -6919,7 +7340,7 @@ getJasmineRequireObj().Suite = function(j$) { }; function removeFns(queueableFns) { - for(var i = 0; i < queueableFns.length; i++) { + for (var i = 0; i < queueableFns.length; i++) { queueableFns[i].fn = null; } } @@ -6958,7 +7379,9 @@ getJasmineRequireObj().Suite = function(j$) { Suite.prototype.sharedUserContext = function() { if (!this.sharedContext) { - this.sharedContext = this.parentSuite ? this.parentSuite.clonedSharedUserContext() : new j$.UserContext(); + this.sharedContext = this.parentSuite + ? this.parentSuite.clonedSharedUserContext() + : new j$.UserContext(); } return this.sharedContext; @@ -6989,11 +7412,11 @@ getJasmineRequireObj().Suite = function(j$) { this.result.failedExpectations.push(failedExpectation); }; - Suite.prototype.addExpectationResult = function () { - if(isFailure(arguments)) { + Suite.prototype.addExpectationResult = function() { + if (isFailure(arguments)) { var data = arguments[1]; this.result.failedExpectations.push(this.expectationResultFactory(data)); - if(this.throwOnExpectationFailure) { + if (this.throwOnExpectationFailure) { throw new j$.errors.ExpectationFailed(); } } @@ -7003,7 +7426,9 @@ getJasmineRequireObj().Suite = function(j$) { if (typeof deprecation === 'string') { deprecation = { message: deprecation }; } - this.result.deprecationWarnings.push(this.expectationResultFactory(deprecation)); + this.result.deprecationWarnings.push( + this.expectationResultFactory(deprecation) + ); }; function isFailure(args) { @@ -7020,7 +7445,9 @@ if (typeof window == void 0 && typeof exports == 'object') { getJasmineRequireObj().Timer = function() { var defaultNow = (function(Date) { - return function() { return new Date().getTime(); }; + return function() { + return new Date().getTime(); + }; })(Date); function Timer(options) { @@ -7044,22 +7471,33 @@ getJasmineRequireObj().Timer = function() { getJasmineRequireObj().noopTimer = function() { return { start: function() {}, - elapsed: function() { return 0; } + elapsed: function() { + return 0; + } }; }; + getJasmineRequireObj().TreeProcessor = function() { function TreeProcessor(attrs) { var tree = attrs.tree, - runnableIds = attrs.runnableIds, - queueRunnerFactory = attrs.queueRunnerFactory, - nodeStart = attrs.nodeStart || function() {}, - nodeComplete = attrs.nodeComplete || function() {}, - orderChildren = attrs.orderChildren || function(node) { return node.children; }, - excludeNode = attrs.excludeNode || function(node) { return false; }, - stats = { valid: true }, - processed = false, - defaultMin = Infinity, - defaultMax = 1 - Infinity; + runnableIds = attrs.runnableIds, + queueRunnerFactory = attrs.queueRunnerFactory, + nodeStart = attrs.nodeStart || function() {}, + nodeComplete = attrs.nodeComplete || function() {}, + orderChildren = + attrs.orderChildren || + function(node) { + return node.children; + }, + excludeNode = + attrs.excludeNode || + function(node) { + return false; + }, + stats = { valid: true }, + processed = false, + defaultMin = Infinity, + defaultMax = 1 - Infinity; this.processTree = function() { processNode(tree, true); @@ -7108,13 +7546,15 @@ getJasmineRequireObj().TreeProcessor = function() { stats[node.id] = { excluded: excluded, willExecute: !excluded && !node.markedPending, - segments: [{ - index: 0, - owner: node, - nodes: [node], - min: startingMin(executableIndex), - max: startingMax(executableIndex) - }] + segments: [ + { + index: 0, + owner: node, + nodes: [node], + min: startingMin(executableIndex), + max: startingMax(executableIndex) + } + ] }; } else { var hasExecutableChild = false; @@ -7156,14 +7596,29 @@ getJasmineRequireObj().TreeProcessor = function() { return executableIndex === undefined ? defaultMax : executableIndex; } - function segmentChildren(node, orderedChildren, nodeStats, executableIndex) { - var currentSegment = { index: 0, owner: node, nodes: [], min: startingMin(executableIndex), max: startingMax(executableIndex) }, - result = [currentSegment], - lastMax = defaultMax, - orderedChildSegments = orderChildSegments(orderedChildren); + function segmentChildren( + node, + orderedChildren, + nodeStats, + executableIndex + ) { + var currentSegment = { + index: 0, + owner: node, + nodes: [], + min: startingMin(executableIndex), + max: startingMax(executableIndex) + }, + result = [currentSegment], + lastMax = defaultMax, + orderedChildSegments = orderChildSegments(orderedChildren); function isSegmentBoundary(minIndex) { - return lastMax !== defaultMax && minIndex !== defaultMin && lastMax < minIndex - 1; + return ( + lastMax !== defaultMax && + minIndex !== defaultMin && + lastMax < minIndex - 1 + ); } for (var i = 0; i < orderedChildSegments.length; i++) { @@ -7172,7 +7627,13 @@ getJasmineRequireObj().TreeProcessor = function() { minIndex = childSegment.min; if (isSegmentBoundary(minIndex)) { - currentSegment = {index: result.length, owner: node, nodes: [], min: defaultMin, max: defaultMax}; + currentSegment = { + index: result.length, + owner: node, + nodes: [], + min: defaultMin, + max: defaultMax + }; result.push(currentSegment); } @@ -7187,11 +7648,11 @@ getJasmineRequireObj().TreeProcessor = function() { function orderChildSegments(children) { var specifiedOrder = [], - unspecifiedOrder = []; + unspecifiedOrder = []; for (var i = 0; i < children.length; i++) { var child = children[i], - segments = stats[child.id].segments; + segments = stats[child.id].segments; for (var j = 0; j < segments.length; j++) { var seg = segments[j]; @@ -7222,7 +7683,7 @@ getJasmineRequireObj().TreeProcessor = function() { }; queueRunnerFactory({ - onComplete: function () { + onComplete: function() { var args = Array.prototype.slice.call(arguments, [0]); node.cleanupBeforeAfter(); nodeComplete(node, node.getResult(), function() { @@ -7231,7 +7692,7 @@ getJasmineRequireObj().TreeProcessor = function() { }, queueableFns: [onStart].concat(wrapChildren(node, segmentNumber)), userContext: node.sharedUserContext(), - onException: function () { + onException: function() { node.onException.apply(node, arguments); } }); @@ -7239,17 +7700,21 @@ getJasmineRequireObj().TreeProcessor = function() { }; } else { return { - fn: function(done) { node.execute(done, stats[node.id].excluded); } + fn: function(done) { + node.execute(done, stats[node.id].excluded); + } }; } } function wrapChildren(node, segmentNumber) { var result = [], - segmentChildren = stats[node.id].segments[segmentNumber].nodes; + segmentChildren = stats[node.id].segments[segmentNumber].nodes; for (var i = 0; i < segmentChildren.length; i++) { - result.push(executeNode(segmentChildren[i].owner, segmentChildren[i].index)); + result.push( + executeNode(segmentChildren[i].owner, segmentChildren[i].index) + ); } if (!stats[node.id].willExecute) { @@ -7264,8 +7729,7 @@ getJasmineRequireObj().TreeProcessor = function() { }; getJasmineRequireObj().UserContext = function(j$) { - function UserContext() { - } + function UserContext() {} UserContext.fromExisting = function(oldContext) { var context = new UserContext(); @@ -7279,7 +7743,7 @@ getJasmineRequireObj().UserContext = function(j$) { return context; }; - return UserContext; + return UserContext; }; getJasmineRequireObj().version = function() { diff --git a/package.json b/package.json index 72ed2916..9cefdc97 100644 --- a/package.json +++ b/package.json @@ -13,28 +13,69 @@ "bdd" ], "scripts": { - "test": "grunt jshint execSpecsInNode" + "pretest": "eslint src/**/*.js spec/**/*.js && prettier --check src/**/*.js spec/**/*.js", + "test": "grunt execSpecsInNode", + "cleanup": "prettier --write src/**/*.js spec/**/*.js" }, "description": "Official packaging of Jasmine's core files for use by Node.js projects.", "homepage": "https://jasmine.github.io", "main": "./lib/jasmine-core.js", "devDependencies": { "ejs": "^2.5.5", + "eslint": "^5.16.0", "express": "^4.16.4", "fast-glob": "^2.2.6", "grunt": "^1.0.4", "grunt-cli": "^1.3.2", "grunt-contrib-compress": "^1.3.0", "grunt-contrib-concat": "^1.0.1", - "grunt-contrib-jshint": "^2.1.0", "grunt-css-url-embed": "^1.11.1", "grunt-sass": "^3.0.2", "jasmine": "^3.4.0", "jsdom": "^15.0.0", "load-grunt-tasks": "^4.0.0", "node-sass": "^4.11.0", + "prettier": "1.17.1", "selenium-webdriver": "^3.6.0", "shelljs": "^0.8.3", "temp": "^0.9.0" + }, + "prettier": { + "singleQuote": true + }, + "eslintConfig": { + "rules": { + "quotes": [ + "error", + "single", + { + "avoidEscape": true + } + ], + "no-unused-vars": [ + "error", + { + "args": "none" + } + ], + "block-spacing": "error", + "comma-dangle": [ + "error", + "never" + ], + "func-call-spacing": [ + "error", + "never" + ], + "key-spacing": "error", + "no-tabs": "error", + "no-trailing-spaces": "error", + "no-whitespace-before-property": "error", + "semi": [ + "error", + "always" + ], + "space-before-blocks": "error" + } } } diff --git a/spec/core/AsyncExpectationSpec.js b/spec/core/AsyncExpectationSpec.js index 906b3081..42fcd544 100644 --- a/spec/core/AsyncExpectationSpec.js +++ b/spec/core/AsyncExpectationSpec.js @@ -1,22 +1,30 @@ describe('AsyncExpectation', function() { beforeEach(function() { - jasmineUnderTest.Expectation.addAsyncCoreMatchers(jasmineUnderTest.asyncMatchers); + jasmineUnderTest.Expectation.addAsyncCoreMatchers( + jasmineUnderTest.asyncMatchers + ); }); describe('Factory', function() { it('throws an Error if promises are not available', function() { - var thenable = {then: function() {}}, - options = {global: {}, actual: thenable} - function f() { jasmineUnderTest.Expectation.asyncFactory(options); } - expect(f).toThrowError('expectAsync is unavailable because the environment does not support promises.'); + var thenable = { then: function() {} }, + options = { global: {}, actual: thenable }; + function f() { + jasmineUnderTest.Expectation.asyncFactory(options); + } + expect(f).toThrowError( + 'expectAsync is unavailable because the environment does not support promises.' + ); }); it('throws an Error if the argument is not a promise', function() { jasmine.getEnv().requirePromises(); function f() { - jasmineUnderTest.Expectation.asyncFactory({actual: 'not a promise'}); + jasmineUnderTest.Expectation.asyncFactory({ actual: 'not a promise' }); } - expect(f).toThrowError('Expected expectAsync to be called with a promise.'); + expect(f).toThrowError( + 'Expected expectAsync to be called with a promise.' + ); }); }); @@ -33,7 +41,8 @@ describe('AsyncExpectation', function() { }); return expectation.not.toBeResolved().then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, + expect(addExpectationResult).toHaveBeenCalledWith( + false, jasmine.objectContaining({ passed: false, message: 'Expected a promise not to be resolved.' @@ -54,7 +63,8 @@ describe('AsyncExpectation', function() { }); return expectation.not.toBeResolved().then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(true, + expect(addExpectationResult).toHaveBeenCalledWith( + true, jasmine.objectContaining({ passed: true, message: '' @@ -68,7 +78,6 @@ describe('AsyncExpectation', function() { jasmine.getEnv().requirePromises(); var error = new Error('ExpectationSpec failure'); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = dummyPromise(), expectation = jasmineUnderTest.Expectation.asyncFactory({ @@ -76,22 +85,26 @@ describe('AsyncExpectation', function() { addExpectationResult: addExpectationResult }); - spyOn(expectation, 'toBeResolved') - .and.returnValue(Promise.reject(error)); + spyOn(expectation, 'toBeResolved').and.returnValue(Promise.reject(error)); - return expectation.toBeResolved() - .then( - function() { fail('Expected a rejection'); }, - function(e) { expect(e).toBe(error); } - ); + return expectation.toBeResolved().then( + function() { + fail('Expected a rejection'); + }, + function(e) { + expect(e).toBe(error); + } + ); }); describe('#withContext', function() { - it("prepends the context to the generated failure message", function() { + it('prepends the context to the generated failure message', function() { jasmine.getEnv().requirePromises(); var util = { - buildFailureMessage: function() { return 'failure message'; } + buildFailureMessage: function() { + return 'failure message'; + } }, addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation = jasmineUnderTest.Expectation.asyncFactory({ @@ -100,21 +113,26 @@ describe('AsyncExpectation', function() { util: util }); - return expectation.withContext('Some context').toBeResolved() - .then( - function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, - jasmine.objectContaining({ - message: 'Some context: failure message' - })); - }); + return expectation + .withContext('Some context') + .toBeResolved() + .then(function() { + expect(addExpectationResult).toHaveBeenCalledWith( + false, + jasmine.objectContaining({ + message: 'Some context: failure message' + }) + ); + }); }); - it("prepends the context to a custom failure message", function() { + it('prepends the context to a custom failure message', function() { jasmine.getEnv().requirePromises(); var util = { - buildFailureMessage: function() { return 'failure message'; } + buildFailureMessage: function() { + return 'failure message'; + } }, addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation = jasmineUnderTest.Expectation.asyncFactory({ @@ -123,22 +141,28 @@ describe('AsyncExpectation', function() { util: util }); - return expectation.withContext('Some context').toBeResolvedTo('a') - .then( - function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, - jasmine.objectContaining({ - message: "Some context: Expected a promise to be resolved to 'a' but it was rejected." - })); - }); + return expectation + .withContext('Some context') + .toBeResolvedTo('a') + .then(function() { + expect(addExpectationResult).toHaveBeenCalledWith( + false, + jasmine.objectContaining({ + message: + "Some context: Expected a promise to be resolved to 'a' but it was rejected." + }) + ); + }); }); - it("prepends the context to a custom failure message from a function", function() { + it('prepends the context to a custom failure message from a function', function() { pending('should actually work, but no custom matchers for async yet'); jasmine.getEnv().requirePromises(); var util = { - buildFailureMessage: function() { return 'failure message'; } + buildFailureMessage: function() { + return 'failure message'; + } }, addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.reject(), @@ -148,17 +172,20 @@ describe('AsyncExpectation', function() { util: util }); - return expectation.withContext('Some context').toBeResolved() - .then( - function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, - jasmine.objectContaining({ - message: 'Some context: msg' - })); - }); + return expectation + .withContext('Some context') + .toBeResolved() + .then(function() { + expect(addExpectationResult).toHaveBeenCalledWith( + false, + jasmine.objectContaining({ + message: 'Some context: msg' + }) + ); + }); }); - it("works with #not", function() { + it('works with #not', function() { jasmine.getEnv().requirePromises(); var addExpectationResult = jasmine.createSpy('addExpectationResult'), @@ -169,17 +196,20 @@ describe('AsyncExpectation', function() { util: jasmineUnderTest.matchersUtil }); - return expectation.withContext('Some context').not.toBeResolved() - .then( - function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, - jasmine.objectContaining({ - message: 'Some context: Expected a promise not to be resolved.' - })); - }); + return expectation + .withContext('Some context') + .not.toBeResolved() + .then(function() { + expect(addExpectationResult).toHaveBeenCalledWith( + false, + jasmine.objectContaining({ + message: 'Some context: Expected a promise not to be resolved.' + }) + ); + }); }); - it("works with #not and a custom message", function() { + it('works with #not and a custom message', function() { jasmine.getEnv().requirePromises(); var addExpectationResult = jasmine.createSpy('addExpectationResult'), @@ -190,19 +220,22 @@ describe('AsyncExpectation', function() { util: jasmineUnderTest.matchersUtil }); - return expectation.withContext('Some context').not.toBeResolvedTo('a') - .then( - function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, - jasmine.objectContaining({ - message: "Some context: Expected a promise not to be resolved to 'a'." - })); - }); + return expectation + .withContext('Some context') + .not.toBeResolvedTo('a') + .then(function() { + expect(addExpectationResult).toHaveBeenCalledWith( + false, + jasmine.objectContaining({ + message: + "Some context: Expected a promise not to be resolved to 'a'." + }) + ); + }); }); }); function dummyPromise() { - return new Promise(function(resolve, reject) { - }); + return new Promise(function(resolve, reject) {}); } }); diff --git a/spec/core/CallTrackerSpec.js b/spec/core/CallTrackerSpec.js index 3fdc8c60..474f674f 100644 --- a/spec/core/CallTrackerSpec.js +++ b/spec/core/CallTrackerSpec.js @@ -1,5 +1,5 @@ -describe("CallTracker", function() { - it("tracks that it was called when executed", function() { +describe('CallTracker', function() { + it('tracks that it was called when executed', function() { var callTracker = new jasmineUnderTest.CallTracker(); expect(callTracker.any()).toBe(false); @@ -9,7 +9,7 @@ describe("CallTracker", function() { expect(callTracker.any()).toBe(true); }); - it("tracks that number of times that it is executed", function() { + it('tracks that number of times that it is executed', function() { var callTracker = new jasmineUnderTest.CallTracker(); expect(callTracker.count()).toEqual(0); @@ -19,52 +19,52 @@ describe("CallTracker", function() { expect(callTracker.count()).toEqual(1); }); - it("tracks the params from each execution", function() { + it('tracks the params from each execution', function() { var callTracker = new jasmineUnderTest.CallTracker(); - callTracker.track({object: void 0, args: []}); - callTracker.track({object: {}, args: [0, "foo"]}); + callTracker.track({ object: void 0, args: [] }); + callTracker.track({ object: {}, args: [0, 'foo'] }); expect(callTracker.argsFor(0)).toEqual([]); - expect(callTracker.argsFor(1)).toEqual([0, "foo"]); + expect(callTracker.argsFor(1)).toEqual([0, 'foo']); }); - it("returns any empty array when there was no call", function() { + it('returns any empty array when there was no call', function() { var callTracker = new jasmineUnderTest.CallTracker(); expect(callTracker.argsFor(0)).toEqual([]); }); - it("allows access for the arguments for all calls", function() { + it('allows access for the arguments for all calls', function() { var callTracker = new jasmineUnderTest.CallTracker(); - callTracker.track({object: {}, args: []}); - callTracker.track({object: {}, args: [0, "foo"]}); + callTracker.track({ object: {}, args: [] }); + callTracker.track({ object: {}, args: [0, 'foo'] }); - expect(callTracker.allArgs()).toEqual([[], [0, "foo"]]); + expect(callTracker.allArgs()).toEqual([[], [0, 'foo']]); }); - it("tracks the context and arguments for each call", function() { + it('tracks the context and arguments for each call', function() { var callTracker = new jasmineUnderTest.CallTracker(); - callTracker.track({object: {}, args: []}); - callTracker.track({object: {}, args: [0, "foo"]}); + callTracker.track({ object: {}, args: [] }); + callTracker.track({ object: {}, args: [0, 'foo'] }); - expect(callTracker.all()[0]).toEqual({object: {}, args: []}); + expect(callTracker.all()[0]).toEqual({ object: {}, args: [] }); - expect(callTracker.all()[1]).toEqual({object: {}, args: [0, "foo"]}); + expect(callTracker.all()[1]).toEqual({ object: {}, args: [0, 'foo'] }); }); - it("simplifies access to the arguments for the last (most recent) call", function() { + it('simplifies access to the arguments for the last (most recent) call', function() { var callTracker = new jasmineUnderTest.CallTracker(); callTracker.track(); - callTracker.track({object: {}, args: [0, "foo"]}); + callTracker.track({ object: {}, args: [0, 'foo'] }); expect(callTracker.mostRecent()).toEqual({ object: {}, - args: [0, "foo"] + args: [0, 'foo'] }); }); @@ -74,12 +74,12 @@ describe("CallTracker", function() { expect(callTracker.mostRecent()).toBeFalsy(); }); - it("simplifies access to the arguments for the first (oldest) call", function() { + it('simplifies access to the arguments for the first (oldest) call', function() { var callTracker = new jasmineUnderTest.CallTracker(); - callTracker.track({object: {}, args: [0, "foo"]}); + callTracker.track({ object: {}, args: [0, 'foo'] }); - expect(callTracker.first()).toEqual({object: {}, args: [0, "foo"]}) + expect(callTracker.first()).toEqual({ object: {}, args: [0, 'foo'] }); }); it("returns a useful falsy value when there isn't a first (oldest) call", function() { @@ -88,12 +88,11 @@ describe("CallTracker", function() { expect(callTracker.first()).toBeFalsy(); }); - - it("allows the tracking to be reset", function() { + it('allows the tracking to be reset', function() { var callTracker = new jasmineUnderTest.CallTracker(); callTracker.track(); - callTracker.track({object: {}, args: [0, "foo"]}); + callTracker.track({ object: {}, args: [0, 'foo'] }); callTracker.reset(); expect(callTracker.any()).toBe(false); @@ -103,14 +102,17 @@ describe("CallTracker", function() { expect(callTracker.mostRecent()).toBeFalsy(); }); - it("allows object arguments to be shallow cloned", function() { + it('allows object arguments to be shallow cloned', function() { var callTracker = new jasmineUnderTest.CallTracker(); callTracker.saveArgumentsByValue(); - var objectArg = {"foo": "bar"}, - arrayArg = ["foo", "bar"]; + var objectArg = { foo: 'bar' }, + arrayArg = ['foo', 'bar']; - callTracker.track({object: {}, args: [objectArg, arrayArg, false, undefined, null, NaN, "", 0, 1.0]}); + callTracker.track({ + object: {}, + args: [objectArg, arrayArg, false, undefined, null, NaN, '', 0, 1.0] + }); expect(callTracker.mostRecent().args[0]).not.toBe(objectArg); expect(callTracker.mostRecent().args[0]).toEqual(objectArg); diff --git a/spec/core/ClearStackSpec.js b/spec/core/ClearStackSpec.js index 854d4478..9592b2d2 100644 --- a/spec/core/ClearStackSpec.js +++ b/spec/core/ClearStackSpec.js @@ -1,17 +1,23 @@ -describe("ClearStack", function() { - it("works in an integrationy way", function(done) { - var clearStack = jasmineUnderTest.getClearStack(jasmineUnderTest.getGlobal()); +describe('ClearStack', function() { + it('works in an integrationy way', function(done) { + var clearStack = jasmineUnderTest.getClearStack( + jasmineUnderTest.getGlobal() + ); clearStack(function() { done(); }); }); - it("uses setImmediate when available", function() { - var setImmediate = jasmine.createSpy('setImmediate').and.callFake(function(fn) { fn() }), - global = { setImmediate: setImmediate }, - clearStack = jasmineUnderTest.getClearStack(global), - called = false; + it('uses setImmediate when available', function() { + var setImmediate = jasmine + .createSpy('setImmediate') + .and.callFake(function(fn) { + fn(); + }), + global = { setImmediate: setImmediate }, + clearStack = jasmineUnderTest.getClearStack(global), + called = false; clearStack(function() { called = true; @@ -21,42 +27,50 @@ describe("ClearStack", function() { expect(setImmediate).toHaveBeenCalled(); }); - it("uses setTimeout instead of setImmediate every 10 calls to make sure we release the CPU", function() { + it('uses setTimeout instead of setImmediate every 10 calls to make sure we release the CPU', function() { var setImmediate = jasmine.createSpy('setImmediate'), - setTimeout = jasmine.createSpy('setTimeout'), - global = { setImmediate: setImmediate, setTimeout: setTimeout }, - clearStack = jasmineUnderTest.getClearStack(global); + setTimeout = jasmine.createSpy('setTimeout'), + global = { setImmediate: setImmediate, setTimeout: setTimeout }, + clearStack = jasmineUnderTest.getClearStack(global); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); expect(setImmediate).toHaveBeenCalled(); expect(setTimeout).not.toHaveBeenCalled(); - clearStack(function() { }); + clearStack(function() {}); expect(setImmediate.calls.count()).toEqual(9); expect(setTimeout.calls.count()).toEqual(1); - clearStack(function() { }); + clearStack(function() {}); expect(setImmediate.calls.count()).toEqual(10); expect(setTimeout.calls.count()).toEqual(1); }); - it("uses MessageChannels when available", function() { + it('uses MessageChannels when available', function() { var fakeChannel = { - port1: {}, - port2: { postMessage: function() { fakeChannel.port1.onmessage(); } } - }, - global = { MessageChannel: function() { return fakeChannel; } }, - clearStack = jasmineUnderTest.getClearStack(global), - called = false; + port1: {}, + port2: { + postMessage: function() { + fakeChannel.port1.onmessage(); + } + } + }, + global = { + MessageChannel: function() { + return fakeChannel; + } + }, + clearStack = jasmineUnderTest.getClearStack(global), + called = false; clearStack(function() { called = true; @@ -65,53 +79,66 @@ describe("ClearStack", function() { expect(called).toBe(true); }); - it("uses setTimeout instead of MessageChannel every 10 calls to make sure we release the CPU", function() { + it('uses setTimeout instead of MessageChannel every 10 calls to make sure we release the CPU', function() { var fakeChannel = { - port1: {}, - port2: { - postMessage: jasmine.createSpy('postMessage').and.callFake(function() { + port1: {}, + port2: { + postMessage: jasmine + .createSpy('postMessage') + .and.callFake(function() { fakeChannel.port1.onmessage(); }) - } + } + }, + setTimeout = jasmine.createSpy('setTimeout'), + global = { + MessageChannel: function() { + return fakeChannel; }, - setTimeout = jasmine.createSpy('setTimeout'), - global = { MessageChannel: function() { return fakeChannel; }, setTimeout: setTimeout }, - clearStack = jasmineUnderTest.getClearStack(global); + setTimeout: setTimeout + }, + clearStack = jasmineUnderTest.getClearStack(global); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); - clearStack(function() { }); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); + clearStack(function() {}); expect(fakeChannel.port2.postMessage).toHaveBeenCalled(); expect(setTimeout).not.toHaveBeenCalled(); - clearStack(function() { }); + clearStack(function() {}); expect(fakeChannel.port2.postMessage.calls.count()).toEqual(9); expect(setTimeout.calls.count()).toEqual(1); - clearStack(function() { }); + clearStack(function() {}); expect(fakeChannel.port2.postMessage.calls.count()).toEqual(10); expect(setTimeout.calls.count()).toEqual(1); }); - it("calls setTimeout when onmessage is called recursively", function() { + it('calls setTimeout when onmessage is called recursively', function() { var fakeChannel = { - port1: {}, - port2: { postMessage: function() { fakeChannel.port1.onmessage(); } } + port1: {}, + port2: { + postMessage: function() { + fakeChannel.port1.onmessage(); + } + } + }, + setTimeout = jasmine.createSpy('setTimeout'), + global = { + MessageChannel: function() { + return fakeChannel; }, - setTimeout = jasmine.createSpy('setTimeout'), - global = { - MessageChannel: function() { return fakeChannel; }, - setTimeout: setTimeout, - }, - clearStack = jasmineUnderTest.getClearStack(global), - fn = jasmine.createSpy("second clearStack function"); + setTimeout: setTimeout + }, + clearStack = jasmineUnderTest.getClearStack(global), + fn = jasmine.createSpy('second clearStack function'); clearStack(function() { clearStack(fn); @@ -121,11 +148,13 @@ describe("ClearStack", function() { expect(setTimeout).toHaveBeenCalledWith(fn, 0); }); - it("falls back to setTimeout", function() { - var setTimeout = jasmine.createSpy('setTimeout').and.callFake(function(fn) { fn() }), - global = { setTimeout: setTimeout }, - clearStack = jasmineUnderTest.getClearStack(global), - called = false; + it('falls back to setTimeout', function() { + var setTimeout = jasmine.createSpy('setTimeout').and.callFake(function(fn) { + fn(); + }), + global = { setTimeout: setTimeout }, + clearStack = jasmineUnderTest.getClearStack(global), + called = false; clearStack(function() { called = true; diff --git a/spec/core/ClockSpec.js b/spec/core/ClockSpec.js index b330b6c7..2aba566b 100644 --- a/spec/core/ClockSpec.js +++ b/spec/core/ClockSpec.js @@ -1,14 +1,29 @@ -describe("Clock", function() { +describe('Clock', function() { + var NODE_JS = + typeof process !== 'undefined' && + process.versions && + typeof process.versions.node === 'string'; - var NODE_JS = typeof process !== 'undefined' && process.versions && typeof process.versions.node === 'string'; - - it("does not replace setTimeout until it is installed", function() { - var fakeSetTimeout = jasmine.createSpy("global setTimeout"), + it('does not replace setTimeout until it is installed', function() { + var fakeSetTimeout = jasmine.createSpy('global setTimeout'), fakeGlobal = { setTimeout: fakeSetTimeout }, - delayedFunctionScheduler = jasmine.createSpyObj("delayedFunctionScheduler", ["scheduleFunction"]), - delayedFn = jasmine.createSpy("delayedFn"), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate); + delayedFunctionScheduler = jasmine.createSpyObj( + 'delayedFunctionScheduler', + ['scheduleFunction'] + ), + delayedFn = jasmine.createSpy('delayedFn'), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); fakeGlobal.setTimeout(delayedFn, 0); @@ -24,35 +39,62 @@ describe("Clock", function() { expect(fakeSetTimeout).not.toHaveBeenCalled(); }); - it("does not replace clearTimeout until it is installed", function() { - var fakeClearTimeout = jasmine.createSpy("global cleartimeout"), + it('does not replace clearTimeout until it is installed', function() { + var fakeClearTimeout = jasmine.createSpy('global cleartimeout'), fakeGlobal = { clearTimeout: fakeClearTimeout }, - delayedFunctionScheduler = jasmine.createSpyObj("delayedFunctionScheduler", ["removeFunctionWithId"]), - delayedFn = jasmine.createSpy("delayedFn"), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate); + delayedFunctionScheduler = jasmine.createSpyObj( + 'delayedFunctionScheduler', + ['removeFunctionWithId'] + ), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); - fakeGlobal.clearTimeout("foo"); + fakeGlobal.clearTimeout('foo'); - expect(fakeClearTimeout).toHaveBeenCalledWith("foo"); - expect(delayedFunctionScheduler.removeFunctionWithId).not.toHaveBeenCalled(); + expect(fakeClearTimeout).toHaveBeenCalledWith('foo'); + expect( + delayedFunctionScheduler.removeFunctionWithId + ).not.toHaveBeenCalled(); fakeClearTimeout.calls.reset(); clock.install(); - fakeGlobal.clearTimeout("foo"); + fakeGlobal.clearTimeout('foo'); expect(delayedFunctionScheduler.removeFunctionWithId).toHaveBeenCalled(); expect(fakeClearTimeout).not.toHaveBeenCalled(); }); - it("does not replace setInterval until it is installed", function() { - var fakeSetInterval = jasmine.createSpy("global setInterval"), + it('does not replace setInterval until it is installed', function() { + var fakeSetInterval = jasmine.createSpy('global setInterval'), fakeGlobal = { setInterval: fakeSetInterval }, - delayedFunctionScheduler = jasmine.createSpyObj("delayedFunctionScheduler", ["scheduleFunction"]), - delayedFn = jasmine.createSpy("delayedFn"), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate); + delayedFunctionScheduler = jasmine.createSpyObj( + 'delayedFunctionScheduler', + ['scheduleFunction'] + ), + delayedFn = jasmine.createSpy('delayedFn'), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); fakeGlobal.setInterval(delayedFn, 0); @@ -68,35 +110,55 @@ describe("Clock", function() { expect(fakeSetInterval).not.toHaveBeenCalled(); }); - it("does not replace clearInterval until it is installed", function() { - var fakeClearInterval = jasmine.createSpy("global clearinterval"), + it('does not replace clearInterval until it is installed', function() { + var fakeClearInterval = jasmine.createSpy('global clearinterval'), fakeGlobal = { clearInterval: fakeClearInterval }, - delayedFunctionScheduler = jasmine.createSpyObj("delayedFunctionScheduler", ["removeFunctionWithId"]), - delayedFn = jasmine.createSpy("delayedFn"), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate); + delayedFunctionScheduler = jasmine.createSpyObj( + 'delayedFunctionScheduler', + ['removeFunctionWithId'] + ), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); - fakeGlobal.clearInterval("foo"); + fakeGlobal.clearInterval('foo'); - expect(fakeClearInterval).toHaveBeenCalledWith("foo"); - expect(delayedFunctionScheduler.removeFunctionWithId).not.toHaveBeenCalled(); + expect(fakeClearInterval).toHaveBeenCalledWith('foo'); + expect( + delayedFunctionScheduler.removeFunctionWithId + ).not.toHaveBeenCalled(); fakeClearInterval.calls.reset(); clock.install(); - fakeGlobal.clearInterval("foo"); + fakeGlobal.clearInterval('foo'); expect(delayedFunctionScheduler.removeFunctionWithId).toHaveBeenCalled(); expect(fakeClearInterval).not.toHaveBeenCalled(); }); - it("does not install if the current setTimeout is not the original function on the global", function() { + it('does not install if the current setTimeout is not the original function on the global', function() { var originalFakeSetTimeout = function() {}, replacedSetTimeout = function() {}, fakeGlobal = { setTimeout: originalFakeSetTimeout }, - delayedFunctionSchedulerFactory = jasmine.createSpy('delayedFunctionSchedulerFactory'), + delayedFunctionSchedulerFactory = jasmine.createSpy( + 'delayedFunctionSchedulerFactory' + ), mockDate = {}, - clock = new jasmineUnderTest.Clock(fakeGlobal, delayedFunctionSchedulerFactory, mockDate); + clock = new jasmineUnderTest.Clock( + fakeGlobal, + delayedFunctionSchedulerFactory, + mockDate + ); fakeGlobal.setTimeout = replacedSetTimeout; @@ -108,13 +170,19 @@ describe("Clock", function() { expect(fakeGlobal.setTimeout).toBe(replacedSetTimeout); }); - it("does not install if the current clearTimeout is not the original function on the global", function() { + it('does not install if the current clearTimeout is not the original function on the global', function() { var originalFakeClearTimeout = function() {}, replacedClearTimeout = function() {}, fakeGlobal = { clearTimeout: originalFakeClearTimeout }, - delayedFunctionSchedulerFactory = jasmine.createSpy('delayedFunctionSchedulerFactory'), + delayedFunctionSchedulerFactory = jasmine.createSpy( + 'delayedFunctionSchedulerFactory' + ), mockDate = {}, - clock = new jasmineUnderTest.Clock(fakeGlobal, delayedFunctionSchedulerFactory, mockDate); + clock = new jasmineUnderTest.Clock( + fakeGlobal, + delayedFunctionSchedulerFactory, + mockDate + ); fakeGlobal.clearTimeout = replacedClearTimeout; @@ -126,13 +194,19 @@ describe("Clock", function() { expect(fakeGlobal.clearTimeout).toBe(replacedClearTimeout); }); - it("does not install if the current setInterval is not the original function on the global", function() { + it('does not install if the current setInterval is not the original function on the global', function() { var originalFakeSetInterval = function() {}, replacedSetInterval = function() {}, fakeGlobal = { setInterval: originalFakeSetInterval }, - delayedFunctionSchedulerFactory = jasmine.createSpy('delayedFunctionSchedulerFactory'), + delayedFunctionSchedulerFactory = jasmine.createSpy( + 'delayedFunctionSchedulerFactory' + ), mockDate = {}, - clock = new jasmineUnderTest.Clock(fakeGlobal, delayedFunctionSchedulerFactory, mockDate); + clock = new jasmineUnderTest.Clock( + fakeGlobal, + delayedFunctionSchedulerFactory, + mockDate + ); fakeGlobal.setInterval = replacedSetInterval; @@ -144,13 +218,19 @@ describe("Clock", function() { expect(fakeGlobal.setInterval).toBe(replacedSetInterval); }); - it("does not install if the current clearInterval is not the original function on the global", function() { + it('does not install if the current clearInterval is not the original function on the global', function() { var originalFakeClearInterval = function() {}, replacedClearInterval = function() {}, fakeGlobal = { clearInterval: originalFakeClearInterval }, - delayedFunctionSchedulerFactory = jasmine.createSpy('delayedFunctionSchedulerFactory'), + delayedFunctionSchedulerFactory = jasmine.createSpy( + 'delayedFunctionSchedulerFactory' + ), mockDate = {}, - clock = new jasmineUnderTest.Clock(fakeGlobal, delayedFunctionSchedulerFactory, mockDate); + clock = new jasmineUnderTest.Clock( + fakeGlobal, + delayedFunctionSchedulerFactory, + mockDate + ); fakeGlobal.clearInterval = replacedClearInterval; @@ -162,58 +242,84 @@ describe("Clock", function() { expect(fakeGlobal.clearInterval).toBe(replacedClearInterval); }); - it("replaces the global timer functions on uninstall", function() { - var fakeSetTimeout = jasmine.createSpy("global setTimeout"), - fakeClearTimeout = jasmine.createSpy("global clearTimeout"), - fakeSetInterval = jasmine.createSpy("global setInterval"), - fakeClearInterval = jasmine.createSpy("global clearInterval"), + it('replaces the global timer functions on uninstall', function() { + var fakeSetTimeout = jasmine.createSpy('global setTimeout'), + fakeClearTimeout = jasmine.createSpy('global clearTimeout'), + fakeSetInterval = jasmine.createSpy('global setInterval'), + fakeClearInterval = jasmine.createSpy('global clearInterval'), fakeGlobal = { setTimeout: fakeSetTimeout, clearTimeout: fakeClearTimeout, setInterval: fakeSetInterval, clearInterval: fakeClearInterval }, - delayedFunctionScheduler = jasmine.createSpyObj("delayedFunctionScheduler", ["scheduleFunction", "reset"]), - delayedFn = jasmine.createSpy("delayedFn"), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate); + delayedFunctionScheduler = jasmine.createSpyObj( + 'delayedFunctionScheduler', + ['scheduleFunction', 'reset'] + ), + delayedFn = jasmine.createSpy('delayedFn'), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); clock.install(); clock.uninstall(); fakeGlobal.setTimeout(delayedFn, 0); - fakeGlobal.clearTimeout("foo"); + fakeGlobal.clearTimeout('foo'); fakeGlobal.setInterval(delayedFn, 10); - fakeGlobal.clearInterval("bar"); + fakeGlobal.clearInterval('bar'); expect(fakeSetTimeout).toHaveBeenCalledWith(delayedFn, 0); - expect(fakeClearTimeout).toHaveBeenCalledWith("foo"); + expect(fakeClearTimeout).toHaveBeenCalledWith('foo'); expect(fakeSetInterval).toHaveBeenCalledWith(delayedFn, 10); - expect(fakeClearInterval).toHaveBeenCalledWith("bar"); + expect(fakeClearInterval).toHaveBeenCalledWith('bar'); expect(delayedFunctionScheduler.scheduleFunction).not.toHaveBeenCalled(); }); - it("can be installed for the duration of a passed in function and uninstalled when done", function() { - var fakeSetTimeout = jasmine.createSpy("global setTimeout"), - fakeClearTimeout = jasmine.createSpy("global clearTimeout"), - fakeSetInterval = jasmine.createSpy("global setInterval"), - fakeClearInterval = jasmine.createSpy("global clearInterval"), + it('can be installed for the duration of a passed in function and uninstalled when done', function() { + var fakeSetTimeout = jasmine.createSpy('global setTimeout'), + fakeClearTimeout = jasmine.createSpy('global clearTimeout'), + fakeSetInterval = jasmine.createSpy('global setInterval'), + fakeClearInterval = jasmine.createSpy('global clearInterval'), fakeGlobal = { setTimeout: fakeSetTimeout, clearTimeout: fakeClearTimeout, setInterval: fakeSetInterval, clearInterval: fakeClearInterval }, - delayedFunctionScheduler = jasmine.createSpyObj("delayedFunctionScheduler", ["scheduleFunction", "reset", "removeFunctionWithId"]), - delayedFn = jasmine.createSpy("delayedFn"), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate), + delayedFunctionScheduler = jasmine.createSpyObj( + 'delayedFunctionScheduler', + ['scheduleFunction', 'reset', 'removeFunctionWithId'] + ), + delayedFn = jasmine.createSpy('delayedFn'), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), passedFunctionCalled = false; clock.withMock(function() { fakeGlobal.setTimeout(delayedFn, 0); - fakeGlobal.clearTimeout("foo"); + fakeGlobal.clearTimeout('foo'); fakeGlobal.setInterval(delayedFn, 10); - fakeGlobal.clearInterval("bar"); + fakeGlobal.clearInterval('bar'); passedFunctionCalled = true; }); @@ -228,40 +334,53 @@ describe("Clock", function() { delayedFunctionScheduler.scheduleFunction.calls.reset(); fakeGlobal.setTimeout(delayedFn, 0); - fakeGlobal.clearTimeout("foo"); + fakeGlobal.clearTimeout('foo'); fakeGlobal.setInterval(delayedFn, 10); - fakeGlobal.clearInterval("bar"); + fakeGlobal.clearInterval('bar'); expect(fakeSetTimeout).toHaveBeenCalledWith(delayedFn, 0); - expect(fakeClearTimeout).toHaveBeenCalledWith("foo"); + expect(fakeClearTimeout).toHaveBeenCalledWith('foo'); expect(fakeSetInterval).toHaveBeenCalledWith(delayedFn, 10); - expect(fakeClearInterval).toHaveBeenCalledWith("bar"); + expect(fakeClearInterval).toHaveBeenCalledWith('bar'); expect(delayedFunctionScheduler.scheduleFunction).not.toHaveBeenCalled(); }); - it("can be installed for the duration of a passed in function and uninstalled if an error is thrown", function() { - var fakeSetTimeout = jasmine.createSpy("global setTimeout"), - fakeClearTimeout = jasmine.createSpy("global clearTimeout"), - fakeSetInterval = jasmine.createSpy("global setInterval"), - fakeClearInterval = jasmine.createSpy("global clearInterval"), + it('can be installed for the duration of a passed in function and uninstalled if an error is thrown', function() { + var fakeSetTimeout = jasmine.createSpy('global setTimeout'), + fakeClearTimeout = jasmine.createSpy('global clearTimeout'), + fakeSetInterval = jasmine.createSpy('global setInterval'), + fakeClearInterval = jasmine.createSpy('global clearInterval'), fakeGlobal = { setTimeout: fakeSetTimeout, clearTimeout: fakeClearTimeout, setInterval: fakeSetInterval, clearInterval: fakeClearInterval }, - delayedFunctionScheduler = jasmine.createSpyObj("delayedFunctionScheduler", ["scheduleFunction", "reset", "removeFunctionWithId"]), - delayedFn = jasmine.createSpy("delayedFn"), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate), + delayedFunctionScheduler = jasmine.createSpyObj( + 'delayedFunctionScheduler', + ['scheduleFunction', 'reset', 'removeFunctionWithId'] + ), + delayedFn = jasmine.createSpy('delayedFn'), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), passedFunctionCalled = false; expect(function() { clock.withMock(function() { fakeGlobal.setTimeout(delayedFn, 0); - fakeGlobal.clearTimeout("foo"); + fakeGlobal.clearTimeout('foo'); fakeGlobal.setInterval(delayedFn, 10); - fakeGlobal.clearInterval("bar"); + fakeGlobal.clearInterval('bar'); passedFunctionCalled = true; throw 'oops'; }); @@ -278,25 +397,35 @@ describe("Clock", function() { delayedFunctionScheduler.scheduleFunction.calls.reset(); fakeGlobal.setTimeout(delayedFn, 0); - fakeGlobal.clearTimeout("foo"); + fakeGlobal.clearTimeout('foo'); fakeGlobal.setInterval(delayedFn, 10); - fakeGlobal.clearInterval("bar"); + fakeGlobal.clearInterval('bar'); expect(fakeSetTimeout).toHaveBeenCalledWith(delayedFn, 0); - expect(fakeClearTimeout).toHaveBeenCalledWith("foo"); + expect(fakeClearTimeout).toHaveBeenCalledWith('foo'); expect(fakeSetInterval).toHaveBeenCalledWith(delayedFn, 10); - expect(fakeClearInterval).toHaveBeenCalledWith("bar"); + expect(fakeClearInterval).toHaveBeenCalledWith('bar'); expect(delayedFunctionScheduler.scheduleFunction).not.toHaveBeenCalled(); }); - it("schedules the delayed function (via setTimeout) with the fake timer", function() { + it('schedules the delayed function (via setTimeout) with the fake timer', function() { var fakeSetTimeout = jasmine.createSpy('setTimeout'), scheduleFunction = jasmine.createSpy('scheduleFunction'), delayedFunctionScheduler = { scheduleFunction: scheduleFunction }, fakeGlobal = { setTimeout: fakeSetTimeout }, delayedFn = jasmine.createSpy('delayedFn'), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), timeout = new clock.FakeTimeout(); clock.install(); @@ -305,21 +434,43 @@ describe("Clock", function() { expect(fakeSetTimeout).not.toHaveBeenCalled(); if (!NODE_JS) { - expect(delayedFunctionScheduler.scheduleFunction).toHaveBeenCalledWith(delayedFn, 0, ['a', 'b']); + expect(delayedFunctionScheduler.scheduleFunction).toHaveBeenCalledWith( + delayedFn, + 0, + ['a', 'b'] + ); } else { - expect(delayedFunctionScheduler.scheduleFunction).toHaveBeenCalledWith(delayedFn, 0, ['a', 'b'], false, timeout); + expect(delayedFunctionScheduler.scheduleFunction).toHaveBeenCalledWith( + delayedFn, + 0, + ['a', 'b'], + false, + timeout + ); } }); - it("returns an id for the delayed function", function() { + it('returns an id for the delayed function', function() { var fakeSetTimeout = jasmine.createSpy('setTimeout'), scheduleId = 123, - scheduleFunction = jasmine.createSpy('scheduleFunction').and.returnValue(scheduleId), - delayedFunctionScheduler = {scheduleFunction: scheduleFunction}, + scheduleFunction = jasmine + .createSpy('scheduleFunction') + .and.returnValue(scheduleId), + delayedFunctionScheduler = { scheduleFunction: scheduleFunction }, fakeGlobal = { setTimeout: fakeSetTimeout }, delayedFn = jasmine.createSpy('delayedFn'), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), timeout; clock.install(); @@ -332,30 +483,54 @@ describe("Clock", function() { } }); - it("clears the scheduled function with the scheduler", function() { + it('clears the scheduled function with the scheduler', function() { var fakeClearTimeout = jasmine.createSpy('clearTimeout'), - delayedFunctionScheduler = jasmine.createSpyObj('delayedFunctionScheduler', ['removeFunctionWithId']), + delayedFunctionScheduler = jasmine.createSpyObj( + 'delayedFunctionScheduler', + ['removeFunctionWithId'] + ), fakeGlobal = { setTimeout: fakeClearTimeout }, - delayedFn = jasmine.createSpy('delayedFn'), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate); + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); clock.install(); clock.clearTimeout(123); expect(fakeClearTimeout).not.toHaveBeenCalled(); - expect(delayedFunctionScheduler.removeFunctionWithId).toHaveBeenCalledWith(123); + expect(delayedFunctionScheduler.removeFunctionWithId).toHaveBeenCalledWith( + 123 + ); }); - it("schedules the delayed function with the fake timer", function() { + it('schedules the delayed function with the fake timer', function() { var fakeSetInterval = jasmine.createSpy('setInterval'), scheduleFunction = jasmine.createSpy('scheduleFunction'), - delayedFunctionScheduler = {scheduleFunction: scheduleFunction}, + delayedFunctionScheduler = { scheduleFunction: scheduleFunction }, fakeGlobal = { setInterval: fakeSetInterval }, delayedFn = jasmine.createSpy('delayedFn'), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate), - timeout = new clock.FakeTimeout; + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), + timeout = new clock.FakeTimeout(); clock.install(); clock.setInterval(delayedFn, 0, 'a', 'b'); @@ -363,21 +538,44 @@ describe("Clock", function() { expect(fakeSetInterval).not.toHaveBeenCalled(); if (!NODE_JS) { - expect(delayedFunctionScheduler.scheduleFunction).toHaveBeenCalledWith(delayedFn, 0, ['a', 'b'], true); + expect(delayedFunctionScheduler.scheduleFunction).toHaveBeenCalledWith( + delayedFn, + 0, + ['a', 'b'], + true + ); } else { - expect(delayedFunctionScheduler.scheduleFunction).toHaveBeenCalledWith(delayedFn, 0, ['a', 'b'], true, timeout); + expect(delayedFunctionScheduler.scheduleFunction).toHaveBeenCalledWith( + delayedFn, + 0, + ['a', 'b'], + true, + timeout + ); } }); - it("returns an id for the delayed function", function() { + it('returns an id for the delayed function', function() { var fakeSetInterval = jasmine.createSpy('setInterval'), scheduleId = 123, - scheduleFunction = jasmine.createSpy('scheduleFunction').and.returnValue(scheduleId), - delayedFunctionScheduler = {scheduleFunction: scheduleFunction}, + scheduleFunction = jasmine + .createSpy('scheduleFunction') + .and.returnValue(scheduleId), + delayedFunctionScheduler = { scheduleFunction: scheduleFunction }, fakeGlobal = { setInterval: fakeSetInterval }, delayedFn = jasmine.createSpy('delayedFn'), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), interval; clock.install(); @@ -390,38 +588,65 @@ describe("Clock", function() { } }); - it("clears the scheduled function with the scheduler", function() { + it('clears the scheduled function with the scheduler', function() { var clearInterval = jasmine.createSpy('clearInterval'), - delayedFunctionScheduler = jasmine.createSpyObj('delayedFunctionScheduler', ['removeFunctionWithId']), + delayedFunctionScheduler = jasmine.createSpyObj( + 'delayedFunctionScheduler', + ['removeFunctionWithId'] + ), fakeGlobal = { setInterval: clearInterval }, - delayedFn = jasmine.createSpy('delayedFn'), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock(fakeGlobal, function () { return delayedFunctionScheduler; }, mockDate); + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + fakeGlobal, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); clock.install(); clock.clearInterval(123); expect(clearInterval).not.toHaveBeenCalled(); - expect(delayedFunctionScheduler.removeFunctionWithId).toHaveBeenCalledWith(123); + expect(delayedFunctionScheduler.removeFunctionWithId).toHaveBeenCalledWith( + 123 + ); }); - it("gives you a friendly reminder if the Clock is not installed and you tick", function() { - var clock = new jasmineUnderTest.Clock({}, jasmine.createSpyObj('delayedFunctionScheduler', ['tick'])); + it('gives you a friendly reminder if the Clock is not installed and you tick', function() { + var clock = new jasmineUnderTest.Clock( + {}, + jasmine.createSpyObj('delayedFunctionScheduler', ['tick']) + ); expect(function() { clock.tick(50); }).toThrow(); }); }); -describe("Clock (acceptance)", function() { - it("can run setTimeouts/setIntervals synchronously", function() { +describe('Clock (acceptance)', function() { + it('can run setTimeouts/setIntervals synchronously', function() { var delayedFn1 = jasmine.createSpy('delayedFn1'), delayedFn2 = jasmine.createSpy('delayedFn2'), delayedFn3 = jasmine.createSpy('delayedFn3'), recurring1 = jasmine.createSpy('recurring1'), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock({setTimeout: setTimeout}, function () { return delayedFunctionScheduler; }, mockDate); + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + { setTimeout: setTimeout }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); clock.install(); @@ -464,11 +689,21 @@ describe("Clock (acceptance)", function() { expect(recurring1.calls.count()).toBe(4); }); - it("can clear a previously set timeout", function() { + it('can clear a previously set timeout', function() { var clearedFn = jasmine.createSpy('clearedFn'), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock({setTimeout: function() {}}, function () { return delayedFunctionScheduler; }, mockDate), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + { setTimeout: function() {} }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), timeoutId; clock.install(); @@ -485,8 +720,18 @@ describe("Clock (acceptance)", function() { it("can clear a previously set interval using that interval's handler", function() { var spy = jasmine.createSpy('spy'), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock({setInterval: function() {}}, function () { return delayedFunctionScheduler; }, mockDate), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + { setInterval: function() {} }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), intervalId; clock.install(); @@ -500,11 +745,21 @@ describe("Clock (acceptance)", function() { expect(spy.calls.count()).toEqual(1); }); - it("correctly schedules functions after the Clock has advanced", function() { + it('correctly schedules functions after the Clock has advanced', function() { var delayedFn1 = jasmine.createSpy('delayedFn1'), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock({setTimeout: function() {}}, function () { return delayedFunctionScheduler; }, mockDate); + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + { setTimeout: function() {} }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); clock.install(); @@ -516,14 +771,26 @@ describe("Clock (acceptance)", function() { expect(delayedFn1).toHaveBeenCalled(); }); - it("correctly schedules functions while the Clock is advancing", function() { + it('correctly schedules functions while the Clock is advancing', function() { var delayedFn1 = jasmine.createSpy('delayedFn1'), - delayedFn2 = jasmine.createSpy('delayedFn2'), - delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock({setTimeout: function() {}}, function () { return delayedFunctionScheduler; }, mockDate); + delayedFn2 = jasmine.createSpy('delayedFn2'), + delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + { setTimeout: function() {} }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); - delayedFn1.and.callFake(function() { clock.setTimeout(delayedFn2, 0); }); + delayedFn1.and.callFake(function() { + clock.setTimeout(delayedFn2, 0); + }); clock.install(); clock.setTimeout(delayedFn1, 5); @@ -535,14 +802,26 @@ describe("Clock (acceptance)", function() { expect(delayedFn2).toHaveBeenCalled(); }); - it("correctly calls functions scheduled while the Clock is advancing", function() { + it('correctly calls functions scheduled while the Clock is advancing', function() { var delayedFn1 = jasmine.createSpy('delayedFn1'), - delayedFn2 = jasmine.createSpy('delayedFn2'), - delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock({setTimeout: function() {}}, function () { return delayedFunctionScheduler; }, mockDate); + delayedFn2 = jasmine.createSpy('delayedFn2'), + delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + { setTimeout: function() {} }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); - delayedFn1.and.callFake(function() { clock.setTimeout(delayedFn2, 1); }); + delayedFn1.and.callFake(function() { + clock.setTimeout(delayedFn2, 1); + }); clock.install(); clock.setTimeout(delayedFn1, 5); @@ -551,12 +830,22 @@ describe("Clock (acceptance)", function() { expect(delayedFn2).toHaveBeenCalled(); }); - it("correctly schedules functions scheduled while the Clock is advancing but after the Clock is uninstalled", function() { + it('correctly schedules functions scheduled while the Clock is advancing but after the Clock is uninstalled', function() { var delayedFn1 = jasmine.createSpy('delayedFn1'), - delayedFn2 = jasmine.createSpy('delayedFn2'), - delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - mockDate = { install: function() {}, tick: function() {}, uninstall: function() {} }, - clock = new jasmineUnderTest.Clock({setTimeout: function() {}}, function () { return delayedFunctionScheduler; }, mockDate); + delayedFn2 = jasmine.createSpy('delayedFn2'), + delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), + mockDate = { + install: function() {}, + tick: function() {}, + uninstall: function() {} + }, + clock = new jasmineUnderTest.Clock( + { setTimeout: function() {} }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); delayedFn1.and.callFake(function() { clock.uninstall(); @@ -575,11 +864,17 @@ describe("Clock (acceptance)", function() { expect(delayedFn2).toHaveBeenCalled(); }); - it("does not mock the Date object by default", function() { - var delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - global = {Date: Date}, + it('does not mock the Date object by default', function() { + var delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), + global = { Date: Date }, mockDate = new jasmineUnderTest.MockDate(global), - clock = new jasmineUnderTest.Clock({setTimeout: setTimeout}, function () { return delayedFunctionScheduler; }, mockDate); + clock = new jasmineUnderTest.Clock( + { setTimeout: setTimeout }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); clock.install(); @@ -592,11 +887,17 @@ describe("Clock (acceptance)", function() { expect(new global.Date().getTime() - now).not.toEqual(50); }); - it("mocks the Date object and sets it to current time", function() { + it('mocks the Date object and sets it to current time', function() { var delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - global = {Date: Date}, + global = { Date: Date }, mockDate = new jasmineUnderTest.MockDate(global), - clock = new jasmineUnderTest.Clock({setTimeout: setTimeout}, function () { return delayedFunctionScheduler; }, mockDate); + clock = new jasmineUnderTest.Clock( + { setTimeout: setTimeout }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); clock.install().mockDate(); @@ -616,14 +917,19 @@ describe("Clock (acceptance)", function() { expect(timeoutDate - now).toEqual(150); }); - it("mocks the Date object and sets it to a given time", function() { + it('mocks the Date object and sets it to a given time', function() { var delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - global = {Date: Date}, + global = { Date: Date }, mockDate = new jasmineUnderTest.MockDate(global), - clock = new jasmineUnderTest.Clock({setTimeout: setTimeout}, function () { return delayedFunctionScheduler; }, mockDate), + clock = new jasmineUnderTest.Clock( + { setTimeout: setTimeout }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), baseTime = new Date(2013, 9, 23); - clock.install().mockDate(baseTime); var now = new global.Date().getTime(); @@ -644,17 +950,25 @@ describe("Clock (acceptance)", function() { expect(timeoutDate).toEqual(baseTime.getTime() + 150); }); - it("mocks the Date object and updates the date per delayed function", function () { + it('mocks the Date object and updates the date per delayed function', function() { var delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - global = {Date: Date}, + global = { Date: Date }, mockDate = new jasmineUnderTest.MockDate(global), - clock = new jasmineUnderTest.Clock({setTimeout: setTimeout}, function () { return delayedFunctionScheduler; }, mockDate), + clock = new jasmineUnderTest.Clock( + { setTimeout: setTimeout }, + function() { + return delayedFunctionScheduler; + }, + mockDate + ), baseTime = new Date(); clock.install().mockDate(baseTime); var actualTimes = []; - var pushCurrentTime = function() { actualTimes.push(global.Date().getTime()); }; + var pushCurrentTime = function() { + actualTimes.push(global.Date().getTime()); + }; delayedFunctionScheduler.scheduleFunction(pushCurrentTime); delayedFunctionScheduler.scheduleFunction(pushCurrentTime, 1); delayedFunctionScheduler.scheduleFunction(pushCurrentTime, 3); @@ -668,20 +982,30 @@ describe("Clock (acceptance)", function() { clock.tick(1); expect(global.Date().getTime()).toEqual(baseTime.getTime() + 5); - expect(actualTimes).toEqual([baseTime.getTime(), baseTime.getTime() + 1, baseTime.getTime() + 3]); + expect(actualTimes).toEqual([ + baseTime.getTime(), + baseTime.getTime() + 1, + baseTime.getTime() + 3 + ]); }); - it('correctly clears a scheduled timeout while the Clock is advancing', function () { + it('correctly clears a scheduled timeout while the Clock is advancing', function() { var delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - global = {Date: Date, setTimeout: undefined}, + global = { Date: Date, setTimeout: undefined }, mockDate = new jasmineUnderTest.MockDate(global), - clock = new jasmineUnderTest.Clock(global, function () { return delayedFunctionScheduler; }, mockDate); + clock = new jasmineUnderTest.Clock( + global, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); clock.install(); var timerId2; - global.setTimeout(function () { + global.setTimeout(function() { global.clearTimeout(timerId2); }, 100); @@ -690,16 +1014,22 @@ describe("Clock (acceptance)", function() { clock.tick(100); }); - it('correctly clears a scheduled interval while the Clock is advancing', function () { + it('correctly clears a scheduled interval while the Clock is advancing', function() { var delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - global = {Date: Date, setTimeout: undefined}, + global = { Date: Date, setTimeout: undefined }, mockDate = new jasmineUnderTest.MockDate(global), - clock = new jasmineUnderTest.Clock(global, function () { return delayedFunctionScheduler; }, mockDate); + clock = new jasmineUnderTest.Clock( + global, + function() { + return delayedFunctionScheduler; + }, + mockDate + ); clock.install(); var timerId2; - var timerId1 = global.setInterval(function () { + global.setInterval(function() { global.clearInterval(timerId2); }, 100); diff --git a/spec/core/DelayedFunctionSchedulerSpec.js b/spec/core/DelayedFunctionSchedulerSpec.js index f04d8f39..d06a66c1 100644 --- a/spec/core/DelayedFunctionSchedulerSpec.js +++ b/spec/core/DelayedFunctionSchedulerSpec.js @@ -1,5 +1,5 @@ -describe("DelayedFunctionScheduler", function() { - it("schedules a function for later execution", function() { +describe('DelayedFunctionScheduler', function() { + it('schedules a function for later execution', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'); @@ -12,9 +12,9 @@ describe("DelayedFunctionScheduler", function() { expect(fn).toHaveBeenCalled(); }); - it("schedules a string for later execution", function() { + it('schedules a string for later execution', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), - strfn = "horrible = true;"; + strfn = 'horrible = true;'; scheduler.scheduleFunction(strfn, 0); @@ -23,7 +23,7 @@ describe("DelayedFunctionScheduler", function() { expect(horrible).toEqual(true); }); - it("#tick defaults to 0", function() { + it('#tick defaults to 0', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'); @@ -36,7 +36,7 @@ describe("DelayedFunctionScheduler", function() { expect(fn).toHaveBeenCalled(); }); - it("defaults delay to 0", function() { + it('defaults delay to 0', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'); @@ -49,7 +49,7 @@ describe("DelayedFunctionScheduler", function() { expect(fn).toHaveBeenCalled(); }); - it("optionally passes params to scheduled functions", function() { + it('optionally passes params to scheduled functions', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'); @@ -62,7 +62,7 @@ describe("DelayedFunctionScheduler", function() { expect(fn).toHaveBeenCalledWith('foo', 'bar'); }); - it("scheduled fns can optionally reoccur", function() { + it('scheduled fns can optionally reoccur', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'); @@ -81,23 +81,20 @@ describe("DelayedFunctionScheduler", function() { scheduler.tick(21); expect(fn.calls.count()).toBe(4); - }); - it("increments scheduled fns ids unless one is passed", function() { + it('increments scheduled fns ids unless one is passed', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(); - expect(scheduler.scheduleFunction(function() { - }, 0)).toBe(1); - expect(scheduler.scheduleFunction(function() { - }, 0)).toBe(2); - expect(scheduler.scheduleFunction(function() { - }, 0, [], false, 123)).toBe(123); - expect(scheduler.scheduleFunction(function() { - }, 0)).toBe(3); + expect(scheduler.scheduleFunction(function() {}, 0)).toBe(1); + expect(scheduler.scheduleFunction(function() {}, 0)).toBe(2); + expect(scheduler.scheduleFunction(function() {}, 0, [], false, 123)).toBe( + 123 + ); + expect(scheduler.scheduleFunction(function() {}, 0)).toBe(3); }); - it("#removeFunctionWithId removes a previously scheduled function with a given id", function() { + it('#removeFunctionWithId removes a previously scheduled function with a given id', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'), timeoutKey; @@ -113,7 +110,7 @@ describe("DelayedFunctionScheduler", function() { expect(fn).not.toHaveBeenCalled(); }); - it("executes recurring functions interleaved with regular functions in the correct order", function() { + it('executes recurring functions interleaved with regular functions in the correct order', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'), recurringCallCount = 0, @@ -134,12 +131,12 @@ describe("DelayedFunctionScheduler", function() { expect(fn).toHaveBeenCalled(); }); - it("schedules a function for later execution during a tick", function () { + it('schedules a function for later execution during a tick', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'), fnDelay = 10; - scheduler.scheduleFunction(function () { + scheduler.scheduleFunction(function() { scheduler.scheduleFunction(fn, fnDelay); }, 0); @@ -150,13 +147,13 @@ describe("DelayedFunctionScheduler", function() { expect(fn).toHaveBeenCalled(); }); - it("#removeFunctionWithId removes a previously scheduled function with a given id during a tick", function () { + it('#removeFunctionWithId removes a previously scheduled function with a given id during a tick', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'), fnDelay = 10, timeoutKey; - scheduler.scheduleFunction(function () { + scheduler.scheduleFunction(function() { scheduler.removeFunctionWithId(timeoutKey); }, 0); timeoutKey = scheduler.scheduleFunction(fn, fnDelay); @@ -168,7 +165,7 @@ describe("DelayedFunctionScheduler", function() { expect(fn).not.toHaveBeenCalled(); }); - it("executes recurring functions interleaved with regular functions and functions scheduled during a tick in the correct order", function () { + it('executes recurring functions interleaved with regular functions and functions scheduled during a tick in the correct order', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'), recurringCallCount = 0, @@ -185,7 +182,7 @@ describe("DelayedFunctionScheduler", function() { scheduling = jasmine.createSpy('scheduling').and.callFake(function() { expect(recurring.calls.count()).toBe(3); expect(fn).not.toHaveBeenCalled(); - scheduler.scheduleFunction(innerFn, 10); // 41ms absolute + scheduler.scheduleFunction(innerFn, 10); // 41ms absolute }); scheduler.scheduleFunction(recurring, 10, [], true); @@ -201,7 +198,7 @@ describe("DelayedFunctionScheduler", function() { expect(innerFn).toHaveBeenCalled(); }); - it("executes recurring functions after rescheduling them", function () { + it('executes recurring functions after rescheduling them', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), recurring = function() { expect(scheduler.scheduleFunction).toHaveBeenCalled(); @@ -209,12 +206,12 @@ describe("DelayedFunctionScheduler", function() { scheduler.scheduleFunction(recurring, 10, [], true); - spyOn(scheduler, "scheduleFunction"); + spyOn(scheduler, 'scheduleFunction'); scheduler.tick(10); }); - it("removes functions during a tick that runs the function", function() { + it('removes functions during a tick that runs the function', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), spy = jasmine.createSpy('fn'), spyAndRemove = jasmine.createSpy('fn'), @@ -235,14 +232,14 @@ describe("DelayedFunctionScheduler", function() { expect(spyAndRemove).toHaveBeenCalled(); }); - it("removes functions during the first tick that runs the function", function() { + it('removes functions during the first tick that runs the function', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'), fnDelay = 10, timeoutKey; timeoutKey = scheduler.scheduleFunction(fn, fnDelay, [], true); - scheduler.scheduleFunction(function () { + scheduler.scheduleFunction(function() { scheduler.removeFunctionWithId(timeoutKey); }, fnDelay); @@ -257,8 +254,7 @@ describe("DelayedFunctionScheduler", function() { it("does not remove a function that hasn't been added yet", function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), fn = jasmine.createSpy('fn'), - fnDelay = 10, - timeoutKey; + fnDelay = 10; scheduler.removeFunctionWithId('foo'); scheduler.scheduleFunction(fn, fnDelay, [], false, 'foo'); @@ -270,17 +266,16 @@ describe("DelayedFunctionScheduler", function() { expect(fn).toHaveBeenCalled(); }); - it("updates the mockDate per scheduled time", function () { + it('updates the mockDate per scheduled time', function() { var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(), tickDate = jasmine.createSpy('tickDate'); - scheduler.scheduleFunction(function() {}); - scheduler.scheduleFunction(function() {}, 1); + scheduler.scheduleFunction(function() {}); + scheduler.scheduleFunction(function() {}, 1); - scheduler.tick(1, tickDate); + scheduler.tick(1, tickDate); - expect(tickDate).toHaveBeenCalledWith(0); - expect(tickDate).toHaveBeenCalledWith(1); - }) + expect(tickDate).toHaveBeenCalledWith(0); + expect(tickDate).toHaveBeenCalledWith(1); + }); }); - diff --git a/spec/core/EnvSpec.js b/spec/core/EnvSpec.js index 0cdad2cd..72c8d979 100644 --- a/spec/core/EnvSpec.js +++ b/spec/core/EnvSpec.js @@ -1,54 +1,63 @@ // TODO: Fix these unit tests! -describe("Env", function() { +describe('Env', function() { var env; beforeEach(function() { env = new jasmineUnderTest.Env(); }); - describe("#pending", function() { - it("throws the Pending Spec exception", function() { + describe('#pending', function() { + it('throws the Pending Spec exception', function() { expect(function() { env.pending(); }).toThrow(jasmineUnderTest.Spec.pendingSpecExceptionMessage); }); - it("throws the Pending Spec exception with a custom message", function() { + it('throws the Pending Spec exception with a custom message', function() { expect(function() { env.pending('custom message'); - }).toThrow(jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'custom message'); + }).toThrow( + jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'custom message' + ); }); }); - describe("#topSuite", function() { - it("returns the Jasmine top suite for users to traverse the spec tree", function() { + describe('#topSuite', function() { + it('returns the Jasmine top suite for users to traverse the spec tree', function() { var suite = env.topSuite(); expect(suite.description).toEqual('Jasmine__TopLevel__Suite'); }); }); it('can configure specs to throw errors on expectation failures', function() { - env.configure({oneFailurePerSpec: true}); + env.configure({ oneFailurePerSpec: true }); spyOn(jasmineUnderTest, 'Spec'); env.it('foo', function() {}); - expect(jasmineUnderTest.Spec).toHaveBeenCalledWith(jasmine.objectContaining({ - throwOnExpectationFailure: true - })); + expect(jasmineUnderTest.Spec).toHaveBeenCalledWith( + jasmine.objectContaining({ + throwOnExpectationFailure: true + }) + ); }); it('can configure suites to throw errors on expectation failures', function() { - env.configure({oneFailurePerSpec: true}); + env.configure({ oneFailurePerSpec: true }); spyOn(jasmineUnderTest, 'Suite'); env.describe('foo', function() {}); - expect(jasmineUnderTest.Suite).toHaveBeenCalledWith(jasmine.objectContaining({ - throwOnExpectationFailure: true - })); + expect(jasmineUnderTest.Suite).toHaveBeenCalledWith( + jasmine.objectContaining({ + throwOnExpectationFailure: true + }) + ); }); describe('promise library', function() { it('can be configured with a custom library', function() { - var myLibrary = { resolve: jasmine.createSpy(), reject: jasmine.createSpy() }; + var myLibrary = { + resolve: jasmine.createSpy(), + reject: jasmine.createSpy() + }; env.configure({ Promise: myLibrary }); }); @@ -57,28 +66,34 @@ describe("Env", function() { expect(function() { env.configure({ Promise: myLibrary }); - }).toThrowError('Custom promise library missing `resolve`/`reject` functions'); + }).toThrowError( + 'Custom promise library missing `resolve`/`reject` functions' + ); }); }); it('defaults to multiple failures for specs', function() { spyOn(jasmineUnderTest, 'Spec'); - env.it('bar', function() {}); - expect(jasmineUnderTest.Spec).toHaveBeenCalledWith(jasmine.objectContaining({ - throwOnExpectationFailure: false - })); + env.it('bar', function() {}); + expect(jasmineUnderTest.Spec).toHaveBeenCalledWith( + jasmine.objectContaining({ + throwOnExpectationFailure: false + }) + ); }); it('defaults to multiple failures for suites', function() { spyOn(jasmineUnderTest, 'Suite'); env.describe('foo', function() {}); - expect(jasmineUnderTest.Suite).toHaveBeenCalledWith(jasmine.objectContaining({ - throwOnExpectationFailure: false - })); + expect(jasmineUnderTest.Suite).toHaveBeenCalledWith( + jasmine.objectContaining({ + throwOnExpectationFailure: false + }) + ); }); - describe('#describe', function () { - it("throws an error when given arguments", function() { + describe('#describe', function() { + it('throws an error when given arguments', function() { expect(function() { env.describe('done method', function(done) {}); }).toThrowError('describe does not expect any arguments'); @@ -92,29 +107,41 @@ describe("Env", function() { // anything other than a function throws an error. expect(function() { env.describe('undefined arg', undefined); - }).toThrowError(/describe expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/); + }).toThrowError( + /describe expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/ + ); expect(function() { env.describe('null arg', null); - }).toThrowError(/describe expects a function argument; received \[object (Null|DOMWindow|Object)\]/); + }).toThrowError( + /describe expects a function argument; received \[object (Null|DOMWindow|Object)\]/ + ); expect(function() { env.describe('array arg', []); - }).toThrowError('describe expects a function argument; received [object Array]'); + }).toThrowError( + 'describe expects a function argument; received [object Array]' + ); expect(function() { env.describe('object arg', {}); - }).toThrowError('describe expects a function argument; received [object Object]'); + }).toThrowError( + 'describe expects a function argument; received [object Object]' + ); expect(function() { env.describe('fn arg', function() {}); - }).not.toThrowError('describe expects a function argument; received [object Function]'); + }).not.toThrowError( + 'describe expects a function argument; received [object Function]' + ); }); }); - describe('#it', function () { + describe('#it', function() { it('throws an error when it receives a non-fn argument', function() { expect(function() { env.it('undefined arg', null); - }).toThrowError(/it expects a function argument; received \[object (Null|DOMWindow|Object)\]/); + }).toThrowError( + /it expects a function argument; received \[object (Null|DOMWindow|Object)\]/ + ); }); it('does not throw when it is not given a fn argument', function() { @@ -144,7 +171,9 @@ describe("Env", function() { it('throws an error when it receives a non-fn argument', function() { expect(function() { env.xit('undefined arg', null); - }).toThrowError(/xit expects a function argument; received \[object (Null|DOMWindow|Object)\]/); + }).toThrowError( + /xit expects a function argument; received \[object (Null|DOMWindow|Object)\]/ + ); }); it('does not throw when it is not given a fn argument', function() { @@ -161,19 +190,23 @@ describe("Env", function() { }); }); - describe('#fit', function () { + describe('#fit', function() { it('throws an error when it receives a non-fn argument', function() { expect(function() { env.fit('undefined arg', undefined); - }).toThrowError(/fit expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/); + }).toThrowError( + /fit expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/ + ); }); }); - describe('#beforeEach', function () { + describe('#beforeEach', function() { it('throws an error when it receives a non-fn argument', function() { expect(function() { env.beforeEach(undefined); - }).toThrowError(/beforeEach expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/); + }).toThrowError( + /beforeEach expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/ + ); }); it('accepts an async function', function() { @@ -184,11 +217,13 @@ describe("Env", function() { }); }); - describe('#beforeAll', function () { + describe('#beforeAll', function() { it('throws an error when it receives a non-fn argument', function() { expect(function() { env.beforeAll(undefined); - }).toThrowError(/beforeAll expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/); + }).toThrowError( + /beforeAll expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/ + ); }); it('accepts an async function', function() { @@ -199,11 +234,13 @@ describe("Env", function() { }); }); - describe('#afterEach', function () { + describe('#afterEach', function() { it('throws an error when it receives a non-fn argument', function() { expect(function() { env.afterEach(undefined); - }).toThrowError(/afterEach expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/); + }).toThrowError( + /afterEach expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/ + ); }); it('accepts an async function', function() { @@ -214,11 +251,13 @@ describe("Env", function() { }); }); - describe('#afterAll', function () { + describe('#afterAll', function() { it('throws an error when it receives a non-fn argument', function() { expect(function() { env.afterAll(undefined); - }).toThrowError(/afterAll expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/); + }).toThrowError( + /afterAll expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/ + ); }); it('accepts an async function', function() { @@ -231,7 +270,11 @@ describe("Env", function() { describe('when not constructed with suppressLoadErrors: true', function() { it('installs a global error handler on construction', function() { - var globalErrors = jasmine.createSpyObj('globalErrors', ['install', 'pushListener', 'popListener']); + var globalErrors = jasmine.createSpyObj('globalErrors', [ + 'install', + 'pushListener', + 'popListener' + ]); spyOn(jasmineUnderTest, 'GlobalErrors').and.returnValue(globalErrors); new jasmineUnderTest.Env(); expect(globalErrors.install).toHaveBeenCalled(); @@ -240,9 +283,13 @@ describe("Env", function() { describe('when constructed with suppressLoadErrors: true', function() { it('does not install a global error handler until execute is called', function() { - var globalErrors = jasmine.createSpyObj('globalErrors', ['install', 'pushListener', 'popListener']); + var globalErrors = jasmine.createSpyObj('globalErrors', [ + 'install', + 'pushListener', + 'popListener' + ]); spyOn(jasmineUnderTest, 'GlobalErrors').and.returnValue(globalErrors); - env = new jasmineUnderTest.Env({suppressLoadErrors: true}); + env = new jasmineUnderTest.Env({ suppressLoadErrors: true }); expect(globalErrors.install).not.toHaveBeenCalled(); env.execute(); expect(globalErrors.install).toHaveBeenCalled(); diff --git a/spec/core/ExceptionFormatterSpec.js b/spec/core/ExceptionFormatterSpec.js index 40316190..2242cf27 100644 --- a/spec/core/ExceptionFormatterSpec.js +++ b/spec/core/ExceptionFormatterSpec.js @@ -1,5 +1,5 @@ -describe("ExceptionFormatter", function() { - describe("#message", function() { +describe('ExceptionFormatter', function() { + describe('#message', function() { it('formats Firefox exception messages', function() { var sampleFirefoxException = { fileName: 'foo.js', @@ -10,7 +10,9 @@ describe("ExceptionFormatter", function() { exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(), message = exceptionFormatter.message(sampleFirefoxException); - expect(message).toEqual('A Classic Mistake: you got your foo in my bar in foo.js (line 1978)'); + expect(message).toEqual( + 'A Classic Mistake: you got your foo in my bar in foo.js (line 1978)' + ); }); it('formats Webkit exception messages', function() { @@ -23,7 +25,9 @@ describe("ExceptionFormatter", function() { exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(), message = exceptionFormatter.message(sampleWebkitException); - expect(message).toEqual('A Classic Mistake: you got your foo in my bar in foo.js (line 1978)'); + expect(message).toEqual( + 'A Classic Mistake: you got your foo in my bar in foo.js (line 1978)' + ); }); it('formats V8 exception messages', function() { @@ -38,10 +42,10 @@ describe("ExceptionFormatter", function() { }); it('formats unnamed exceptions with message', function() { - var unnamedError = {message: 'This is an unnamed error message.'}; + var unnamedError = { message: 'This is an unnamed error message.' }; var exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(), - message = exceptionFormatter.message(unnamedError); + message = exceptionFormatter.message(unnamedError); expect(message).toEqual('This is an unnamed error message.'); }); @@ -54,32 +58,39 @@ describe("ExceptionFormatter", function() { var emptyError = new EmptyError(); var exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(), - message = exceptionFormatter.message(emptyError); + message = exceptionFormatter.message(emptyError); expect(message).toEqual('[EmptyError] thrown'); }); it("formats thrown exceptions that aren't errors", function() { - var thrown = "crazy error", - exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(), - message = exceptionFormatter.message(thrown); + var thrown = 'crazy error', + exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(), + message = exceptionFormatter.message(thrown); - expect(message).toEqual("crazy error thrown"); + expect(message).toEqual('crazy error thrown'); }); }); - describe("#stack", function() { - it("formats stack traces", function() { + describe('#stack', function() { + it('formats stack traces', function() { var error; - try { throw new Error("an error") } catch(e) { error = e; } + try { + throw new Error('an error'); + } catch (e) { + error = e; + } - expect(new jasmineUnderTest.ExceptionFormatter().stack(error)).toMatch(/ExceptionFormatterSpec\.js.*\d+/) + expect(new jasmineUnderTest.ExceptionFormatter().stack(error)).toMatch( + /ExceptionFormatterSpec\.js.*\d+/ + ); }); - it("filters Jasmine stack frames from V8 style traces", function() { + it('filters Jasmine stack frames from V8 style traces', function() { var error = { message: 'nope', - stack: 'Error: nope\n' + + stack: + 'Error: nope\n' + ' at fn1 (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' + ' at fn2 (http://localhost:8888/__jasmine__/jasmine.js:4320:20)\n' + ' at fn3 (http://localhost:8888/__jasmine__/jasmine.js:4320:20)\n' + @@ -89,16 +100,18 @@ describe("ExceptionFormatter", function() { jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js' }); var result = subject.stack(error); - expect(result).toEqual('Error: nope\n' + + expect(result).toEqual( + 'Error: nope\n' + ' at fn1 (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' + ' at \n' + ' at fn4 (http://localhost:8888/__spec__/core/UtilSpec.js:110:19)' ); }); - it("filters Jasmine stack frames from Webkit style traces", function() { + it('filters Jasmine stack frames from Webkit style traces', function() { var error = { - stack: 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28\n' + + stack: + 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28\n' + 'fn1@http://localhost:8888/__jasmine__/jasmine.js:4320:27\n' + 'fn2@http://localhost:8888/__jasmine__/jasmine.js:4320:27\n' + 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28' @@ -114,9 +127,13 @@ describe("ExceptionFormatter", function() { ); }); - it("filters Jasmine stack frames in this environment", function() { + it('filters Jasmine stack frames in this environment', function() { var error, i; - try { throw new Error("an error"); } catch(e) { error = e; } + try { + throw new Error('an error'); + } catch (e) { + error = e; + } var subject = new jasmineUnderTest.ExceptionFormatter({ jasmineFile: jasmine.util.jasmineFile() }); @@ -136,9 +153,14 @@ describe("ExceptionFormatter", function() { } }); - it("handles multiline error messages in this environment", function() { - var error, i, msg = "an error\nwith two lines"; - try { throw new Error(msg); } catch(e) { error = e; } + it('handles multiline error messages in this environment', function() { + var error, + msg = 'an error\nwith two lines'; + try { + throw new Error(msg); + } catch (e) { + error = e; + } if (error.stack.indexOf(msg) === -1) { pending("Stack traces don't have messages in this environment"); @@ -155,19 +177,22 @@ describe("ExceptionFormatter", function() { expect(lines[3]).toMatch(//); }); - it("returns null if no Error provided", function() { + it('returns null if no Error provided', function() { expect(new jasmineUnderTest.ExceptionFormatter().stack()).toBeNull(); }); - it("includes error properties in stack", function() { + it('includes error properties in stack', function() { var error; - try { throw new Error("an error") } catch(e) { error = e; } + try { + throw new Error('an error'); + } catch (e) { + error = e; + } error.someProperty = 'hello there'; var result = new jasmineUnderTest.ExceptionFormatter().stack(error); expect(result).toMatch(/error properties:.*someProperty.*hello there/); }); - }); }); diff --git a/spec/core/ExceptionsSpec.js b/spec/core/ExceptionsSpec.js index e0a141a6..538c682d 100644 --- a/spec/core/ExceptionsSpec.js +++ b/spec/core/ExceptionsSpec.js @@ -7,11 +7,17 @@ describe('Exceptions:', function() { it('should handle exceptions thrown, but continue', function(done) { var secondTest = jasmine.createSpy('second test'); - env.describe('Suite for handles exceptions', function () { - env.it('should be a test that fails because it throws an exception', function() { - throw new Error(); - }); - env.it('should be a passing test that runs after exceptions are thrown from a async test', secondTest); + env.describe('Suite for handles exceptions', function() { + env.it( + 'should be a test that fails because it throws an exception', + function() { + throw new Error(); + } + ); + env.it( + 'should be a passing test that runs after exceptions are thrown from a async test', + secondTest + ); }); var expectations = function() { @@ -23,14 +29,14 @@ describe('Exceptions:', function() { env.execute(); }); - it("should handle exceptions thrown directly in top-level describe blocks and continue", function(done) { - var secondDescribe = jasmine.createSpy("second describe"); - env.describe("a suite that throws an exception", function () { - env.it("is a test that should pass", function () { + it('should handle exceptions thrown directly in top-level describe blocks and continue', function(done) { + var secondDescribe = jasmine.createSpy('second describe'); + env.describe('a suite that throws an exception', function() { + env.it('is a test that should pass', function() { this.expect(true).toEqual(true); }); - throw new Error("top level error"); + throw new Error('top level error'); }); env.describe("a suite that doesn't throw an exception", secondDescribe); @@ -43,4 +49,3 @@ describe('Exceptions:', function() { env.execute(); }); }); - diff --git a/spec/core/ExpectationFilterChainSpec.js b/spec/core/ExpectationFilterChainSpec.js index 195fbe27..911f6b30 100644 --- a/spec/core/ExpectationFilterChainSpec.js +++ b/spec/core/ExpectationFilterChainSpec.js @@ -6,7 +6,7 @@ describe('ExpectationFilterChain', function() { orig = new jasmineUnderTest.ExpectationFilterChain({ modifyFailureMessage: first }), - added = orig.addFilter({selectComparisonFunc: second}); + added = orig.addFilter({ selectComparisonFunc: second }); added.modifyFailureMessage(); expect(first).toHaveBeenCalled(); @@ -18,7 +18,7 @@ describe('ExpectationFilterChain', function() { var orig = new jasmineUnderTest.ExpectationFilterChain({}), f = jasmine.createSpy('f'); - orig.addFilter({selectComparisonFunc: f}); + orig.addFilter({ selectComparisonFunc: f }); orig.selectComparisonFunc(); expect(f).not.toHaveBeenCalled(); @@ -39,8 +39,8 @@ describe('ExpectationFilterChain', function() { var first = jasmine.createSpy('first').and.returnValue('first'), second = jasmine.createSpy('second').and.returnValue('second'), chain = new jasmineUnderTest.ExpectationFilterChain() - .addFilter({selectComparisonFunc: first}) - .addFilter({selectComparisonFunc: second}), + .addFilter({ selectComparisonFunc: first }) + .addFilter({ selectComparisonFunc: second }), matcher = {}, result; @@ -67,17 +67,27 @@ describe('ExpectationFilterChain', function() { var first = jasmine.createSpy('first').and.returnValue('first'), second = jasmine.createSpy('second').and.returnValue('second'), chain = new jasmineUnderTest.ExpectationFilterChain() - .addFilter({buildFailureMessage: first}) - .addFilter({buildFailureMessage: second}), - matcherResult = {pass: false}, + .addFilter({ buildFailureMessage: first }) + .addFilter({ buildFailureMessage: second }), + matcherResult = { pass: false }, matcherName = 'foo', args = [], util = {}, result; - result = chain.buildFailureMessage(matcherResult, matcherName, args, util); + result = chain.buildFailureMessage( + matcherResult, + matcherName, + args, + util + ); - expect(first).toHaveBeenCalledWith(matcherResult, matcherName, args, util); + expect(first).toHaveBeenCalledWith( + matcherResult, + matcherName, + args, + util + ); expect(second).not.toHaveBeenCalled(); expect(result).toEqual('first'); }); @@ -98,8 +108,8 @@ describe('ExpectationFilterChain', function() { var first = jasmine.createSpy('first').and.returnValue('first'), second = jasmine.createSpy('second').and.returnValue('second'), chain = new jasmineUnderTest.ExpectationFilterChain() - .addFilter({modifyFailureMessage: first}) - .addFilter({modifyFailureMessage: second}), + .addFilter({ modifyFailureMessage: first }) + .addFilter({ modifyFailureMessage: second }), result; result = chain.modifyFailureMessage('original'); diff --git a/spec/core/ExpectationResultSpec.js b/spec/core/ExpectationResultSpec.js index 53d2c7e3..d9af2322 100644 --- a/spec/core/ExpectationResultSpec.js +++ b/spec/core/ExpectationResultSpec.js @@ -1,76 +1,93 @@ -describe("buildExpectationResult", function() { - it("defaults to passed", function() { - var result = jasmineUnderTest.buildExpectationResult({passed: 'some-value'}); +describe('buildExpectationResult', function() { + it('defaults to passed', function() { + var result = jasmineUnderTest.buildExpectationResult({ + passed: 'some-value' + }); expect(result.passed).toBe('some-value'); }); - it("message defaults to Passed for passing specs", function() { - var result = jasmineUnderTest.buildExpectationResult({passed: true, message: 'some-value'}); + it('message defaults to Passed for passing specs', function() { + var result = jasmineUnderTest.buildExpectationResult({ + passed: true, + message: 'some-value' + }); expect(result.message).toBe('Passed.'); }); - it("message returns the message for failing expectations", function() { - var result = jasmineUnderTest.buildExpectationResult({passed: false, message: 'some-value'}); + it('message returns the message for failing expectations', function() { + var result = jasmineUnderTest.buildExpectationResult({ + passed: false, + message: 'some-value' + }); expect(result.message).toBe('some-value'); }); - it("delegates message formatting to the provided formatter if there was an Error", function() { - var fakeError = {message: 'foo'}, - messageFormatter = jasmine.createSpy("exception message formatter").and.returnValue(fakeError.message); + it('delegates message formatting to the provided formatter if there was an Error', function() { + var fakeError = { message: 'foo' }, + messageFormatter = jasmine + .createSpy('exception message formatter') + .and.returnValue(fakeError.message); - var result = jasmineUnderTest.buildExpectationResult( - { - passed: false, - error: fakeError, - messageFormatter: messageFormatter - }); + var result = jasmineUnderTest.buildExpectationResult({ + passed: false, + error: fakeError, + messageFormatter: messageFormatter + }); expect(messageFormatter).toHaveBeenCalledWith(fakeError); expect(result.message).toEqual('foo'); }); - it("delegates stack formatting to the provided formatter if there was an Error", function() { - var fakeError = {stack: 'foo'}, - stackFormatter = jasmine.createSpy("stack formatter").and.returnValue(fakeError.stack); + it('delegates stack formatting to the provided formatter if there was an Error', function() { + var fakeError = { stack: 'foo' }, + stackFormatter = jasmine + .createSpy('stack formatter') + .and.returnValue(fakeError.stack); - var result = jasmineUnderTest.buildExpectationResult( - { - passed: false, - error: fakeError, - stackFormatter: stackFormatter - }); + var result = jasmineUnderTest.buildExpectationResult({ + passed: false, + error: fakeError, + stackFormatter: stackFormatter + }); expect(stackFormatter).toHaveBeenCalledWith(fakeError); expect(result.stack).toEqual('foo'); }); - it("delegates stack formatting to the provided formatter if there was a provided errorForStack", function() { - var fakeError = {stack: 'foo'}, - stackFormatter = jasmine.createSpy("stack formatter").and.returnValue(fakeError.stack); + it('delegates stack formatting to the provided formatter if there was a provided errorForStack', function() { + var fakeError = { stack: 'foo' }, + stackFormatter = jasmine + .createSpy('stack formatter') + .and.returnValue(fakeError.stack); - var result = jasmineUnderTest.buildExpectationResult( - { - passed: false, - errorForStack: fakeError, - stackFormatter: stackFormatter - }); + var result = jasmineUnderTest.buildExpectationResult({ + passed: false, + errorForStack: fakeError, + stackFormatter: stackFormatter + }); expect(stackFormatter).toHaveBeenCalledWith(fakeError); expect(result.stack).toEqual('foo'); }); - it("matcherName returns passed matcherName", function() { - var result = jasmineUnderTest.buildExpectationResult({matcherName: 'some-value'}); + it('matcherName returns passed matcherName', function() { + var result = jasmineUnderTest.buildExpectationResult({ + matcherName: 'some-value' + }); expect(result.matcherName).toBe('some-value'); }); - it("expected returns passed expected", function() { - var result = jasmineUnderTest.buildExpectationResult({expected: 'some-value'}); + it('expected returns passed expected', function() { + var result = jasmineUnderTest.buildExpectationResult({ + expected: 'some-value' + }); expect(result.expected).toBe('some-value'); }); - it("actual returns passed actual", function() { - var result = jasmineUnderTest.buildExpectationResult({actual: 'some-value'}); + it('actual returns passed actual', function() { + var result = jasmineUnderTest.buildExpectationResult({ + actual: 'some-value' + }); expect(result.actual).toBe('some-value'); }); }); diff --git a/spec/core/ExpectationSpec.js b/spec/core/ExpectationSpec.js index 72a4426f..45f69eb5 100644 --- a/spec/core/ExpectationSpec.js +++ b/spec/core/ExpectationSpec.js @@ -1,5 +1,5 @@ -describe("Expectation", function() { - it("makes custom matchers available to this expectation", function() { +describe('Expectation', function() { + it('makes custom matchers available to this expectation', function() { var matchers = { toFoo: function() {}, toBar: function() {} @@ -14,7 +14,7 @@ describe("Expectation", function() { expect(expectation.toBar).toBeDefined(); }); - it(".addCoreMatchers makes matchers available to any expectation", function() { + it('.addCoreMatchers makes matchers available to any expectation', function() { var coreMatchers = { toQuux: function() {} }, @@ -28,8 +28,12 @@ describe("Expectation", function() { }); it("wraps matchers's compare functions, passing in matcher dependencies", function() { - var fakeCompare = function() { return { pass: true }; }, - matcherFactory = jasmine.createSpy("matcher").and.returnValue({ compare: fakeCompare }), + var fakeCompare = function() { + return { pass: true }; + }, + matcherFactory = jasmine + .createSpy('matcher') + .and.returnValue({ compare: fakeCompare }), matchers = { toFoo: matcherFactory }, @@ -37,24 +41,26 @@ describe("Expectation", function() { buildFailureMessage: jasmine.createSpy('buildFailureMessage') }, customEqualityTesters = ['a'], - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation; expectation = jasmineUnderTest.Expectation.factory({ util: util, customMatchers: matchers, customEqualityTesters: customEqualityTesters, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }); - expectation.toFoo("hello"); + expectation.toFoo('hello'); - expect(matcherFactory).toHaveBeenCalledWith(util, customEqualityTesters) + expect(matcherFactory).toHaveBeenCalledWith(util, customEqualityTesters); }); it("wraps matchers's compare functions, passing the actual and expected", function() { - var fakeCompare = jasmine.createSpy('fake-compare').and.returnValue({pass: true}), + var fakeCompare = jasmine + .createSpy('fake-compare') + .and.returnValue({ pass: true }), matchers = { toFoo: function() { return { @@ -65,259 +71,270 @@ describe("Expectation", function() { util = { buildFailureMessage: jasmine.createSpy('buildFailureMessage') }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation; expectation = jasmineUnderTest.Expectation.factory({ util: util, customMatchers: matchers, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }); - expectation.toFoo("hello"); + expectation.toFoo('hello'); - expect(fakeCompare).toHaveBeenCalledWith("an actual", "hello"); + expect(fakeCompare).toHaveBeenCalledWith('an actual', 'hello'); }); - it("reports a passing result to the spec when the comparison passes", function() { + it('reports a passing result to the spec when the comparison passes', function() { var matchers = { toFoo: function() { return { - compare: function() { return { pass: true }; } + compare: function() { + return { pass: true }; + } }; } }, util = { buildFailureMessage: jasmine.createSpy('buildFailureMessage') }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation; expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, util: util, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }); - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(true, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: true, - message: "", + message: '', error: undefined, - expected: "hello", - actual: "an actual", + expected: 'hello', + actual: 'an actual', errorForStack: undefined }); }); - it("reports a failing result to the spec when the comparison fails", function() { + it('reports a failing result to the spec when the comparison fails', function() { var matchers = { toFoo: function() { return { - compare: function() { return { pass: false }; } + compare: function() { + return { pass: false }; + } }; } }, util = { - buildFailureMessage: function() { return ""; } + buildFailureMessage: function() { + return ''; + } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation; expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, util: util, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }); - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: false, - expected: "hello", - actual: "an actual", - message: "", + expected: 'hello', + actual: 'an actual', + message: '', error: undefined, errorForStack: undefined }); }); - it("reports a failing result and a custom fail message to the spec when the comparison fails", function() { + it('reports a failing result and a custom fail message to the spec when the comparison fails', function() { var matchers = { toFoo: function() { return { compare: function() { return { pass: false, - message: "I am a custom message" + message: 'I am a custom message' }; } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation; expectation = jasmineUnderTest.Expectation.factory({ - actual: "an actual", + actual: 'an actual', customMatchers: matchers, addExpectationResult: addExpectationResult }); - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: false, - expected: "hello", - actual: "an actual", - message: "I am a custom message", + expected: 'hello', + actual: 'an actual', + message: 'I am a custom message', error: undefined, errorForStack: undefined }); }); - it("reports a failing result with a custom fail message function to the spec when the comparison fails", function() { + it('reports a failing result with a custom fail message function to the spec when the comparison fails', function() { var matchers = { toFoo: function() { return { compare: function() { return { pass: false, - message: function() { return "I am a custom message"; } + message: function() { + return 'I am a custom message'; + } }; } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation; expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }); - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: false, - expected: "hello", - actual: "an actual", - message: "I am a custom message", + expected: 'hello', + actual: 'an actual', + message: 'I am a custom message', error: undefined, errorForStack: undefined }); }); - it("reports a passing result to the spec when the comparison fails for a negative expectation", function() { + it('reports a passing result to the spec when the comparison fails for a negative expectation', function() { var matchers = { toFoo: function() { return { - compare: function() { return { pass: false }; } + compare: function() { + return { pass: false }; + } }; } }, - util = { - buildFailureMessage: function() { return ""; } - }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), - actual = "an actual", + addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = 'an actual', expectation; expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }).not; - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(true, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: true, - message: "", + message: '', error: undefined, - expected: "hello", + expected: 'hello', actual: actual, errorForStack: undefined }); }); - it("reports a failing result to the spec when the comparison passes for a negative expectation", function() { + it('reports a failing result to the spec when the comparison passes for a negative expectation', function() { var matchers = { toFoo: function() { return { - compare: function() { return { pass: true }; } + compare: function() { + return { pass: true }; + } }; } }, util = { - buildFailureMessage: function() { return "default message"; } + buildFailureMessage: function() { + return 'default message'; + } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), - actual = "an actual", + addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = 'an actual', expectation; expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, - actual: "an actual", + actual: 'an actual', util: util, - addExpectationResult: addExpectationResult, + addExpectationResult: addExpectationResult }).not; - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: false, - expected: "hello", + expected: 'hello', actual: actual, - message: "default message", + message: 'default message', error: undefined, errorForStack: undefined }); }); - it("reports a failing result and a custom fail message to the spec when the comparison passes for a negative expectation", function() { + it('reports a failing result and a custom fail message to the spec when the comparison passes for a negative expectation', function() { var matchers = { toFoo: function() { return { compare: function() { return { pass: true, - message: "I am a custom message" + message: 'I am a custom message' }; } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), - actual = "an actual", + addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = 'an actual', expectation; expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }).not; - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: false, - expected: "hello", + expected: 'hello', actual: actual, - message: "I am a custom message", + message: 'I am a custom message', error: undefined, errorForStack: undefined }); @@ -327,29 +344,33 @@ describe("Expectation", function() { var matchers = { toFoo: function() { return { - compare: function() { return { pass: true }; }, - negativeCompare: function() { return { pass: true }; } + compare: function() { + return { pass: true }; + }, + negativeCompare: function() { + return { pass: true }; + } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), - actual = "an actual", + addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = 'an actual', expectation; expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }).not; - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(true, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: true, - expected: "hello", + expected: 'hello', actual: actual, - message: "", + message: '', error: undefined, errorForStack: undefined }); @@ -359,7 +380,9 @@ describe("Expectation", function() { var matchers = { toFoo: function() { return { - compare: function() { return { pass: true }; }, + compare: function() { + return { pass: true }; + }, negativeCompare: function() { return { pass: false, @@ -369,22 +392,22 @@ describe("Expectation", function() { }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), - actual = "an actual", + addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = 'an actual', expectation; expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, - actual: "an actual", - addExpectationResult: addExpectationResult, + actual: 'an actual', + addExpectationResult: addExpectationResult }).not; - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: false, - expected: "hello", + expected: 'hello', actual: actual, message: "I'm a custom message", error: undefined, @@ -392,254 +415,272 @@ describe("Expectation", function() { }); }); - it("reports a custom error message to the spec", function() { - var customError = new Error("I am a custom error"); + it('reports a custom error message to the spec', function() { + var customError = new Error('I am a custom error'); var matchers = { toFoo: function() { return { compare: function() { return { pass: false, - message: "I am a custom message", + message: 'I am a custom message', error: customError }; } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation; expectation = jasmineUnderTest.Expectation.factory({ - actual: "an actual", + actual: 'an actual', customMatchers: matchers, addExpectationResult: addExpectationResult }); - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: false, - expected: "hello", - actual: "an actual", - message: "I am a custom message", + expected: 'hello', + actual: 'an actual', + message: 'I am a custom message', error: customError, errorForStack: undefined }); }); it("reports a custom message to the spec when a 'not' comparison fails", function() { - var customError = new Error("I am a custom error"); + var customError = new Error('I am a custom error'); var matchers = { toFoo: function() { return { compare: function() { return { pass: true, - message: "I am a custom message", + message: 'I am a custom message', error: customError }; } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation; expectation = jasmineUnderTest.Expectation.factory({ - actual: "an actual", + actual: 'an actual', customMatchers: matchers, addExpectationResult: addExpectationResult }).not; - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: false, - expected: "hello", - actual: "an actual", - message: "I am a custom message", + expected: 'hello', + actual: 'an actual', + message: 'I am a custom message', error: customError, errorForStack: undefined }); }); it("reports a custom message func to the spec when a 'not' comparison fails", function() { - var customError = new Error("I am a custom error"); + var customError = new Error('I am a custom error'); var matchers = { toFoo: function() { return { compare: function() { return { pass: true, - message: function() { return "I am a custom message"; }, + message: function() { + return 'I am a custom message'; + }, error: customError }; } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation; expectation = jasmineUnderTest.Expectation.factory({ - actual: "an actual", + actual: 'an actual', customMatchers: matchers, addExpectationResult: addExpectationResult }).not; - expectation.toFoo("hello"); + expectation.toFoo('hello'); expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: "toFoo", + matcherName: 'toFoo', passed: false, - expected: "hello", - actual: "an actual", - message: "I am a custom message", + expected: 'hello', + actual: 'an actual', + message: 'I am a custom message', error: customError, errorForStack: undefined }); }); - describe("#withContext", function() { - it("prepends the context to the generated failure message", function() { + describe('#withContext', function() { + it('prepends the context to the generated failure message', function() { var matchers = { toFoo: function() { return { - compare: function() { return { pass: false }; } + compare: function() { + return { pass: false }; + } }; } }, util = { - buildFailureMessage: function() { return "failure message"; } + buildFailureMessage: function() { + return 'failure message'; + } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, util: util, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }); - expectation.withContext("Some context").toFoo("hello"); + expectation.withContext('Some context').toFoo('hello'); - expect(addExpectationResult).toHaveBeenCalledWith(false, + expect(addExpectationResult).toHaveBeenCalledWith( + false, jasmine.objectContaining({ - message: "Some context: failure message" + message: 'Some context: failure message' }) ); }); - it("prepends the context to a custom failure message", function() { + it('prepends the context to a custom failure message', function() { var matchers = { toFoo: function() { return { - compare: function() { return { pass: false, message: "msg" }; } + compare: function() { + return { pass: false, message: 'msg' }; + } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }); - expectation.withContext("Some context").toFoo("hello"); + expectation.withContext('Some context').toFoo('hello'); - expect(addExpectationResult).toHaveBeenCalledWith(false, + expect(addExpectationResult).toHaveBeenCalledWith( + false, jasmine.objectContaining({ - message: "Some context: msg" + message: 'Some context: msg' }) ); }); - it("prepends the context to a custom failure message from a function", function() { + it('prepends the context to a custom failure message from a function', function() { var matchers = { toFoo: function() { return { compare: function() { return { pass: false, - message: function() { return "msg"; } + message: function() { + return 'msg'; + } }; } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }); - expectation.withContext("Some context").toFoo("hello"); + expectation.withContext('Some context').toFoo('hello'); - expect(addExpectationResult).toHaveBeenCalledWith(false, + expect(addExpectationResult).toHaveBeenCalledWith( + false, jasmine.objectContaining({ - message: "Some context: msg" + message: 'Some context: msg' }) ); }); - it("works with #not", function() { + it('works with #not', function() { var matchers = { toFoo: function() { return { - compare: function() { return { pass: true }; } + compare: function() { + return { pass: true }; + } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, util: jasmineUnderTest.matchersUtil, - actual: "an actual", + actual: 'an actual', addExpectationResult: addExpectationResult }); - expectation.withContext("Some context").not.toFoo(); + expectation.withContext('Some context').not.toFoo(); - expect(addExpectationResult).toHaveBeenCalledWith(false, + expect(addExpectationResult).toHaveBeenCalledWith( + false, jasmine.objectContaining({ message: "Some context: Expected 'an actual' not to foo." }) ); }); - it("works with #not and a custom message", function() { - var customError = new Error("I am a custom error"); + it('works with #not and a custom message', function() { + var customError = new Error('I am a custom error'); var matchers = { toFoo: function() { return { compare: function() { return { pass: true, - message: function() { return "I am a custom message"; }, + message: function() { + return 'I am a custom message'; + }, error: customError }; } }; } }, - addExpectationResult = jasmine.createSpy("addExpectationResult"), + addExpectationResult = jasmine.createSpy('addExpectationResult'), expectation = jasmineUnderTest.Expectation.factory({ - actual: "an actual", + actual: 'an actual', customMatchers: matchers, addExpectationResult: addExpectationResult }); - expectation.withContext("Some context").not.toFoo("hello"); + expectation.withContext('Some context').not.toFoo('hello'); - expect(addExpectationResult).toHaveBeenCalledWith(false, + expect(addExpectationResult).toHaveBeenCalledWith( + false, jasmine.objectContaining({ - message: "Some context: I am a custom message", + message: 'Some context: I am a custom message' }) ); }); }); }); - diff --git a/spec/core/GlobalErrorsSpec.js b/spec/core/GlobalErrorsSpec.js index 1d26185d..9ff19891 100644 --- a/spec/core/GlobalErrorsSpec.js +++ b/spec/core/GlobalErrorsSpec.js @@ -1,8 +1,8 @@ -describe("GlobalErrors", function() { - it("calls the added handler on error", function() { +describe('GlobalErrors', function() { + it('calls the added handler on error', function() { var fakeGlobal = { onerror: null }, - handler = jasmine.createSpy('errorHandler'), - errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); + handler = jasmine.createSpy('errorHandler'), + errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); errors.install(); errors.pushListener(handler); @@ -12,11 +12,11 @@ describe("GlobalErrors", function() { expect(handler).toHaveBeenCalledWith('foo'); }); - it("only calls the most recent handler", function() { + it('only calls the most recent handler', function() { var fakeGlobal = { onerror: null }, - handler1 = jasmine.createSpy('errorHandler1'), - handler2 = jasmine.createSpy('errorHandler2'), - errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); + handler1 = jasmine.createSpy('errorHandler1'), + handler2 = jasmine.createSpy('errorHandler2'), + errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); errors.install(); errors.pushListener(handler1); @@ -28,11 +28,11 @@ describe("GlobalErrors", function() { expect(handler2).toHaveBeenCalledWith('foo'); }); - it("calls previous handlers when one is removed", function() { + it('calls previous handlers when one is removed', function() { var fakeGlobal = { onerror: null }, - handler1 = jasmine.createSpy('errorHandler1'), - handler2 = jasmine.createSpy('errorHandler2'), - errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); + handler1 = jasmine.createSpy('errorHandler1'), + handler2 = jasmine.createSpy('errorHandler2'), + errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); errors.install(); errors.pushListener(handler1); @@ -46,10 +46,10 @@ describe("GlobalErrors", function() { expect(handler2).not.toHaveBeenCalled(); }); - it("uninstalls itself, putting back a previous callback", function() { + it('uninstalls itself, putting back a previous callback', function() { var originalCallback = jasmine.createSpy('error'), - fakeGlobal = { onerror: originalCallback }, - errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); + fakeGlobal = { onerror: originalCallback }, + errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); expect(fakeGlobal.onerror).toBe(originalCallback); @@ -62,10 +62,10 @@ describe("GlobalErrors", function() { expect(fakeGlobal.onerror).toBe(originalCallback); }); - it("rethrows the original error when there is no handler", function() { - var fakeGlobal = { }, - errors = new jasmineUnderTest.GlobalErrors(fakeGlobal), - originalError = new Error('nope'); + it('rethrows the original error when there is no handler', function() { + var fakeGlobal = {}, + errors = new jasmineUnderTest.GlobalErrors(fakeGlobal), + originalError = new Error('nope'); errors.install(); @@ -78,22 +78,31 @@ describe("GlobalErrors", function() { errors.uninstall(); }); - it("reports uncaughtException in node.js", function() { + it('reports uncaughtException in node.js', function() { var fakeGlobal = { - process: { - on: jasmine.createSpy('process.on'), - removeListener: jasmine.createSpy('process.removeListener'), - listeners: jasmine.createSpy('process.listeners').and.returnValue(['foo']), - removeAllListeners: jasmine.createSpy('process.removeAllListeners') - } - }, - handler = jasmine.createSpy('errorHandler'), - errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); + process: { + on: jasmine.createSpy('process.on'), + removeListener: jasmine.createSpy('process.removeListener'), + listeners: jasmine + .createSpy('process.listeners') + .and.returnValue(['foo']), + removeAllListeners: jasmine.createSpy('process.removeAllListeners') + } + }, + handler = jasmine.createSpy('errorHandler'), + errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); errors.install(); - expect(fakeGlobal.process.on).toHaveBeenCalledWith('uncaughtException', jasmine.any(Function)); - expect(fakeGlobal.process.listeners).toHaveBeenCalledWith('uncaughtException'); - expect(fakeGlobal.process.removeAllListeners).toHaveBeenCalledWith('uncaughtException'); + expect(fakeGlobal.process.on).toHaveBeenCalledWith( + 'uncaughtException', + jasmine.any(Function) + ); + expect(fakeGlobal.process.listeners).toHaveBeenCalledWith( + 'uncaughtException' + ); + expect(fakeGlobal.process.removeAllListeners).toHaveBeenCalledWith( + 'uncaughtException' + ); errors.pushListener(handler); @@ -101,30 +110,47 @@ describe("GlobalErrors", function() { addedListener(new Error('bar')); expect(handler).toHaveBeenCalledWith(new Error('bar')); - expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe('Uncaught exception: Error: bar'); + expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe( + 'Uncaught exception: Error: bar' + ); errors.uninstall(); - expect(fakeGlobal.process.removeListener).toHaveBeenCalledWith('uncaughtException', addedListener); - expect(fakeGlobal.process.on).toHaveBeenCalledWith('uncaughtException', 'foo'); + expect(fakeGlobal.process.removeListener).toHaveBeenCalledWith( + 'uncaughtException', + addedListener + ); + expect(fakeGlobal.process.on).toHaveBeenCalledWith( + 'uncaughtException', + 'foo' + ); }); - it("reports unhandledRejection in node.js", function() { + it('reports unhandledRejection in node.js', function() { var fakeGlobal = { - process: { - on: jasmine.createSpy('process.on'), - removeListener: jasmine.createSpy('process.removeListener'), - listeners: jasmine.createSpy('process.listeners').and.returnValue(['foo']), - removeAllListeners: jasmine.createSpy('process.removeAllListeners') - } - }, - handler = jasmine.createSpy('errorHandler'), - errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); + process: { + on: jasmine.createSpy('process.on'), + removeListener: jasmine.createSpy('process.removeListener'), + listeners: jasmine + .createSpy('process.listeners') + .and.returnValue(['foo']), + removeAllListeners: jasmine.createSpy('process.removeAllListeners') + } + }, + handler = jasmine.createSpy('errorHandler'), + errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); errors.install(); - expect(fakeGlobal.process.on).toHaveBeenCalledWith('unhandledRejection', jasmine.any(Function)); - expect(fakeGlobal.process.listeners).toHaveBeenCalledWith('unhandledRejection'); - expect(fakeGlobal.process.removeAllListeners).toHaveBeenCalledWith('unhandledRejection'); + expect(fakeGlobal.process.on).toHaveBeenCalledWith( + 'unhandledRejection', + jasmine.any(Function) + ); + expect(fakeGlobal.process.listeners).toHaveBeenCalledWith( + 'unhandledRejection' + ); + expect(fakeGlobal.process.removeAllListeners).toHaveBeenCalledWith( + 'unhandledRejection' + ); errors.pushListener(handler); @@ -132,11 +158,19 @@ describe("GlobalErrors", function() { addedListener(new Error('bar')); expect(handler).toHaveBeenCalledWith(new Error('bar')); - expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe('Unhandled promise rejection: Error: bar'); + expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe( + 'Unhandled promise rejection: Error: bar' + ); errors.uninstall(); - expect(fakeGlobal.process.removeListener).toHaveBeenCalledWith('unhandledRejection', addedListener); - expect(fakeGlobal.process.on).toHaveBeenCalledWith('unhandledRejection', 'foo'); + expect(fakeGlobal.process.removeListener).toHaveBeenCalledWith( + 'unhandledRejection', + addedListener + ); + expect(fakeGlobal.process.on).toHaveBeenCalledWith( + 'unhandledRejection', + 'foo' + ); }); }); diff --git a/spec/core/JsApiReporterSpec.js b/spec/core/JsApiReporterSpec.js index 7a8cf2fb..2dcbdcff 100644 --- a/spec/core/JsApiReporterSpec.js +++ b/spec/core/JsApiReporterSpec.js @@ -2,86 +2,81 @@ xdescribe('JsApiReporter (integration specs)', function() { describe('results', function() { var reporter, spec1, spec2; var env; - var suite, nestedSuite, nestedSpec; beforeEach(function() { env = new jasmineUnderTest.Env(); - suite = env.describe("top-level suite", function() { - spec1 = env.it("spec 1", function() { + env.describe('top-level suite', function() { + spec1 = env.it('spec 1', function() { this.expect(true).toEqual(true); - }); - spec2 = env.it("spec 2", function() { + spec2 = env.it('spec 2', function() { this.expect(true).toEqual(false); }); - nestedSuite = env.describe("nested suite", function() { - nestedSpec = env.it("nested spec", function() { + env.describe('nested suite', function() { + env.it('nested spec', function() { expect(true).toEqual(true); }); }); - }); reporter = new jasmineUnderTest.JsApiReporter({}); env.addReporter(reporter); env.execute(); - }); it('results() should return a hash of all results, indexed by spec id', function() { - var expectedSpec1Results = { - result: "passed" - }, - expectedSpec2Results = { - result: "failed" - }; expect(reporter.results()[spec1.id].result).toEqual('passed'); expect(reporter.results()[spec2.id].result).toEqual('failed'); }); - it("should return nested suites as children of their parents", function() { + it('should return nested suites as children of their parents', function() { expect(reporter.suites()).toEqual([ - { id: 0, name: 'top-level suite', type: 'suite', + { + id: 0, + name: 'top-level suite', + type: 'suite', children: [ - { id: 0, name: 'spec 1', type: 'spec', children: [ ] }, - { id: 1, name: 'spec 2', type: 'spec', children: [ ] }, - { id: 1, name: 'nested suite', type: 'suite', + { id: 0, name: 'spec 1', type: 'spec', children: [] }, + { id: 1, name: 'spec 2', type: 'spec', children: [] }, + { + id: 1, + name: 'nested suite', + type: 'suite', children: [ - { id: 2, name: 'nested spec', type: 'spec', children: [ ] } + { id: 2, name: 'nested spec', type: 'spec', children: [] } ] - }, + } ] } ]); }); - describe("#summarizeResult_", function() { - it("should summarize a passing result", function() { + describe('#summarizeResult_', function() { + it('should summarize a passing result', function() { var result = reporter.results()[spec1.id]; var summarizedResult = reporter.summarizeResult_(result); expect(summarizedResult.result).toEqual('passed'); expect(summarizedResult.messages.length).toEqual(0); }); - it("should have a stack trace for failing specs", function() { + it('should have a stack trace for failing specs', function() { var result = reporter.results()[spec2.id]; var summarizedResult = reporter.summarizeResult_(result); expect(summarizedResult.result).toEqual('failed'); - expect(summarizedResult.messages[0].trace.stack).toEqual(result.messages[0].trace.stack); + expect(summarizedResult.messages[0].trace.stack).toEqual( + result.messages[0].trace.stack + ); }); - }); }); }); - -describe("JsApiReporter", function() { - - it("knows when a full environment is started", function() { +describe('JsApiReporter', function() { + it('knows when a full environment is started', function() { var reporter = new jasmineUnderTest.JsApiReporter({}); expect(reporter.started).toBe(false); @@ -93,7 +88,7 @@ describe("JsApiReporter", function() { expect(reporter.finished).toBe(false); }); - it("knows when a full environment is done", function() { + it('knows when a full environment is done', function() { var reporter = new jasmineUnderTest.JsApiReporter({}); expect(reporter.started).toBe(false); @@ -127,58 +122,60 @@ describe("JsApiReporter", function() { expect(reporter.status()).toEqual('done'); }); - it("tracks a suite", function() { + it('tracks a suite', function() { var reporter = new jasmineUnderTest.JsApiReporter({}); reporter.suiteStarted({ id: 123, - description: "A suite" + description: 'A suite' }); var suites = reporter.suites(); - expect(suites).toEqual({123: {id: 123, description: "A suite"}}); + expect(suites).toEqual({ 123: { id: 123, description: 'A suite' } }); reporter.suiteDone({ id: 123, - description: "A suite", + description: 'A suite', status: 'passed' }); - expect(suites).toEqual({123: {id: 123, description: "A suite", status: 'passed'}}); + expect(suites).toEqual({ + 123: { id: 123, description: 'A suite', status: 'passed' } + }); }); - describe("#specResults", function() { + describe('#specResults', function() { var reporter, specResult1, specResult2; beforeEach(function() { reporter = new jasmineUnderTest.JsApiReporter({}); specResult1 = { id: 1, - description: "A spec" + description: 'A spec' }; specResult2 = { id: 2, - description: "Another spec" + description: 'Another spec' }; reporter.specDone(specResult1); reporter.specDone(specResult2); }); - it("should return a slice of results", function() { + it('should return a slice of results', function() { expect(reporter.specResults(0, 1)).toEqual([specResult1]); expect(reporter.specResults(1, 1)).toEqual([specResult2]); }); - describe("when the results do not exist", function() { - it("should return a slice of shorter length", function() { + describe('when the results do not exist', function() { + it('should return a slice of shorter length', function() { expect(reporter.specResults(0, 3)).toEqual([specResult1, specResult2]); expect(reporter.specResults(2, 3)).toEqual([]); }); }); }); - describe("#suiteResults", function(){ + describe('#suiteResults', function() { var reporter, suiteResult1, suiteResult2; beforeEach(function() { reporter = new jasmineUnderTest.JsApiReporter({}); @@ -200,37 +197,37 @@ describe("JsApiReporter", function() { reporter.suiteDone(suiteResult2); }); - it('should not include suite starts', function(){ - expect(reporter.suiteResults(0,3).length).toEqual(2); + it('should not include suite starts', function() { + expect(reporter.suiteResults(0, 3).length).toEqual(2); }); - it("should return a slice of results", function() { + it('should return a slice of results', function() { expect(reporter.suiteResults(0, 1)).toEqual([suiteResult1]); expect(reporter.suiteResults(1, 1)).toEqual([suiteResult2]); }); - it("returns nothing for out of bounds indices", function() { + it('returns nothing for out of bounds indices', function() { expect(reporter.suiteResults(0, 3)).toEqual([suiteResult1, suiteResult2]); expect(reporter.suiteResults(2, 3)).toEqual([]); }); }); - describe("#executionTime", function() { - it("should start the timer when jasmine starts", function() { + describe('#executionTime', function() { + it('should start the timer when jasmine starts', function() { var timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']), - reporter = new jasmineUnderTest.JsApiReporter({ - timer: timerSpy - }); + reporter = new jasmineUnderTest.JsApiReporter({ + timer: timerSpy + }); reporter.jasmineStarted(); expect(timerSpy.start).toHaveBeenCalled(); }); - it("should return the time it took the specs to run, in ms", function() { + it('should return the time it took the specs to run, in ms', function() { var timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']), - reporter = new jasmineUnderTest.JsApiReporter({ - timer: timerSpy - }); + reporter = new jasmineUnderTest.JsApiReporter({ + timer: timerSpy + }); timerSpy.elapsed.and.returnValue(1000); reporter.jasmineDone(); @@ -238,11 +235,11 @@ describe("JsApiReporter", function() { }); describe("when the specs haven't finished being run", function() { - it("should return undefined", function() { + it('should return undefined', function() { var timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']), - reporter = new jasmineUnderTest.JsApiReporter({ - timer: timerSpy - }); + reporter = new jasmineUnderTest.JsApiReporter({ + timer: timerSpy + }); expect(reporter.executionTime()).toBeUndefined(); }); @@ -252,8 +249,8 @@ describe("JsApiReporter", function() { describe('#runDetails', function() { it('should have details about the run', function() { var reporter = new jasmineUnderTest.JsApiReporter({}); - reporter.jasmineDone({some: {run: 'details'}}); - expect(reporter.runDetails).toEqual({some: {run: 'details'}}); + reporter.jasmineDone({ some: { run: 'details' } }); + expect(reporter.runDetails).toEqual({ some: { run: 'details' } }); }); }); }); diff --git a/spec/core/MockDateSpec.js b/spec/core/MockDateSpec.js index cc4ae816..6f6f88df 100644 --- a/spec/core/MockDateSpec.js +++ b/spec/core/MockDateSpec.js @@ -1,5 +1,5 @@ -describe("FakeDate", function() { - it("does not fail if no global date is found", function() { +describe('FakeDate', function() { + it('does not fail if no global date is found', function() { var fakeGlobal = {}, mockDate = new jasmineUnderTest.MockDate(fakeGlobal); @@ -10,11 +10,11 @@ describe("FakeDate", function() { }).not.toThrow(); }); - it("replaces the global Date when it is installed", function() { - var globalDate = jasmine.createSpy("global Date").and.callFake(function() { + it('replaces the global Date when it is installed', function() { + var globalDate = jasmine.createSpy('global Date').and.callFake(function() { return { getTime: function() {} - } + }; }), fakeGlobal = { Date: globalDate }, mockDate = new jasmineUnderTest.MockDate(fakeGlobal); @@ -25,11 +25,11 @@ describe("FakeDate", function() { expect(fakeGlobal.Date).not.toEqual(globalDate); }); - it("replaces the global Date on uninstall", function() { - var globalDate = jasmine.createSpy("global Date").and.callFake(function() { + it('replaces the global Date on uninstall', function() { + var globalDate = jasmine.createSpy('global Date').and.callFake(function() { return { getTime: function() {} - } + }; }), fakeGlobal = { Date: globalDate }, mockDate = new jasmineUnderTest.MockDate(fakeGlobal); @@ -40,13 +40,13 @@ describe("FakeDate", function() { expect(fakeGlobal.Date).toEqual(globalDate); }); - it("takes the current time as the base when installing without parameters", function() { - var globalDate = jasmine.createSpy("global Date").and.callFake(function() { + it('takes the current time as the base when installing without parameters', function() { + var globalDate = jasmine.createSpy('global Date').and.callFake(function() { return { getTime: function() { return 1000; } - } + }; }), fakeGlobal = { Date: globalDate }, mockDate = new jasmineUnderTest.MockDate(fakeGlobal); @@ -58,7 +58,7 @@ describe("FakeDate", function() { expect(globalDate).toHaveBeenCalledWith(1000); }); - it("can accept a date as time base when installing", function() { + it('can accept a date as time base when installing', function() { var fakeGlobal = { Date: Date }, mockDate = new jasmineUnderTest.MockDate(fakeGlobal), baseDate = new Date(); @@ -69,7 +69,7 @@ describe("FakeDate", function() { expect(new fakeGlobal.Date().getTime()).toEqual(123); }); - it("makes real dates", function() { + it('makes real dates', function() { var fakeGlobal = { Date: Date }, mockDate = new jasmineUnderTest.MockDate(fakeGlobal); @@ -78,13 +78,13 @@ describe("FakeDate", function() { expect(new fakeGlobal.Date() instanceof fakeGlobal.Date).toBe(true); }); - it("fakes current time when using Date.now()", function() { - var globalDate = jasmine.createSpy("global Date").and.callFake(function() { + it('fakes current time when using Date.now()', function() { + var globalDate = jasmine.createSpy('global Date').and.callFake(function() { return { getTime: function() { return 1000; } - } + }; }), fakeGlobal = { Date: globalDate }; @@ -97,28 +97,30 @@ describe("FakeDate", function() { }); it("does not stub Date.now() if it doesn't already exist", function() { - var globalDate = jasmine.createSpy("global Date").and.callFake(function() { + var globalDate = jasmine.createSpy('global Date').and.callFake(function() { return { getTime: function() { return 1000; } - } + }; }), fakeGlobal = { Date: globalDate }, mockDate = new jasmineUnderTest.MockDate(fakeGlobal); mockDate.install(); - expect(fakeGlobal.Date.now).toThrowError("Browser does not support Date.now()"); + expect(fakeGlobal.Date.now).toThrowError( + 'Browser does not support Date.now()' + ); }); - it("makes time passes using tick", function() { - var globalDate = jasmine.createSpy("global Date").and.callFake(function() { + it('makes time passes using tick', function() { + var globalDate = jasmine.createSpy('global Date').and.callFake(function() { return { getTime: function() { return 1000; } - } + }; }), fakeGlobal = { Date: globalDate }; @@ -136,13 +138,13 @@ describe("FakeDate", function() { expect(fakeGlobal.Date.now()).toEqual(2100); }); - it("allows to increase 0 milliseconds using tick", function() { - var globalDate = jasmine.createSpy("global Date").and.callFake(function() { + it('allows to increase 0 milliseconds using tick', function() { + var globalDate = jasmine.createSpy('global Date').and.callFake(function() { return { getTime: function() { return 1000; } - } + }; }), fakeGlobal = { Date: globalDate }; @@ -158,14 +160,16 @@ describe("FakeDate", function() { expect(fakeGlobal.Date.now()).toEqual(1000); }); - it("allows creation of a Date in a different time than the mocked time", function() { + it('allows creation of a Date in a different time than the mocked time', function() { var fakeGlobal = { Date: Date }, mockDate = new jasmineUnderTest.MockDate(fakeGlobal); mockDate.install(); var otherDate = new fakeGlobal.Date(2013, 9, 23, 0, 0, 1, 0); - expect(otherDate.getTime()).toEqual(new Date(2013, 9, 23, 0, 0, 1, 0).getTime()); + expect(otherDate.getTime()).toEqual( + new Date(2013, 9, 23, 0, 0, 1, 0).getTime() + ); }); it("allows creation of a Date that isn't fully specified", function() { @@ -189,7 +193,7 @@ describe("FakeDate", function() { expect(otherDate.getTime()).toEqual(now); }); - it("copies all Date properties to the mocked date", function() { + it('copies all Date properties to the mocked date', function() { var fakeGlobal = { Date: Date }, mockDate = new jasmineUnderTest.MockDate(fakeGlobal); diff --git a/spec/core/PrettyPrintSpec.js b/spec/core/PrettyPrintSpec.js index b62d191d..0e3c48ad 100644 --- a/spec/core/PrettyPrintSpec.js +++ b/spec/core/PrettyPrintSpec.js @@ -1,29 +1,29 @@ -describe("jasmineUnderTest.pp", function () { - it("should wrap strings in single quotes", function() { - expect(jasmineUnderTest.pp("some string")).toEqual("'some string'"); +describe('jasmineUnderTest.pp', function() { + it('should wrap strings in single quotes', function() { + expect(jasmineUnderTest.pp('some string')).toEqual("'some string'"); expect(jasmineUnderTest.pp("som' string")).toEqual("'som' string'"); }); - it("should stringify primitives properly", function() { - expect(jasmineUnderTest.pp(true)).toEqual("true"); - expect(jasmineUnderTest.pp(false)).toEqual("false"); - expect(jasmineUnderTest.pp(null)).toEqual("null"); - expect(jasmineUnderTest.pp(jasmine.undefined)).toEqual("undefined"); - expect(jasmineUnderTest.pp(3)).toEqual("3"); - expect(jasmineUnderTest.pp(-3.14)).toEqual("-3.14"); - expect(jasmineUnderTest.pp(-0)).toEqual("-0"); + it('should stringify primitives properly', function() { + expect(jasmineUnderTest.pp(true)).toEqual('true'); + expect(jasmineUnderTest.pp(false)).toEqual('false'); + expect(jasmineUnderTest.pp(null)).toEqual('null'); + expect(jasmineUnderTest.pp(jasmine.undefined)).toEqual('undefined'); + expect(jasmineUnderTest.pp(3)).toEqual('3'); + expect(jasmineUnderTest.pp(-3.14)).toEqual('-3.14'); + expect(jasmineUnderTest.pp(-0)).toEqual('-0'); }); describe('stringify sets', function() { - it("should stringify sets properly", function() { + it('should stringify sets properly', function() { jasmine.getEnv().requireFunctioningSets(); var set = new Set(); set.add(1); set.add(2); - expect(jasmineUnderTest.pp(set)).toEqual("Set( 1, 2 )"); + expect(jasmineUnderTest.pp(set)).toEqual('Set( 1, 2 )'); }); - it("should truncate sets with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH", function() { + it('should truncate sets with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() { jasmine.getEnv().requireFunctioningSets(); var originalMaxSize = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; @@ -37,112 +37,137 @@ describe("jasmineUnderTest.pp", function () { } finally { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize; } - }) + }); }); describe('stringify maps', function() { - it("should stringify maps properly", function() { + it('should stringify maps properly', function() { jasmine.getEnv().requireFunctioningMaps(); var map = new Map(); - map.set(1,2); - expect(jasmineUnderTest.pp(map)).toEqual("Map( [ 1, 2 ] )"); + map.set(1, 2); + expect(jasmineUnderTest.pp(map)).toEqual('Map( [ 1, 2 ] )'); }); - it("should truncate maps with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH", function() { + it('should truncate maps with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() { jasmine.getEnv().requireFunctioningMaps(); var originalMaxSize = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; try { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; var map = new Map(); - map.set("a",1); - map.set("b",2); - map.set("c",3); - expect(jasmineUnderTest.pp(map)).toEqual("Map( [ 'a', 1 ], [ 'b', 2 ], ... )"); + map.set('a', 1); + map.set('b', 2); + map.set('c', 3); + expect(jasmineUnderTest.pp(map)).toEqual( + "Map( [ 'a', 1 ], [ 'b', 2 ], ... )" + ); } finally { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize; } - }) + }); }); - describe('stringify arrays', function() { - it("should stringify arrays properly", function() { - expect(jasmineUnderTest.pp([1, 2])).toEqual("[ 1, 2 ]"); - expect(jasmineUnderTest.pp([1, 'foo', {}, jasmine.undefined, null])).toEqual("[ 1, 'foo', Object({ }), undefined, null ]"); + it('should stringify arrays properly', function() { + expect(jasmineUnderTest.pp([1, 2])).toEqual('[ 1, 2 ]'); + expect( + jasmineUnderTest.pp([1, 'foo', {}, jasmine.undefined, null]) + ).toEqual("[ 1, 'foo', Object({ }), undefined, null ]"); }); - it("should truncate arrays that are longer than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH", function() { + it('should truncate arrays that are longer than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() { var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; var array = [1, 2, 3]; try { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; - expect(jasmineUnderTest.pp(array)).toEqual("[ 1, 2, ... ]"); + expect(jasmineUnderTest.pp(array)).toEqual('[ 1, 2, ... ]'); } finally { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength; } }); - it("should stringify arrays with properties properly", function() { + it('should stringify arrays with properties properly', function() { var arr = [1, 2]; arr.foo = 'bar'; arr.baz = {}; - expect(jasmineUnderTest.pp(arr)).toEqual("[ 1, 2, foo: 'bar', baz: Object({ }) ]"); + expect(jasmineUnderTest.pp(arr)).toEqual( + "[ 1, 2, foo: 'bar', baz: Object({ }) ]" + ); }); - it("should stringify empty arrays with properties properly", function() { + it('should stringify empty arrays with properties properly', function() { var empty = []; empty.foo = 'bar'; empty.baz = {}; - expect(jasmineUnderTest.pp(empty)).toEqual("[ foo: 'bar', baz: Object({ }) ]"); + expect(jasmineUnderTest.pp(empty)).toEqual( + "[ foo: 'bar', baz: Object({ }) ]" + ); }); - it("should stringify long arrays with properties properly", function() { + it('should stringify long arrays with properties properly', function() { var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; - var long = [1,2,3]; + var long = [1, 2, 3]; long.foo = 'bar'; long.baz = {}; try { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; - expect(jasmineUnderTest.pp(long)).toEqual("[ 1, 2, ..., foo: 'bar', baz: Object({ }) ]"); + expect(jasmineUnderTest.pp(long)).toEqual( + "[ 1, 2, ..., foo: 'bar', baz: Object({ }) ]" + ); } finally { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength; } }); - it("should indicate circular array references", function() { + it('should indicate circular array references', function() { var array1 = [1, 2]; var array2 = [array1]; array1.push(array2); - expect(jasmineUnderTest.pp(array1)).toEqual("[ 1, 2, [ ] ]"); + expect(jasmineUnderTest.pp(array1)).toEqual( + '[ 1, 2, [ ] ]' + ); }); - it("should not indicate circular references incorrectly", function() { - var array = [ [1] ]; - expect(jasmineUnderTest.pp(array)).toEqual("[ [ 1 ] ]"); + it('should not indicate circular references incorrectly', function() { + var array = [[1]]; + expect(jasmineUnderTest.pp(array)).toEqual('[ [ 1 ] ]'); }); }); - it("should stringify objects properly", function() { - expect(jasmineUnderTest.pp({foo: 'bar'})).toEqual("Object({ foo: 'bar' })"); - expect(jasmineUnderTest.pp({foo:'bar', baz:3, nullValue: null, undefinedValue: jasmine.undefined})).toEqual("Object({ foo: 'bar', baz: 3, nullValue: null, undefinedValue: undefined })"); - expect(jasmineUnderTest.pp({foo: function () { - }, bar: [1, 2, 3]})).toEqual("Object({ foo: Function, bar: [ 1, 2, 3 ] })"); + it('should stringify objects properly', function() { + expect(jasmineUnderTest.pp({ foo: 'bar' })).toEqual( + "Object({ foo: 'bar' })" + ); + expect( + jasmineUnderTest.pp({ + foo: 'bar', + baz: 3, + nullValue: null, + undefinedValue: jasmine.undefined + }) + ).toEqual( + "Object({ foo: 'bar', baz: 3, nullValue: null, undefinedValue: undefined })" + ); + expect(jasmineUnderTest.pp({ foo: function() {}, bar: [1, 2, 3] })).toEqual( + 'Object({ foo: Function, bar: [ 1, 2, 3 ] })' + ); }); - it("should stringify objects that almost look like DOM nodes", function() { - expect(jasmineUnderTest.pp({nodeType: 1})).toEqual("Object({ nodeType: 1 })"); + it('should stringify objects that almost look like DOM nodes', function() { + expect(jasmineUnderTest.pp({ nodeType: 1 })).toEqual( + 'Object({ nodeType: 1 })' + ); }); - it("should truncate objects with too many keys", function () { + it('should truncate objects with too many keys', function() { var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; - var long = {a: 1, b: 2, c: 3}; + var long = { a: 1, b: 2, c: 3 }; try { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; - expect(jasmineUnderTest.pp(long)).toEqual("Object({ a: 1, b: 2, ... })"); + expect(jasmineUnderTest.pp(long)).toEqual('Object({ a: 1, b: 2, ... })'); } finally { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength; } @@ -159,86 +184,119 @@ describe("jasmineUnderTest.pp", function () { } } - it("should truncate outputs that are too long", function() { - var big = [ - { a: 1, b: "a long string" }, - {} - ]; + it('should truncate outputs that are too long', function() { + var big = [{ a: 1, b: 'a long string' }, {}]; withMaxChars(34, function() { - expect(jasmineUnderTest.pp(big)).toEqual("[ Object({ a: 1, b: 'a long st ..."); + expect(jasmineUnderTest.pp(big)).toEqual( + "[ Object({ a: 1, b: 'a long st ..." + ); }); }); - it("should not serialize more objects after hitting MAX_PRETTY_PRINT_CHARS", function() { - var a = { jasmineToString: function() { return 'object a'; } }, - b = { jasmineToString: function() { return 'object b'; } }, - c = { jasmineToString: jasmine.createSpy('c jasmineToString').and.returnValue('') }, - d = { jasmineToString: jasmine.createSpy('d jasmineToString').and.returnValue('') }; + it('should not serialize more objects after hitting MAX_PRETTY_PRINT_CHARS', function() { + var a = { + jasmineToString: function() { + return 'object a'; + } + }, + b = { + jasmineToString: function() { + return 'object b'; + } + }, + c = { + jasmineToString: jasmine + .createSpy('c jasmineToString') + .and.returnValue('') + }, + d = { + jasmineToString: jasmine + .createSpy('d jasmineToString') + .and.returnValue('') + }; withMaxChars(30, function() { - jasmineUnderTest.pp([{a: a, b: b, c: c}, d]); + jasmineUnderTest.pp([{ a: a, b: b, c: c }, d]); expect(c.jasmineToString).not.toHaveBeenCalled(); expect(d.jasmineToString).not.toHaveBeenCalled(); }); }); it("should print 'null' as the constructor of an object with its own constructor property", function() { - expect(jasmineUnderTest.pp({constructor: function() {}})).toContain("null({"); - expect(jasmineUnderTest.pp({constructor: 'foo'})).toContain("null({"); + expect(jasmineUnderTest.pp({ constructor: function() {} })).toContain( + 'null({' + ); + expect(jasmineUnderTest.pp({ constructor: 'foo' })).toContain('null({'); }); - it("should not include inherited properties when stringifying an object", function() { + it('should not include inherited properties when stringifying an object', function() { var SomeClass = function SomeClass() {}; - SomeClass.prototype.foo = "inherited foo"; + SomeClass.prototype.foo = 'inherited foo'; var instance = new SomeClass(); - instance.bar = "my own bar"; - expect(jasmineUnderTest.pp(instance)).toEqual("SomeClass({ bar: 'my own bar' })"); + instance.bar = 'my own bar'; + expect(jasmineUnderTest.pp(instance)).toEqual( + "SomeClass({ bar: 'my own bar' })" + ); }); - it("should not recurse objects and arrays more deeply than jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH", function() { + it('should not recurse objects and arrays more deeply than jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH', function() { var originalMaxDepth = jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH; - var nestedObject = { level1: { level2: { level3: { level4: "leaf" } } } }; - var nestedArray = [1, [2, [3, [4, "leaf"]]]]; + var nestedObject = { level1: { level2: { level3: { level4: 'leaf' } } } }; + var nestedArray = [1, [2, [3, [4, 'leaf']]]]; try { jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 2; - expect(jasmineUnderTest.pp(nestedObject)).toEqual("Object({ level1: Object({ level2: Object }) })"); - expect(jasmineUnderTest.pp(nestedArray)).toEqual("[ 1, [ 2, Array ] ]"); + expect(jasmineUnderTest.pp(nestedObject)).toEqual( + 'Object({ level1: Object({ level2: Object }) })' + ); + expect(jasmineUnderTest.pp(nestedArray)).toEqual('[ 1, [ 2, Array ] ]'); jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 3; - expect(jasmineUnderTest.pp(nestedObject)).toEqual("Object({ level1: Object({ level2: Object({ level3: Object }) }) })"); - expect(jasmineUnderTest.pp(nestedArray)).toEqual("[ 1, [ 2, [ 3, Array ] ] ]"); + expect(jasmineUnderTest.pp(nestedObject)).toEqual( + 'Object({ level1: Object({ level2: Object({ level3: Object }) }) })' + ); + expect(jasmineUnderTest.pp(nestedArray)).toEqual( + '[ 1, [ 2, [ 3, Array ] ] ]' + ); jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 4; - expect(jasmineUnderTest.pp(nestedObject)).toEqual("Object({ level1: Object({ level2: Object({ level3: Object({ level4: 'leaf' }) }) }) })"); - expect(jasmineUnderTest.pp(nestedArray)).toEqual("[ 1, [ 2, [ 3, [ 4, 'leaf' ] ] ] ]"); + expect(jasmineUnderTest.pp(nestedObject)).toEqual( + "Object({ level1: Object({ level2: Object({ level3: Object({ level4: 'leaf' }) }) }) })" + ); + expect(jasmineUnderTest.pp(nestedArray)).toEqual( + "[ 1, [ 2, [ 3, [ 4, 'leaf' ] ] ] ]" + ); } finally { jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = originalMaxDepth; } }); - it("should stringify immutable circular objects", function(){ - if(Object.freeze){ - var frozenObject = {foo: {bar: 'baz'}}; + it('should stringify immutable circular objects', function() { + if (Object.freeze) { + var frozenObject = { foo: { bar: 'baz' } }; frozenObject.circular = frozenObject; frozenObject = Object.freeze(frozenObject); - expect(jasmineUnderTest.pp(frozenObject)).toEqual("Object({ foo: Object({ bar: 'baz' }), circular: })"); + expect(jasmineUnderTest.pp(frozenObject)).toEqual( + "Object({ foo: Object({ bar: 'baz' }), circular: })" + ); } }); - it("should stringify RegExp objects properly", function() { - expect(jasmineUnderTest.pp(/x|y|z/)).toEqual("/x|y|z/"); + it('should stringify RegExp objects properly', function() { + expect(jasmineUnderTest.pp(/x|y|z/)).toEqual('/x|y|z/'); }); - it("should indicate circular object references", function() { - var sampleValue = {foo: 'hello'}; + it('should indicate circular object references', function() { + var sampleValue = { foo: 'hello' }; sampleValue.nested = sampleValue; - expect(jasmineUnderTest.pp(sampleValue)).toEqual("Object({ foo: 'hello', nested: })"); + expect(jasmineUnderTest.pp(sampleValue)).toEqual( + "Object({ foo: 'hello', nested: })" + ); }); - it("should indicate getters on objects as such", function() { - var sampleValue = {id: 1}; + it('should indicate getters on objects as such', function() { + var sampleValue = { id: 1 }; if (sampleValue.__defineGetter__) { //not supported in IE! sampleValue.__defineGetter__('calculatedValue', function() { @@ -246,53 +304,64 @@ describe("jasmineUnderTest.pp", function () { }); } if (sampleValue.__defineGetter__) { - expect(jasmineUnderTest.pp(sampleValue)).toEqual("Object({ id: 1, calculatedValue: })"); - } - else { - expect(jasmineUnderTest.pp(sampleValue)).toEqual("Object({ id: 1 })"); + expect(jasmineUnderTest.pp(sampleValue)).toEqual( + 'Object({ id: 1, calculatedValue: })' + ); + } else { + expect(jasmineUnderTest.pp(sampleValue)).toEqual('Object({ id: 1 })'); } }); it('should not do HTML escaping of strings', function() { - expect(jasmineUnderTest.pp('some html string &', false)).toEqual('\'some html string &\''); + expect(jasmineUnderTest.pp('some html string &', false)).toEqual( + "'some html string &'" + ); }); - it("should abbreviate the global (usually window) object", function() { - expect(jasmineUnderTest.pp(jasmine.getGlobal())).toEqual(""); + it('should abbreviate the global (usually window) object', function() { + expect(jasmineUnderTest.pp(jasmine.getGlobal())).toEqual(''); }); - it("should stringify Date objects properly", function() { + it('should stringify Date objects properly', function() { var now = new Date(); - expect(jasmineUnderTest.pp(now)).toEqual("Date(" + now.toString() + ")"); + expect(jasmineUnderTest.pp(now)).toEqual('Date(' + now.toString() + ')'); }); - it("should stringify spy objects properly", function() { + it('should stringify spy objects properly', function() { var TestObject = { - someFunction: function() {} - }, - env = new jasmineUnderTest.Env(); + someFunction: function() {} + }, + env = new jasmineUnderTest.Env(); var spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() {return [];}, + currentSpies: function() { + return []; + }, createSpy: function(name, originalFn) { return jasmineUnderTest.Spy(name, originalFn); } }); spyRegistry.spyOn(TestObject, 'someFunction'); - expect(jasmineUnderTest.pp(TestObject.someFunction)).toEqual("spy on someFunction"); + expect(jasmineUnderTest.pp(TestObject.someFunction)).toEqual( + 'spy on someFunction' + ); - expect(jasmineUnderTest.pp(env.createSpy("something"))).toEqual("spy on something"); + expect(jasmineUnderTest.pp(env.createSpy('something'))).toEqual( + 'spy on something' + ); }); - it("should stringify spyOn toString properly", function() { + it('should stringify spyOn toString properly', function() { var TestObject = { - someFunction: function() {} - }, - env = new jasmineUnderTest.Env(); + someFunction: function() {} + }, + env = new jasmineUnderTest.Env(); var spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() {return [];}, + currentSpies: function() { + return []; + }, createSpy: function(name, originalFn) { return jasmineUnderTest.Spy(name, originalFn); } @@ -301,59 +370,73 @@ describe("jasmineUnderTest.pp", function () { spyRegistry.spyOn(TestObject, 'toString'); var testSpyObj = env.createSpyObj('TheClassName', ['toString']); - expect(jasmineUnderTest.pp(testSpyObj)).toEqual("spy on TheClassName.toString"); + expect(jasmineUnderTest.pp(testSpyObj)).toEqual( + 'spy on TheClassName.toString' + ); }); - it("should stringify objects that implement jasmineToString", function () { + it('should stringify objects that implement jasmineToString', function() { var obj = { - jasmineToString: function () { return "strung"; } + jasmineToString: function() { + return 'strung'; + } }; - expect(jasmineUnderTest.pp(obj)).toEqual("strung"); + expect(jasmineUnderTest.pp(obj)).toEqual('strung'); }); - it("should stringify objects that implement custom toString", function () { + it('should stringify objects that implement custom toString', function() { var obj = { - toString: function () { return "my toString"; } + toString: function() { + return 'my toString'; + } }; - expect(jasmineUnderTest.pp(obj)).toEqual("my toString"); + expect(jasmineUnderTest.pp(obj)).toEqual('my toString'); // Simulate object from another global context (e.g. an iframe or Web Worker) that does not actually have a custom // toString despite obj.toString !== Object.prototype.toString var objFromOtherContext = { foo: 'bar', - toString: function () { return Object.prototype.toString.call(this); } + toString: function() { + return Object.prototype.toString.call(this); + } }; - expect(jasmineUnderTest.pp(objFromOtherContext)).toEqual("Object({ foo: 'bar', toString: Function })"); + expect(jasmineUnderTest.pp(objFromOtherContext)).toEqual( + "Object({ foo: 'bar', toString: Function })" + ); }); it("should stringify objects have have a toString that isn't a function", function() { var obj = { - toString: "foo" + toString: 'foo' }; expect(jasmineUnderTest.pp(obj)).toEqual("Object({ toString: 'foo' })"); }); - it("should stringify objects from anonymous constructors with custom toString", function () { - var MyAnonymousConstructor = (function() { return function () {}; })(); - MyAnonymousConstructor.toString = function () { return ''; }; + it('should stringify objects from anonymous constructors with custom toString', function() { + var MyAnonymousConstructor = (function() { + return function() {}; + })(); + MyAnonymousConstructor.toString = function() { + return ''; + }; var a = new MyAnonymousConstructor(); - expect(jasmineUnderTest.pp(a)).toEqual("({ })"); + expect(jasmineUnderTest.pp(a)).toEqual('({ })'); }); - it("should handle objects with null prototype", function() { + it('should handle objects with null prototype', function() { var obj = Object.create(null); obj.foo = 'bar'; expect(jasmineUnderTest.pp(obj)).toEqual("null({ foo: 'bar' })"); }); - it("should gracefully handle objects with invalid toString implementations", function () { + it('should gracefully handle objects with invalid toString implementations', function() { var obj = { foo: { toString: function() { @@ -374,9 +457,11 @@ describe("jasmineUnderTest.pp", function () { // Valid: an actual number baz: 3, // Valid: an actual Error object - qux: new Error("bar") + qux: new Error('bar') }; - expect(jasmineUnderTest.pp(obj)).toEqual("Object({ foo: [object Number], bar: [object Object], baz: 3, qux: Error: bar })"); + expect(jasmineUnderTest.pp(obj)).toEqual( + 'Object({ foo: [object Number], bar: [object Object], baz: 3, qux: Error: bar })' + ); }); }); diff --git a/spec/core/QueueRunnerSpec.js b/spec/core/QueueRunnerSpec.js index 632565ba..e0b4c23c 100644 --- a/spec/core/QueueRunnerSpec.js +++ b/spec/core/QueueRunnerSpec.js @@ -1,5 +1,4 @@ -describe("QueueRunner", function() { - +describe('QueueRunner', function() { it("runs all the functions it's passed", function() { var calls = [], queueableFn1 = { fn: jasmine.createSpy('fn1') }, @@ -19,7 +18,7 @@ describe("QueueRunner", function() { expect(calls).toEqual(['fn1', 'fn2']); }); - it("runs cleanup functions after the others", function() { + it('runs cleanup functions after the others', function() { var calls = [], queueableFn1 = { fn: jasmine.createSpy('fn1') }, queueableFn2 = { fn: jasmine.createSpy('fn2') }, @@ -41,12 +40,17 @@ describe("QueueRunner", function() { it("calls each function with a consistent 'this'-- an empty object", function() { var queueableFn1 = { fn: jasmine.createSpy('fn1') }, - queueableFn2 = { fn: jasmine.createSpy('fn2') }, - queueableFn3 = { fn: function(done) { asyncContext = this; done(); } }, - queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn1, queueableFn2, queueableFn3] - }), - asyncContext; + queueableFn2 = { fn: jasmine.createSpy('fn2') }, + queueableFn3 = { + fn: function(done) { + asyncContext = this; + done(); + } + }, + queueRunner = new jasmineUnderTest.QueueRunner({ + queueableFns: [queueableFn1, queueableFn2, queueableFn3] + }), + asyncContext; queueRunner.execute(); @@ -56,7 +60,7 @@ describe("QueueRunner", function() { expect(asyncContext).toBe(context); }); - describe("with an asynchronous function", function() { + describe('with an asynchronous function', function() { beforeEach(function() { jasmine.clock().install(); }); @@ -65,7 +69,7 @@ describe("QueueRunner", function() { jasmine.clock().uninstall(); }); - it("supports asynchronous functions, only advancing to next function after a done() callback", function() { + it('supports asynchronous functions, only advancing to next function after a done() callback', function() { //TODO: it would be nice if spy arity could match the fake, so we could do something like: //createSpy('asyncfn').and.callFake(function(done) {}); @@ -73,18 +77,24 @@ describe("QueueRunner", function() { beforeCallback = jasmine.createSpy('beforeCallback'), fnCallback = jasmine.createSpy('fnCallback'), afterCallback = jasmine.createSpy('afterCallback'), - queueableFn1 = { fn: function(done) { - beforeCallback(); - setTimeout(done, 100); - } }, - queueableFn2 = { fn: function(done) { - fnCallback(); - setTimeout(done, 100); - } }, - queueableFn3 = { fn: function(done) { - afterCallback(); - setTimeout(done, 100); - } }, + queueableFn1 = { + fn: function(done) { + beforeCallback(); + setTimeout(done, 100); + } + }, + queueableFn2 = { + fn: function(done) { + fnCallback(); + setTimeout(done, 100); + } + }, + queueableFn3 = { + fn: function(done) { + afterCallback(); + setTimeout(done, 100); + } + }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn1, queueableFn2, queueableFn3], onComplete: onComplete @@ -113,10 +123,14 @@ describe("QueueRunner", function() { expect(onComplete).toHaveBeenCalled(); }); - it("explicitly fails an async function with a provided fail function and moves to the next function", function() { - var queueableFn1 = { fn: function(done) { - setTimeout(function() { done.fail('foo'); }, 100); - } }, + it('explicitly fails an async function with a provided fail function and moves to the next function', function() { + var queueableFn1 = { + fn: function(done) { + setTimeout(function() { + done.fail('foo'); + }, 100); + } + }, queueableFn2 = { fn: jasmine.createSpy('fn2') }, failFn = jasmine.createSpy('fail'), queueRunner = new jasmineUnderTest.QueueRunner({ @@ -135,11 +149,15 @@ describe("QueueRunner", function() { expect(queueableFn2.fn).toHaveBeenCalled(); }); - it("explicitly fails an async function when next is called with an Error and moves to the next function", function() { + it('explicitly fails an async function when next is called with an Error and moves to the next function', function() { var err = new Error('foo'), - queueableFn1 = { fn: function(done) { - setTimeout(function() { done(err); }, 100); - } }, + queueableFn1 = { + fn: function(done) { + setTimeout(function() { + done(err); + }, 100); + } + }, queueableFn2 = { fn: jasmine.createSpy('fn2') }, failFn = jasmine.createSpy('fail'), queueRunner = new jasmineUnderTest.QueueRunner({ @@ -158,11 +176,15 @@ describe("QueueRunner", function() { expect(queueableFn2.fn).toHaveBeenCalled(); }); - it("does not cause an explicit fail if execution is being stopped", function() { + it('does not cause an explicit fail if execution is being stopped', function() { var err = new jasmineUnderTest.StopExecutionError('foo'), - queueableFn1 = { fn: function(done) { - setTimeout(function() { done(err); }, 100); - } }, + queueableFn1 = { + fn: function(done) { + setTimeout(function() { + done(err); + }, 100); + } + }, queueableFn2 = { fn: jasmine.createSpy('fn2') }, failFn = jasmine.createSpy('fail'), queueRunner = new jasmineUnderTest.QueueRunner({ @@ -183,7 +205,7 @@ describe("QueueRunner", function() { it("sets a timeout if requested for asynchronous functions so they don't go on forever", function() { var timeout = 3, - beforeFn = { fn: function(done) { }, type: 'before', timeout: timeout }, + beforeFn = { fn: function(done) {}, type: 'before', timeout: timeout }, queueableFn = { fn: jasmine.createSpy('fn'), type: 'queueable' }, onComplete = jasmine.createSpy('onComplete'), onException = jasmine.createSpy('onException'), @@ -203,15 +225,15 @@ describe("QueueRunner", function() { expect(onComplete).toHaveBeenCalled(); }); - it("by default does not set a timeout for asynchronous functions", function() { - var beforeFn = { fn: function(done) { } }, + it('by default does not set a timeout for asynchronous functions', function() { + var beforeFn = { fn: function(done) {} }, queueableFn = { fn: jasmine.createSpy('fn') }, onComplete = jasmine.createSpy('onComplete'), onException = jasmine.createSpy('onException'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [beforeFn, queueableFn], onComplete: onComplete, - onException: onException, + onException: onException }); queueRunner.execute(); @@ -224,8 +246,12 @@ describe("QueueRunner", function() { expect(onComplete).not.toHaveBeenCalled(); }); - it("clears the timeout when an async function throws an exception, to prevent additional exception reporting", function() { - var queueableFn = { fn: function(done) { throw new Error("error!"); } }, + it('clears the timeout when an async function throws an exception, to prevent additional exception reporting', function() { + var queueableFn = { + fn: function(done) { + throw new Error('error!'); + } + }, onComplete = jasmine.createSpy('onComplete'), onException = jasmine.createSpy('onException'), queueRunner = new jasmineUnderTest.QueueRunner({ @@ -243,8 +269,12 @@ describe("QueueRunner", function() { expect(onException.calls.count()).toEqual(1); }); - it("clears the timeout when the done callback is called", function() { - var queueableFn = { fn: function(done) { done(); } }, + it('clears the timeout when the done callback is called', function() { + var queueableFn = { + fn: function(done) { + done(); + } + }, onComplete = jasmine.createSpy('onComplete'), onException = jasmine.createSpy('onException'), queueRunner = new jasmineUnderTest.QueueRunner({ @@ -262,8 +292,13 @@ describe("QueueRunner", function() { expect(onException).not.toHaveBeenCalled(); }); - it("only moves to the next spec the first time you call done", function() { - var queueableFn = { fn: function(done) {done(); done();} }, + it('only moves to the next spec the first time you call done', function() { + var queueableFn = { + fn: function(done) { + done(); + done(); + } + }, nextQueueableFn = { fn: jasmine.createSpy('nextFn') }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn, nextQueueableFn] @@ -274,27 +309,31 @@ describe("QueueRunner", function() { expect(nextQueueableFn.fn.calls.count()).toEqual(1); }); - it("does not move to the next spec if done is called after an exception has ended the spec", function() { - var queueableFn = { fn: function(done) { - setTimeout(done, 1); - throw new Error('error!'); - } }, - nextQueueableFn = { fn: jasmine.createSpy('nextFn') }, - queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn, nextQueueableFn] - }); + it('does not move to the next spec if done is called after an exception has ended the spec', function() { + var queueableFn = { + fn: function(done) { + setTimeout(done, 1); + throw new Error('error!'); + } + }, + nextQueueableFn = { fn: jasmine.createSpy('nextFn') }, + queueRunner = new jasmineUnderTest.QueueRunner({ + queueableFns: [queueableFn, nextQueueableFn] + }); queueRunner.execute(); jasmine.clock().tick(1); expect(nextQueueableFn.fn.calls.count()).toEqual(1); }); - it("should return a null when you call done", function () { + it('should return a null when you call done', function() { // Some promises want handlers to return anything but undefined to help catch "forgotten returns". var doneReturn, - queueableFn = { fn: function(done) { - doneReturn = done(); - } }, + queueableFn = { + fn: function(done) { + doneReturn = done(); + } + }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn] }); @@ -303,24 +342,36 @@ describe("QueueRunner", function() { expect(doneReturn).toBe(null); }); - it("continues running functions when an exception is thrown in async code without timing out", function() { - var queueableFn = { fn: function(done) { throwAsync(); }, timeout: 1 }, - nextQueueableFn = { fn: jasmine.createSpy("nextFunction") }, + it('continues running functions when an exception is thrown in async code without timing out', function() { + var queueableFn = { + fn: function(done) { + throwAsync(); + }, + timeout: 1 + }, + nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, onException = jasmine.createSpy('onException'), - globalErrors = { pushListener: jasmine.createSpy('pushListener'), popListener: jasmine.createSpy('popListener') }, + globalErrors = { + pushListener: jasmine.createSpy('pushListener'), + popListener: jasmine.createSpy('popListener') + }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn, nextQueueableFn], onException: onException, globalErrors: globalErrors }), throwAsync = function() { - globalErrors.pushListener.calls.mostRecent().args[0](new Error('foo')); + globalErrors.pushListener.calls + .mostRecent() + .args[0](new Error('foo')); jasmine.clock().tick(2); }; nextQueueableFn.fn.and.callFake(function() { // should remove the same function that was added - expect(globalErrors.popListener).toHaveBeenCalledWith(globalErrors.pushListener.calls.argsFor(1)[0]); + expect(globalErrors.popListener).toHaveBeenCalledWith( + globalErrors.pushListener.calls.argsFor(1)[0] + ); }); queueRunner.execute(); @@ -335,28 +386,37 @@ describe("QueueRunner", function() { } }; } - expect(onException).not.toHaveBeenCalledWith(errorWithMessage(/DEFAULT_TIMEOUT_INTERVAL/)); + expect(onException).not.toHaveBeenCalledWith( + errorWithMessage(/DEFAULT_TIMEOUT_INTERVAL/) + ); expect(onException).toHaveBeenCalledWith(errorWithMessage(/^foo$/)); expect(nextQueueableFn.fn).toHaveBeenCalled(); }); - it("handles exceptions thrown while waiting for the stack to clear", function() { - var queueableFn = { fn: function(done) { done() } }, - global = {}, - errorListeners = [], - globalErrors = { - pushListener: function(f) { errorListeners.push(f); }, - popListener: function() { errorListeners.pop(); } - }, - clearStack = jasmine.createSpy('clearStack'), - onException = jasmine.createSpy('onException'), - queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn], - globalErrors: globalErrors, - clearStack: clearStack, - onException: onException - }), - error = new Error('nope'); + it('handles exceptions thrown while waiting for the stack to clear', function() { + var queueableFn = { + fn: function(done) { + done(); + } + }, + errorListeners = [], + globalErrors = { + pushListener: function(f) { + errorListeners.push(f); + }, + popListener: function() { + errorListeners.pop(); + } + }, + clearStack = jasmine.createSpy('clearStack'), + onException = jasmine.createSpy('onException'), + queueRunner = new jasmineUnderTest.QueueRunner({ + queueableFns: [queueableFn], + globalErrors: globalErrors, + clearStack: clearStack, + onException: onException + }), + error = new Error('nope'); queueRunner.execute(); jasmine.clock().tick(); @@ -368,7 +428,7 @@ describe("QueueRunner", function() { }); }); - describe("with a function that returns a promise", function() { + describe('with a function that returns a promise', function() { function StubPromise() {} StubPromise.prototype.then = function(resolve, reject) { @@ -384,28 +444,32 @@ describe("QueueRunner", function() { jasmine.clock().uninstall(); }); - it("runs the function asynchronously, advancing once the promise is settled", function() { + it('runs the function asynchronously, advancing once the promise is settled', function() { var onComplete = jasmine.createSpy('onComplete'), - fnCallback = jasmine.createSpy('fnCallback'), + fnCallback = jasmine.createSpy('fnCallback'), p1 = new StubPromise(), p2 = new StubPromise(), - queueableFn1 = { fn: function() { - setTimeout(function() { - p1.resolveHandler(); - }, 100); - return p1; - } }; - queueableFn2 = { fn: function() { + queueableFn1 = { + fn: function() { + setTimeout(function() { + p1.resolveHandler(); + }, 100); + return p1; + } + }; + (queueableFn2 = { + fn: function() { fnCallback(); setTimeout(function() { p2.resolveHandler(); }, 100); return p2; - } }, - queueRunner = new jasmineUnderTest.QueueRunner({ + } + }), + (queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn1, queueableFn2], onComplete: onComplete - }); + })); queueRunner.execute(); expect(fnCallback).not.toHaveBeenCalled(); @@ -421,16 +485,17 @@ describe("QueueRunner", function() { expect(onComplete).toHaveBeenCalled(); }); - it("handles a rejected promise like an unhandled exception", function() { + it('handles a rejected promise like an unhandled exception', function() { var promise = new StubPromise(), - queueableFn1 = { fn: function() { - setTimeout(function() { - promise.rejectHandler('foo') - }, 100); - return promise; - } }, + queueableFn1 = { + fn: function() { + setTimeout(function() { + promise.rejectHandler('foo'); + }, 100); + return promise; + } + }, queueableFn2 = { fn: jasmine.createSpy('fn2') }, - failFn = jasmine.createSpy('fail'), onExceptionCallback = jasmine.createSpy('on exception callback'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn1, queueableFn2], @@ -449,11 +514,13 @@ describe("QueueRunner", function() { }); }); - it("calls exception handlers when an exception is thrown in a fn", function() { - var queueableFn = { type: 'queueable', - fn: function() { - throw new Error('fake error'); - } }, + it('calls exception handlers when an exception is thrown in a fn', function() { + var queueableFn = { + type: 'queueable', + fn: function() { + throw new Error('fake error'); + } + }, onExceptionCallback = jasmine.createSpy('on exception callback'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn], @@ -465,9 +532,13 @@ describe("QueueRunner", function() { expect(onExceptionCallback).toHaveBeenCalledWith(jasmine.any(Error)); }); - it("continues running the functions even after an exception is thrown in an async spec", function() { - var queueableFn = { fn: function(done) { throw new Error("error"); } }, - nextQueueableFn = { fn: jasmine.createSpy("nextFunction") }, + it('continues running the functions even after an exception is thrown in an async spec', function() { + var queueableFn = { + fn: function(done) { + throw new Error('error'); + } + }, + nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn, nextQueueableFn] }); @@ -476,12 +547,16 @@ describe("QueueRunner", function() { expect(nextQueueableFn.fn).toHaveBeenCalled(); }); - describe("When configured to complete on first error", function() { - it("skips to cleanup functions on the first exception", function() { - var queueableFn = { fn: function() { throw new Error("error"); } }, - nextQueueableFn = { fn: jasmine.createSpy("nextFunction") }, - cleanupFn = { fn: jasmine.createSpy("cleanup") }, - onComplete = jasmine.createSpy("onComplete"), + describe('When configured to complete on first error', function() { + it('skips to cleanup functions on the first exception', function() { + var queueableFn = { + fn: function() { + throw new Error('error'); + } + }, + nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, + cleanupFn = { fn: jasmine.createSpy('cleanup') }, + onComplete = jasmine.createSpy('onComplete'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn, nextQueueableFn], cleanupFns: [cleanupFn], @@ -492,13 +567,19 @@ describe("QueueRunner", function() { queueRunner.execute(); expect(nextQueueableFn.fn).not.toHaveBeenCalled(); expect(cleanupFn.fn).toHaveBeenCalled(); - expect(onComplete).toHaveBeenCalledWith(jasmine.any(jasmineUnderTest.StopExecutionError)); + expect(onComplete).toHaveBeenCalledWith( + jasmine.any(jasmineUnderTest.StopExecutionError) + ); }); - it("does not skip when a cleanup function throws", function() { - var queueableFn = { fn: function() { } }, - cleanupFn1 = { fn: function() { throw new Error("error"); } }, - cleanupFn2 = { fn: jasmine.createSpy("cleanupFn2") }, + it('does not skip when a cleanup function throws', function() { + var queueableFn = { fn: function() {} }, + cleanupFn1 = { + fn: function() { + throw new Error('error'); + } + }, + cleanupFn2 = { fn: jasmine.createSpy('cleanupFn2') }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn], cleanupFns: [cleanupFn1, cleanupFn2], @@ -509,7 +590,7 @@ describe("QueueRunner", function() { expect(cleanupFn2.fn).toHaveBeenCalled(); }); - describe("with an asynchronous function", function() { + describe('with an asynchronous function', function() { beforeEach(function() { jasmine.clock().install(); }); @@ -518,21 +599,24 @@ describe("QueueRunner", function() { jasmine.clock().uninstall(); }); - - it("skips to cleanup functions on the first exception", function() { + it('skips to cleanup functions on the first exception', function() { var errorListeners = [], queueableFn = { fn: function(done) {} }, nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, cleanupFn = { fn: jasmine.createSpy('cleanup') }, queueRunner = new jasmineUnderTest.QueueRunner({ globalErrors: { - pushListener: function(f) { errorListeners.push(f); }, - popListener: function() { errorListeners.pop(); }, + pushListener: function(f) { + errorListeners.push(f); + }, + popListener: function() { + errorListeners.pop(); + } }, queueableFns: [queueableFn, nextQueueableFn], cleanupFns: [cleanupFn], - completeOnFirstError: true, - }); + completeOnFirstError: true + }); queueRunner.execute(); errorListeners[errorListeners.length - 1](new Error('error')); @@ -540,17 +624,19 @@ describe("QueueRunner", function() { expect(cleanupFn.fn).toHaveBeenCalled(); }); - it("skips to cleanup functions when next.fail is called", function() { - var queueableFn = { fn: function(done) { - done.fail('nope'); - } }, + it('skips to cleanup functions when next.fail is called', function() { + var queueableFn = { + fn: function(done) { + done.fail('nope'); + } + }, nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, cleanupFn = { fn: jasmine.createSpy('cleanup') }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn, nextQueueableFn], cleanupFns: [cleanupFn], - completeOnFirstError: true, - }); + completeOnFirstError: true + }); queueRunner.execute(); jasmine.clock().tick(); @@ -558,17 +644,19 @@ describe("QueueRunner", function() { expect(cleanupFn.fn).toHaveBeenCalled(); }); - it("skips to cleanup functions when next is called with an Error", function() { - var queueableFn = { fn: function(done) { - done(new Error('nope')); - } }, + it('skips to cleanup functions when next is called with an Error', function() { + var queueableFn = { + fn: function(done) { + done(new Error('nope')); + } + }, nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, cleanupFn = { fn: jasmine.createSpy('cleanup') }, queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn, nextQueueableFn], cleanupFns: [cleanupFn], - completeOnFirstError: true, - }); + completeOnFirstError: true + }); queueRunner.execute(); jasmine.clock().tick(); @@ -578,7 +666,7 @@ describe("QueueRunner", function() { }); }); - it("calls a provided complete callback when done", function() { + it('calls a provided complete callback when done', function() { var queueableFn = { fn: jasmine.createSpy('fn') }, completeCallback = jasmine.createSpy('completeCallback'), queueRunner = new jasmineUnderTest.QueueRunner({ @@ -591,7 +679,7 @@ describe("QueueRunner", function() { expect(completeCallback).toHaveBeenCalled(); }); - describe("clearing the stack", function() { + describe('clearing the stack', function() { beforeEach(function() { jasmine.clock().install(); }); @@ -600,18 +688,24 @@ describe("QueueRunner", function() { jasmine.clock().uninstall(); }); - it("calls a provided stack clearing function when done", function() { - var asyncFn = { fn: function(done) { done() } }, - afterFn = { fn: jasmine.createSpy('afterFn') }, - completeCallback = jasmine.createSpy('completeCallback'), - clearStack = jasmine.createSpy('clearStack'), - queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [asyncFn, afterFn], - clearStack: clearStack, - onComplete: completeCallback - }); + it('calls a provided stack clearing function when done', function() { + var asyncFn = { + fn: function(done) { + done(); + } + }, + afterFn = { fn: jasmine.createSpy('afterFn') }, + completeCallback = jasmine.createSpy('completeCallback'), + clearStack = jasmine.createSpy('clearStack'), + queueRunner = new jasmineUnderTest.QueueRunner({ + queueableFns: [asyncFn, afterFn], + clearStack: clearStack, + onComplete: completeCallback + }); - clearStack.and.callFake(function(fn) { fn(); }); + clearStack.and.callFake(function(fn) { + fn(); + }); queueRunner.execute(); jasmine.clock().tick(); @@ -633,9 +727,7 @@ describe("QueueRunner", function() { }); it('runs the functions on the scope of a UserContext', function() { - var calls = [], - context; - + var context; this.fn.and.callFake(function() { context = this; }); @@ -659,8 +751,7 @@ describe("QueueRunner", function() { }); it('runs the functions on the scope of a UserContext', function() { - var calls = [], - context; + var context; this.fn.and.callFake(function() { context = this; }); diff --git a/spec/core/ReportDispatcherSpec.js b/spec/core/ReportDispatcherSpec.js index 87511ab7..2b569844 100644 --- a/spec/core/ReportDispatcherSpec.js +++ b/spec/core/ReportDispatcherSpec.js @@ -1,16 +1,22 @@ -describe("ReportDispatcher", function() { - - it("builds an interface of requested methods", function() { - var dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar', 'baz']); +describe('ReportDispatcher', function() { + it('builds an interface of requested methods', function() { + var dispatcher = new jasmineUnderTest.ReportDispatcher([ + 'foo', + 'bar', + 'baz' + ]); expect(dispatcher.foo).toBeDefined(); expect(dispatcher.bar).toBeDefined(); expect(dispatcher.baz).toBeDefined(); }); - it("dispatches requested methods to added reporters", function() { + it('dispatches requested methods to added reporters', function() { var queueRunnerFactory = jasmine.createSpy('queueRunner'), - dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar'], queueRunnerFactory), + dispatcher = new jasmineUnderTest.ReportDispatcher( + ['foo', 'bar'], + queueRunnerFactory + ), reporter = jasmine.createSpyObj('reporter', ['foo', 'bar']), anotherReporter = jasmine.createSpyObj('reporter', ['foo', 'bar']), completeCallback = jasmine.createSpy('complete'); @@ -20,10 +26,15 @@ describe("ReportDispatcher", function() { dispatcher.foo(123, 456, completeCallback); - expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({ - queueableFns: [{fn: jasmine.any(Function)}, {fn: jasmine.any(Function)}], - isReporter: true - })); + expect(queueRunnerFactory).toHaveBeenCalledWith( + jasmine.objectContaining({ + queueableFns: [ + { fn: jasmine.any(Function) }, + { fn: jasmine.any(Function) } + ], + isReporter: true + }) + ); var fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns; fns[0].fn(); @@ -38,10 +49,15 @@ describe("ReportDispatcher", function() { dispatcher.bar('a', 'b', completeCallback); - expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({ - queueableFns: [{fn: jasmine.any(Function)}, {fn: jasmine.any(Function)}], - isReporter: true - })); + expect(queueRunnerFactory).toHaveBeenCalledWith( + jasmine.objectContaining({ + queueableFns: [ + { fn: jasmine.any(Function) }, + { fn: jasmine.any(Function) } + ], + isReporter: true + }) + ); fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns; fns[0].fn(); @@ -53,39 +69,52 @@ describe("ReportDispatcher", function() { it("does not dispatch to a reporter if the reporter doesn't accept the method", function() { var queueRunnerFactory = jasmine.createSpy('queueRunner'), - dispatcher = new jasmineUnderTest.ReportDispatcher(['foo'], queueRunnerFactory), + dispatcher = new jasmineUnderTest.ReportDispatcher( + ['foo'], + queueRunnerFactory + ), reporter = jasmine.createSpyObj('reporter', ['baz']); dispatcher.addReporter(reporter); dispatcher.foo(123, 456); - expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({ - queueableFns: [] - })); + expect(queueRunnerFactory).toHaveBeenCalledWith( + jasmine.objectContaining({ + queueableFns: [] + }) + ); }); it("allows providing a fallback reporter in case there's no other reporter", function() { var queueRunnerFactory = jasmine.createSpy('queueRunner'), - dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar'], queueRunnerFactory), + dispatcher = new jasmineUnderTest.ReportDispatcher( + ['foo', 'bar'], + queueRunnerFactory + ), reporter = jasmine.createSpyObj('reporter', ['foo', 'bar']), completeCallback = jasmine.createSpy('complete'); dispatcher.provideFallbackReporter(reporter); dispatcher.foo(123, 456, completeCallback); - expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({ - queueableFns: [{fn: jasmine.any(Function)}], - isReporter: true - })); + expect(queueRunnerFactory).toHaveBeenCalledWith( + jasmine.objectContaining({ + queueableFns: [{ fn: jasmine.any(Function) }], + isReporter: true + }) + ); var fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns; fns[0].fn(); expect(reporter.foo).toHaveBeenCalledWith(123, 456); }); - it("does not call fallback reporting methods when another reporter is provided", function() { + it('does not call fallback reporting methods when another reporter is provided', function() { var queueRunnerFactory = jasmine.createSpy('queueRunner'), - dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar'], queueRunnerFactory), + dispatcher = new jasmineUnderTest.ReportDispatcher( + ['foo', 'bar'], + queueRunnerFactory + ), reporter = jasmine.createSpyObj('reporter', ['foo', 'bar']), fallbackReporter = jasmine.createSpyObj('otherReporter', ['foo', 'bar']), completeCallback = jasmine.createSpy('complete'); @@ -94,10 +123,12 @@ describe("ReportDispatcher", function() { dispatcher.addReporter(reporter); dispatcher.foo(123, 456, completeCallback); - expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({ - queueableFns: [{fn: jasmine.any(Function)}], - isReporter: true - })); + expect(queueRunnerFactory).toHaveBeenCalledWith( + jasmine.objectContaining({ + queueableFns: [{ fn: jasmine.any(Function) }], + isReporter: true + }) + ); var fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns; fns[0].fn(); @@ -105,19 +136,24 @@ describe("ReportDispatcher", function() { expect(fallbackReporter.foo).not.toHaveBeenCalledWith(123, 456); }); - it("allows registered reporters to be cleared", function() { + it('allows registered reporters to be cleared', function() { var queueRunnerFactory = jasmine.createSpy('queueRunner'), - dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar'], queueRunnerFactory), - reporter1 = jasmine.createSpyObj('reporter1', ['foo', 'bar']), - reporter2 = jasmine.createSpyObj('reporter2', ['foo', 'bar']), + dispatcher = new jasmineUnderTest.ReportDispatcher( + ['foo', 'bar'], + queueRunnerFactory + ), + reporter1 = jasmine.createSpyObj('reporter1', ['foo', 'bar']), + reporter2 = jasmine.createSpyObj('reporter2', ['foo', 'bar']), completeCallback = jasmine.createSpy('complete'); dispatcher.addReporter(reporter1); dispatcher.foo(123, completeCallback); - expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({ - queueableFns: [{fn: jasmine.any(Function)}], - isReporter: true - })); + expect(queueRunnerFactory).toHaveBeenCalledWith( + jasmine.objectContaining({ + queueableFns: [{ fn: jasmine.any(Function) }], + isReporter: true + }) + ); var fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns; fns[0].fn(); @@ -127,10 +163,12 @@ describe("ReportDispatcher", function() { dispatcher.addReporter(reporter2); dispatcher.bar(456, completeCallback); - expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({ - queueableFns: [{fn: jasmine.any(Function)}], - isReporter: true - })); + expect(queueRunnerFactory).toHaveBeenCalledWith( + jasmine.objectContaining({ + queueableFns: [{ fn: jasmine.any(Function) }], + isReporter: true + }) + ); fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns; fns[0].fn(); diff --git a/spec/core/SpecSpec.js b/spec/core/SpecSpec.js index 1191f7c3..8219a1cd 100644 --- a/spec/core/SpecSpec.js +++ b/spec/core/SpecSpec.js @@ -1,25 +1,30 @@ -describe("Spec", function() { - - it("#isPendingSpecException returns true for a pending spec exception", function() { +describe('Spec', function() { + it('#isPendingSpecException returns true for a pending spec exception', function() { var e = new Error(jasmineUnderTest.Spec.pendingSpecExceptionMessage); expect(jasmineUnderTest.Spec.isPendingSpecException(e)).toBe(true); }); - it("#isPendingSpecException returns true for a pending spec exception (even when FF bug is present)", function() { + it('#isPendingSpecException returns true for a pending spec exception (even when FF bug is present)', function() { var fakeError = { - toString: function() { return "Error: " + jasmineUnderTest.Spec.pendingSpecExceptionMessage; } + toString: function() { + return 'Error: ' + jasmineUnderTest.Spec.pendingSpecExceptionMessage; + } }; expect(jasmineUnderTest.Spec.isPendingSpecException(fakeError)).toBe(true); }); - it("#isPendingSpecException returns true for a pending spec exception with a custom message", function() { - expect(jasmineUnderTest.Spec.isPendingSpecException(jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'foo')).toBe(true); + it('#isPendingSpecException returns true for a pending spec exception with a custom message', function() { + expect( + jasmineUnderTest.Spec.isPendingSpecException( + jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'foo' + ) + ).toBe(true); }); - it("#isPendingSpecException returns false for not a pending spec exception", function() { - var e = new Error("foo"); + it('#isPendingSpecException returns false for not a pending spec exception', function() { + var e = new Error('foo'); expect(jasmineUnderTest.Spec.isPendingSpecException(e)).toBe(false); }); @@ -28,7 +33,7 @@ describe("Spec", function() { expect(jasmineUnderTest.Spec.isPendingSpecException(void 0)).toBe(false); }); - it("delegates execution to a QueueRunner", function() { + it('delegates execution to a QueueRunner', function() { var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'), spec = new jasmineUnderTest.Spec({ description: 'my test', @@ -42,7 +47,7 @@ describe("Spec", function() { expect(fakeQueueRunner).toHaveBeenCalled(); }); - it("should call the start callback on execution", function() { + it('should call the start callback on execution', function() { var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'), startCallback = jasmine.createSpy('startCallback'), spec = new jasmineUnderTest.Spec({ @@ -64,18 +69,22 @@ describe("Spec", function() { expect(startCallback.calls.first().object).toEqual(spec); }); - it("should call the start callback on execution but before any befores are called", function() { + it('should call the start callback on execution but before any befores are called', function() { var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'), beforesWereCalled = false, - startCallback = jasmine.createSpy('start-callback').and.callFake(function() { - expect(beforesWereCalled).toBe(false); - }), + startCallback = jasmine + .createSpy('start-callback') + .and.callFake(function() { + expect(beforesWereCalled).toBe(false); + }), spec = new jasmineUnderTest.Spec({ queueableFn: { fn: function() {} }, beforeFns: function() { - return [function() { - beforesWereCalled = true - }] + return [ + function() { + beforesWereCalled = true; + } + ]; }, onStart: startCallback, queueRunnerFactory: fakeQueueRunner @@ -87,18 +96,20 @@ describe("Spec", function() { expect(startCallback).toHaveBeenCalled(); }); - it("provides all before fns and after fns to be run", function() { + it('provides all before fns and after fns to be run', function() { var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'), before = jasmine.createSpy('before'), after = jasmine.createSpy('after'), - queueableFn = { fn: jasmine.createSpy('test body').and.callFake(function() { - expect(before).toHaveBeenCalled(); - expect(after).not.toHaveBeenCalled(); - }) }, + queueableFn = { + fn: jasmine.createSpy('test body').and.callFake(function() { + expect(before).toHaveBeenCalled(); + expect(after).not.toHaveBeenCalled(); + }) + }, spec = new jasmineUnderTest.Spec({ queueableFn: queueableFn, beforeAndAfterFns: function() { - return {befores: [before], afters: [after]} + return { befores: [before], afters: [after] }; }, queueRunnerFactory: fakeQueueRunner }); @@ -106,8 +117,12 @@ describe("Spec", function() { spec.execute(); var options = fakeQueueRunner.calls.mostRecent().args[0]; - expect(options.queueableFns).toEqual([{fn: jasmine.any(Function)}, before, queueableFn]); - expect(options.cleanupFns).toEqual([after, {fn: jasmine.any(Function)}]); + expect(options.queueableFns).toEqual([ + { fn: jasmine.any(Function) }, + before, + queueableFn + ]); + expect(options.cleanupFns).toEqual([after, { fn: jasmine.any(Function) }]); }); it("tells the queue runner that it's a leaf node", function() { @@ -115,21 +130,22 @@ describe("Spec", function() { spec = new jasmineUnderTest.Spec({ queueableFn: { fn: function() {} }, beforeAndAfterFns: function() { - return {befores: [], afters: []} + return { befores: [], afters: [] }; }, queueRunnerFactory: fakeQueueRunner }); spec.execute(); - expect(fakeQueueRunner).toHaveBeenCalledWith(jasmine.objectContaining({ - isLeaf: true - })); + expect(fakeQueueRunner).toHaveBeenCalledWith( + jasmine.objectContaining({ + isLeaf: true + }) + ); }); - it("is marked pending if created without a function body", function() { + it('is marked pending if created without a function body', function() { var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'), - startCallback = jasmine.createSpy('startCallback'), resultCallback = jasmine.createSpy('resultCallback'), spec = new jasmineUnderTest.Spec({ @@ -142,13 +158,13 @@ describe("Spec", function() { expect(spec.status()).toBe('pending'); }); - it("can be excluded at execution time by a parent", function() { + it('can be excluded at execution time by a parent', function() { var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'), startCallback = jasmine.createSpy('startCallback'), specBody = jasmine.createSpy('specBody'), resultCallback = jasmine.createSpy('resultCallback'), spec = new jasmineUnderTest.Spec({ - onStart:startCallback, + onStart: startCallback, queueableFn: { fn: specBody }, resultCallback: resultCallback, queueRunnerFactory: fakeQueueRunner @@ -156,11 +172,13 @@ describe("Spec", function() { spec.execute('cally-back', true); - expect(fakeQueueRunner).toHaveBeenCalledWith(jasmine.objectContaining({ - onComplete: jasmine.any(Function), - queueableFns: [{fn: jasmine.any(Function)}], - cleanupFns: [{fn: jasmine.any(Function)}] - })); + expect(fakeQueueRunner).toHaveBeenCalledWith( + jasmine.objectContaining({ + onComplete: jasmine.any(Function), + queueableFns: [{ fn: jasmine.any(Function) }], + cleanupFns: [{ fn: jasmine.any(Function) }] + }) + ); expect(specBody).not.toHaveBeenCalled(); var args = fakeQueueRunner.calls.mostRecent().args[0]; @@ -172,16 +190,16 @@ describe("Spec", function() { expect(spec.result.status).toBe('excluded'); }); - it("can be marked pending, but still calls callbacks when executed", function() { + it('can be marked pending, but still calls callbacks when executed', function() { var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'), startCallback = jasmine.createSpy('startCallback'), resultCallback = jasmine.createSpy('resultCallback'), spec = new jasmineUnderTest.Spec({ onStart: startCallback, resultCallback: resultCallback, - description: "with a spec", + description: 'with a spec', getSpecName: function() { - return "a suite with a spec" + return 'a suite with a spec'; }, queueRunnerFactory: fakeQueueRunner, queueableFn: { fn: null } @@ -199,26 +217,33 @@ describe("Spec", function() { args.queueableFns[0].fn(); expect(startCallback).toHaveBeenCalled(); args.cleanupFns[0].fn('things'); - expect(resultCallback).toHaveBeenCalledWith({ - id: spec.id, - status: 'pending', - description: 'with a spec', - fullName: 'a suite with a spec', - failedExpectations: [], - passedExpectations: [], - deprecationWarnings: [], - pendingReason: '', - duration: null, - }, 'things'); + expect(resultCallback).toHaveBeenCalledWith( + { + id: spec.id, + status: 'pending', + description: 'with a spec', + fullName: 'a suite with a spec', + failedExpectations: [], + passedExpectations: [], + deprecationWarnings: [], + pendingReason: '', + duration: null + }, + 'things' + ); }); - it("should call the done callback on execution complete", function() { + it('should call the done callback on execution complete', function() { var done = jasmine.createSpy('done callback'), spec = new jasmineUnderTest.Spec({ queueableFn: { fn: function() {} }, - catchExceptions: function() { return false; }, + catchExceptions: function() { + return false; + }, resultCallback: function() {}, - queueRunnerFactory: function(attrs) { attrs.onComplete(); } + queueRunnerFactory: function(attrs) { + attrs.onComplete(); + } }); spec.execute(done); @@ -226,11 +251,13 @@ describe("Spec", function() { expect(done).toHaveBeenCalled(); }); - it("should call the done callback with an error if the spec is failed", function() { + it('should call the done callback with an error if the spec is failed', function() { var done = jasmine.createSpy('done callback'), spec = new jasmineUnderTest.Spec({ queueableFn: { fn: function() {} }, - catchExceptions: function() { return false; }, + catchExceptions: function() { + return false; + }, resultCallback: function() {}, queueRunnerFactory: function(attrs) { spec.result.status = 'failed'; @@ -240,49 +267,61 @@ describe("Spec", function() { spec.execute(done); - expect(done).toHaveBeenCalledWith(jasmine.any(jasmineUnderTest.StopExecutionError)); + expect(done).toHaveBeenCalledWith( + jasmine.any(jasmineUnderTest.StopExecutionError) + ); }); - it("should report the duration of the test", function() { + it('should report the duration of the test', function() { var done = jasmine.createSpy('done callback'), - timer = jasmine.createSpyObj('timer', {'start': null, elapsed: 77000}), + timer = jasmine.createSpyObj('timer', { start: null, elapsed: 77000 }), spec = new jasmineUnderTest.Spec({ - queueableFn: { fn: jasmine.createSpy("spec body")}, - catchExceptions: function() { return false; }, + queueableFn: { fn: jasmine.createSpy('spec body') }, + catchExceptions: function() { + return false; + }, resultCallback: function() {}, queueRunnerFactory: function(attrs) { attrs.onComplete(); }, - timer: timer, + timer: timer }); spec.execute(done); expect(spec.result.duration).toBe(77000); }); - it("#status returns passing by default", function() { - var spec = new jasmineUnderTest.Spec({queueableFn: { fn: jasmine.createSpy("spec body")} }); + it('#status returns passing by default', function() { + var spec = new jasmineUnderTest.Spec({ + queueableFn: { fn: jasmine.createSpy('spec body') } + }); expect(spec.status()).toBe('passed'); }); - it("#status returns passed if all expectations in the spec have passed", function() { - var spec = new jasmineUnderTest.Spec({queueableFn: { fn: jasmine.createSpy("spec body")} }); + it('#status returns passed if all expectations in the spec have passed', function() { + var spec = new jasmineUnderTest.Spec({ + queueableFn: { fn: jasmine.createSpy('spec body') } + }); spec.addExpectationResult(true); expect(spec.status()).toBe('passed'); }); - it("#status returns failed if any expectations in the spec have failed", function() { - var spec = new jasmineUnderTest.Spec({queueableFn: { fn: jasmine.createSpy("spec body") } }); + it('#status returns failed if any expectations in the spec have failed', function() { + var spec = new jasmineUnderTest.Spec({ + queueableFn: { fn: jasmine.createSpy('spec body') } + }); spec.addExpectationResult(true); spec.addExpectationResult(false); expect(spec.status()).toBe('failed'); }); - it("keeps track of passed and failed expectations", function() { + it('keeps track of passed and failed expectations', function() { var fakeQueueRunner = jasmine.createSpy('queueRunner'), resultCallback = jasmine.createSpy('resultCallback'), spec = new jasmineUnderTest.Spec({ - queueableFn: { fn: jasmine.createSpy("spec body") }, - expectationResultFactory: function (data) { return data; }, + queueableFn: { fn: jasmine.createSpy('spec body') }, + expectationResultFactory: function(data) { + return data; + }, queueRunnerFactory: fakeQueueRunner, resultCallback: resultCallback }); @@ -292,8 +331,12 @@ describe("Spec", function() { spec.execute(); fakeQueueRunner.calls.mostRecent().args[0].cleanupFns[0].fn(); - expect(resultCallback.calls.first().args[0].passedExpectations).toEqual(['expectation1']); - expect(resultCallback.calls.first().args[0].failedExpectations).toEqual(['expectation2']); + expect(resultCallback.calls.first().args[0].passedExpectations).toEqual([ + 'expectation1' + ]); + expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([ + 'expectation2' + ]); }); it("throws an ExpectationFailed error upon receiving a failed expectation when 'throwOnExpectationFailure' is set", function() { @@ -301,7 +344,9 @@ describe("Spec", function() { resultCallback = jasmine.createSpy('resultCallback'), spec = new jasmineUnderTest.Spec({ queueableFn: { fn: function() {} }, - expectationResultFactory: function(data) { return data; }, + expectationResultFactory: function(data) { + return data; + }, queueRunnerFactory: fakeQueueRunner, resultCallback: resultCallback, throwOnExpectationFailure: true @@ -309,22 +354,30 @@ describe("Spec", function() { spec.addExpectationResult(true, 'passed'); expect(function() { - spec.addExpectationResult(false, 'failed') + spec.addExpectationResult(false, 'failed'); }).toThrowError(jasmineUnderTest.errors.ExpectationFailed); spec.execute(); fakeQueueRunner.calls.mostRecent().args[0].cleanupFns[0].fn(); - expect(resultCallback.calls.first().args[0].passedExpectations).toEqual(['passed']); - expect(resultCallback.calls.first().args[0].failedExpectations).toEqual(['failed']); + expect(resultCallback.calls.first().args[0].passedExpectations).toEqual([ + 'passed' + ]); + expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([ + 'failed' + ]); }); - it("does not throw an ExpectationFailed error when handling an error", function() { + it('does not throw an ExpectationFailed error when handling an error', function() { var resultCallback = jasmine.createSpy('resultCallback'), spec = new jasmineUnderTest.Spec({ queueableFn: { fn: function() {} }, - expectationResultFactory: function(data) { return data; }, - queueRunnerFactory: function(attrs) { attrs.onComplete(); }, + expectationResultFactory: function(data) { + return data; + }, + queueRunnerFactory: function(attrs) { + attrs.onComplete(); + }, resultCallback: resultCallback, throwOnExpectationFailure: true }); @@ -332,8 +385,10 @@ describe("Spec", function() { spec.onException('failing exception'); }); - it("can return its full name", function() { - var specNameSpy = jasmine.createSpy('specNameSpy').and.returnValue('expected val'); + it('can return its full name', function() { + var specNameSpy = jasmine + .createSpy('specNameSpy') + .and.returnValue('expected val'); var spec = new jasmineUnderTest.Spec({ getSpecName: specNameSpy, @@ -344,48 +399,57 @@ describe("Spec", function() { expect(specNameSpy.calls.mostRecent().args[0].id).toEqual(spec.id); }); - describe("when a spec is marked pending during execution", function() { - it("should mark the spec as pending", function() { + describe('when a spec is marked pending during execution', function() { + it('should mark the spec as pending', function() { var fakeQueueRunner = function(opts) { - opts.onException(new Error(jasmineUnderTest.Spec.pendingSpecExceptionMessage)); + opts.onException( + new Error(jasmineUnderTest.Spec.pendingSpecExceptionMessage) + ); }, spec = new jasmineUnderTest.Spec({ description: 'my test', id: 'some-id', - queueableFn: { fn: function() { } }, + queueableFn: { fn: function() {} }, queueRunnerFactory: fakeQueueRunner }); spec.execute(); - expect(spec.status()).toEqual("pending"); + expect(spec.status()).toEqual('pending'); expect(spec.result.pendingReason).toEqual(''); }); - it("should set the pendingReason", function() { + it('should set the pendingReason', function() { var fakeQueueRunner = function(opts) { - opts.onException(new Error(jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'custom message')); + opts.onException( + new Error( + jasmineUnderTest.Spec.pendingSpecExceptionMessage + + 'custom message' + ) + ); }, spec = new jasmineUnderTest.Spec({ description: 'my test', id: 'some-id', - queueableFn: { fn: function() { } }, + queueableFn: { fn: function() {} }, queueRunnerFactory: fakeQueueRunner }); spec.execute(); - expect(spec.status()).toEqual("pending"); + expect(spec.status()).toEqual('pending'); expect(spec.result.pendingReason).toEqual('custom message'); }); }); - it("should log a failure when handling an exception", function() { + it('should log a failure when handling an exception', function() { var fakeQueueRunner = jasmine.createSpy('queueRunner'), resultCallback = jasmine.createSpy('resultCallback'), spec = new jasmineUnderTest.Spec({ queueableFn: { fn: function() {} }, - expectationResultFactory: function(data) { return data; }, + expectationResultFactory: function(data) { + return data; + }, queueRunnerFactory: fakeQueueRunner, resultCallback: resultCallback }); @@ -395,21 +459,25 @@ describe("Spec", function() { var args = fakeQueueRunner.calls.mostRecent().args[0]; args.cleanupFns[0].fn(); - expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([{ - error: 'foo', - matcherName: '', - passed: false, - expected: '', - actual: '' - }]); + expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([ + { + error: 'foo', + matcherName: '', + passed: false, + expected: '', + actual: '' + } + ]); }); - it("should not log an additional failure when handling an ExpectationFailed error", function() { + it('should not log an additional failure when handling an ExpectationFailed error', function() { var fakeQueueRunner = jasmine.createSpy('queueRunner'), resultCallback = jasmine.createSpy('resultCallback'), spec = new jasmineUnderTest.Spec({ queueableFn: { fn: function() {} }, - expectationResultFactory: function(data) { return data; }, + expectationResultFactory: function(data) { + return data; + }, queueRunnerFactory: fakeQueueRunner, resultCallback: resultCallback }); diff --git a/spec/core/SpyRegistrySpec.js b/spec/core/SpyRegistrySpec.js index dcf414a2..f3c81a47 100644 --- a/spec/core/SpyRegistrySpec.js +++ b/spec/core/SpyRegistrySpec.js @@ -1,33 +1,35 @@ -describe("SpyRegistry", function() { +describe('SpyRegistry', function() { function createSpy(name, originalFn) { return jasmineUnderTest.Spy(name, originalFn); } - describe("#spyOn", function() { - it("checks for the existence of the object", function() { - var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}); + describe('#spyOn', function() { + it('checks for the existence of the object', function() { + var spyRegistry = new jasmineUnderTest.SpyRegistry({ + createSpy: createSpy + }); expect(function() { spyRegistry.spyOn(void 0, 'pants'); }).toThrowError(/could not find an object/); }); - it("checks that a method name was passed", function() { + it('checks that a method name was passed', function() { var spyRegistry = new jasmineUnderTest.SpyRegistry(), subject = {}; - expect(function() { - spyRegistry.spyOn(subject); - }).toThrowError(/No method name supplied/); + expect(function() { + spyRegistry.spyOn(subject); + }).toThrowError(/No method name supplied/); }); - it("checks that the object is not `null`", function() { + it('checks that the object is not `null`', function() { var spyRegistry = new jasmineUnderTest.SpyRegistry(); expect(function() { spyRegistry.spyOn(null, 'pants'); }).toThrowError(/could not find an object/); }); - it("checks that the method name is not `null`", function() { + it('checks that the method name is not `null`', function() { var spyRegistry = new jasmineUnderTest.SpyRegistry(), subject = {}; @@ -36,7 +38,7 @@ describe("SpyRegistry", function() { }).toThrowError(/No method name supplied/); }); - it("checks for the existence of the method", function() { + it('checks for the existence of the method', function() { var spyRegistry = new jasmineUnderTest.SpyRegistry(), subject = {}; @@ -45,10 +47,12 @@ describe("SpyRegistry", function() { }).toThrowError(/method does not exist/); }); - it("checks if it has already been spied upon", function() { + it('checks if it has already been spied upon', function() { var spies = [], spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() { return spies; }, + currentSpies: function() { + return spies; + }, createSpy: createSpy }), subject = { spiedFunc: function() {} }; @@ -60,7 +64,7 @@ describe("SpyRegistry", function() { }).toThrowError(/has already been spied upon/); }); - it("checks if it can be spied upon", function() { + it('checks if it can be spied upon', function() { var scope = {}; function myFunc() { @@ -74,7 +78,11 @@ describe("SpyRegistry", function() { }); var spies = [], - spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}), + spyRegistry = new jasmineUnderTest.SpyRegistry({ + currentSpies: function() { + return spies; + } + }), subject = { spiedFunc: scope.myFunc }; expect(function() { @@ -86,35 +94,43 @@ describe("SpyRegistry", function() { }).not.toThrowError(/is not declared writable or has no setter/); }); - it("overrides the method on the object and returns the spy", function() { + it('overrides the method on the object and returns the spy', function() { var originalFunctionWasCalled = false, - spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}), - subject = { spiedFunc: function() { originalFunctionWasCalled = true; } }; + spyRegistry = new jasmineUnderTest.SpyRegistry({ + createSpy: createSpy + }), + subject = { + spiedFunc: function() { + originalFunctionWasCalled = true; + } + }; var spy = spyRegistry.spyOn(subject, 'spiedFunc'); expect(subject.spiedFunc).toEqual(spy); + subject.spiedFunc(); + expect(originalFunctionWasCalled).toBe(false); }); }); - describe("#spyOnProperty", function() { - it("checks for the existence of the object", function() { + describe('#spyOnProperty', function() { + it('checks for the existence of the object', function() { var spyRegistry = new jasmineUnderTest.SpyRegistry(); expect(function() { spyRegistry.spyOnProperty(void 0, 'pants'); }).toThrowError(/could not find an object/); }); - it("checks that a property name was passed", function() { + it('checks that a property name was passed', function() { var spyRegistry = new jasmineUnderTest.SpyRegistry(), subject = {}; - expect(function() { - spyRegistry.spyOnProperty(subject); - }).toThrowError(/No property name supplied/); + expect(function() { + spyRegistry.spyOnProperty(subject); + }).toThrowError(/No property name supplied/); }); - it("checks for the existence of the method", function() { + it('checks for the existence of the method', function() { var spyRegistry = new jasmineUnderTest.SpyRegistry(), subject = {}; @@ -123,12 +139,14 @@ describe("SpyRegistry", function() { }).toThrowError(/property does not exist/); }); - it("checks for the existence of access type", function() { + it('checks for the existence of access type', function() { var spyRegistry = new jasmineUnderTest.SpyRegistry(), subject = {}; Object.defineProperty(subject, 'pants', { - get: function() { return 1; }, + get: function() { + return 1; + }, configurable: true }); @@ -137,7 +155,7 @@ describe("SpyRegistry", function() { }).toThrowError(/does not have access type/); }); - it("checks if it can be spied upon", function() { + it('checks if it can be spied upon', function() { var subject = {}; Object.defineProperty(subject, 'myProp', { @@ -160,50 +178,64 @@ describe("SpyRegistry", function() { }).not.toThrowError(/is not declared configurable/); }); - it("overrides the property getter on the object and returns the spy", function() { - var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}), + it('overrides the property getter on the object and returns the spy', function() { + var spyRegistry = new jasmineUnderTest.SpyRegistry({ + createSpy: createSpy + }), subject = {}, returnValue = 1; Object.defineProperty(subject, 'spiedProperty', { - get: function() { return returnValue; }, + get: function() { + return returnValue; + }, configurable: true }); expect(subject.spiedProperty).toEqual(returnValue); var spy = spyRegistry.spyOnProperty(subject, 'spiedProperty'); - var getter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty').get; + var getter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty') + .get; expect(getter).toEqual(spy); expect(subject.spiedProperty).toBeUndefined(); }); - it("overrides the property setter on the object and returns the spy", function() { - var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}), + it('overrides the property setter on the object and returns the spy', function() { + var spyRegistry = new jasmineUnderTest.SpyRegistry({ + createSpy: createSpy + }), subject = {}, returnValue = 1; Object.defineProperty(subject, 'spiedProperty', { - get: function() { return returnValue; }, + get: function() { + return returnValue; + }, set: function() {}, configurable: true }); var spy = spyRegistry.spyOnProperty(subject, 'spiedProperty', 'set'); - var setter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty').set; + var setter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty') + .set; expect(subject.spiedProperty).toEqual(returnValue); expect(setter).toEqual(spy); }); - describe("when the property is already spied upon", function() { - it("throws an error if respy is not allowed", function() { - var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}), + describe('when the property is already spied upon', function() { + it('throws an error if respy is not allowed', function() { + var spyRegistry = new jasmineUnderTest.SpyRegistry({ + createSpy: createSpy + }), subject = {}; Object.defineProperty(subject, 'spiedProp', { - get: function() { return 1; }, + get: function() { + return 1; + }, configurable: true }); @@ -214,37 +246,49 @@ describe("SpyRegistry", function() { }).toThrowError(/spiedProp#get has already been spied upon/); }); - it("returns the original spy if respy is allowed", function() { - var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}), + it('returns the original spy if respy is allowed', function() { + var spyRegistry = new jasmineUnderTest.SpyRegistry({ + createSpy: createSpy + }), subject = {}; spyRegistry.allowRespy(true); Object.defineProperty(subject, 'spiedProp', { - get: function() { return 1; }, + get: function() { + return 1; + }, configurable: true }); var originalSpy = spyRegistry.spyOnProperty(subject, 'spiedProp'); - expect(spyRegistry.spyOnProperty(subject, 'spiedProp')).toBe(originalSpy); + expect(spyRegistry.spyOnProperty(subject, 'spiedProp')).toBe( + originalSpy + ); }); }); }); - describe("#spyOnAllFunctions", function() { - it("checks for the existence of the object", function() { + describe('#spyOnAllFunctions', function() { + it('checks for the existence of the object', function() { var spyRegistry = new jasmineUnderTest.SpyRegistry(); expect(function() { spyRegistry.spyOnAllFunctions(void 0); }).toThrowError(/spyOnAllFunctions could not find an object to spy upon/); }); - it("overrides all writable and configurable functions of the object and its parents", function() { - var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: function() { - return 'I am a spy'; - }}); - var createNoop = function() { return function() { /**/}; }; + it('overrides all writable and configurable functions of the object and its parents', function() { + var spyRegistry = new jasmineUnderTest.SpyRegistry({ + createSpy: function() { + return 'I am a spy'; + } + }); + var createNoop = function() { + return function() { + /**/ + }; + }; var noop1 = createNoop(); var noop2 = createNoop(); var noop3 = createNoop(); @@ -270,7 +314,7 @@ describe("SpyRegistry", function() { var _spied3 = noop3; Object.defineProperty(subject, 'spied3', { configurable: true, - set: function (val) { + set: function(val) { _spied3 = val; }, get: function() { @@ -293,7 +337,9 @@ describe("SpyRegistry", function() { }); Object.defineProperty(subject, 'notSpied4', { configurable: false, - set: function(val) { /**/ }, + set: function(val) { + /**/ + }, get: function() { return noop4; }, @@ -322,13 +368,15 @@ describe("SpyRegistry", function() { expect(spiedObject).toBe(subject); }); - it("overrides prototype methods on the object", function() { - var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: function() { - return 'I am a spy'; - }}); + it('overrides prototype methods on the object', function() { + var spyRegistry = new jasmineUnderTest.SpyRegistry({ + createSpy: function() { + return 'I am a spy'; + } + }); - var noop1 = function() { }; - var noop2 = function() { }; + var noop1 = function() {}; + var noop2 = function() {}; var MyClass = function() { this.spied1 = noop1; @@ -343,12 +391,14 @@ describe("SpyRegistry", function() { expect(MyClass.prototype.spied2).toBe(noop2); }); - it("does not override non-enumerable properties (like Object.prototype methods)", function() { - var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: function() { - return 'I am a spy'; - }}); + it('does not override non-enumerable properties (like Object.prototype methods)', function() { + var spyRegistry = new jasmineUnderTest.SpyRegistry({ + createSpy: function() { + return 'I am a spy'; + } + }); var subject = { - spied1: function() { } + spied1: function() {} }; spyRegistry.spyOnAllFunctions(subject); @@ -359,11 +409,13 @@ describe("SpyRegistry", function() { }); }); - describe("#clearSpies", function() { - it("restores the original functions on the spied-upon objects", function() { + describe('#clearSpies', function() { + it('restores the original functions on the spied-upon objects', function() { var spies = [], spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() { return spies; }, + currentSpies: function() { + return spies; + }, createSpy: createSpy }), originalFunction = function() {}, @@ -375,10 +427,12 @@ describe("SpyRegistry", function() { expect(subject.spiedFunc).toBe(originalFunction); }); - it("restores the original functions, even when that spy has been replace and re-spied upon", function() { + it('restores the original functions, even when that spy has been replace and re-spied upon', function() { var spies = [], spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() { return spies; }, + currentSpies: function() { + return spies; + }, createSpy: createSpy }), originalFunction = function() {}, @@ -400,11 +454,13 @@ describe("SpyRegistry", function() { it("does not add a property that the spied-upon object didn't originally have", function() { var spies = [], spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() { return spies; }, + currentSpies: function() { + return spies; + }, createSpy: createSpy }), originalFunction = function() {}, - subjectParent = {spiedFunc: originalFunction}; + subjectParent = { spiedFunc: originalFunction }; var subject = Object.create(subjectParent); @@ -417,14 +473,16 @@ describe("SpyRegistry", function() { expect(subject.spiedFunc).toBe(originalFunction); }); - it("restores the original function when it\'s inherited and cannot be deleted", function() { + it("restores the original function when it's inherited and cannot be deleted", function() { var spies = [], spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() { return spies; }, + currentSpies: function() { + return spies; + }, createSpy: createSpy }), originalFunction = function() {}, - subjectParent = {spiedFunc: originalFunction}; + subjectParent = { spiedFunc: originalFunction }; var subject = Object.create(subjectParent); @@ -440,15 +498,16 @@ describe("SpyRegistry", function() { expect(jasmineUnderTest.isSpy(subject.spiedFunc)).toBe(false); }); - it("restores window.onerror by overwriting, not deleting", function() { - function FakeWindow() { - } + it('restores window.onerror by overwriting, not deleting', function() { + function FakeWindow() {} FakeWindow.prototype.onerror = function() {}; var spies = [], global = new FakeWindow(), spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() { return spies; }, + currentSpies: function() { + return spies; + }, createSpy: createSpy, global: global }); @@ -460,50 +519,58 @@ describe("SpyRegistry", function() { }); }); - describe('spying on properties', function() { - it("restores the original properties on the spied-upon objects", function() { - var spies = [], - spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() { return spies; }, - createSpy: createSpy - }), - originalReturn = 1, - subject = {}; + describe('spying on properties', function() { + it('restores the original properties on the spied-upon objects', function() { + var spies = [], + spyRegistry = new jasmineUnderTest.SpyRegistry({ + currentSpies: function() { + return spies; + }, + createSpy: createSpy + }), + originalReturn = 1, + subject = {}; - Object.defineProperty(subject, 'spiedProp', { - get: function() { return originalReturn; }, - configurable: true - }); - - spyRegistry.spyOnProperty(subject, 'spiedProp'); - spyRegistry.clearSpies(); - - expect(subject.spiedProp).toBe(originalReturn); + Object.defineProperty(subject, 'spiedProp', { + get: function() { + return originalReturn; + }, + configurable: true }); - it("does not add a property that the spied-upon object didn't originally have", function() { - var spies = [], - spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() { return spies; }, - createSpy: createSpy - }), - originalReturn = 1, - subjectParent = {}; + spyRegistry.spyOnProperty(subject, 'spiedProp'); + spyRegistry.clearSpies(); - Object.defineProperty(subjectParent, 'spiedProp', { - get: function() { return originalReturn; }, - configurable: true - }); - - var subject = Object.create(subjectParent); - - expect(subject.hasOwnProperty('spiedProp')).toBe(false); - - spyRegistry.spyOnProperty(subject, 'spiedProp'); - spyRegistry.clearSpies(); - - expect(subject.hasOwnProperty('spiedProp')).toBe(false); - expect(subject.spiedProp).toBe(originalReturn); - }); + expect(subject.spiedProp).toBe(originalReturn); }); + + it("does not add a property that the spied-upon object didn't originally have", function() { + var spies = [], + spyRegistry = new jasmineUnderTest.SpyRegistry({ + currentSpies: function() { + return spies; + }, + createSpy: createSpy + }), + originalReturn = 1, + subjectParent = {}; + + Object.defineProperty(subjectParent, 'spiedProp', { + get: function() { + return originalReturn; + }, + configurable: true + }); + + var subject = Object.create(subjectParent); + + expect(subject.hasOwnProperty('spiedProp')).toBe(false); + + spyRegistry.spyOnProperty(subject, 'spiedProp'); + spyRegistry.clearSpies(); + + expect(subject.hasOwnProperty('spiedProp')).toBe(false); + expect(subject.spiedProp).toBe(originalReturn); + }); + }); }); diff --git a/spec/core/SpySpec.js b/spec/core/SpySpec.js index 04734e2f..fd7dc4e6 100644 --- a/spec/core/SpySpec.js +++ b/spec/core/SpySpec.js @@ -1,64 +1,78 @@ -describe('Spies', function () { +describe('Spies', function() { var env; beforeEach(function() { env = new jasmineUnderTest.Env(); }); - describe("createSpy", function() { + describe('createSpy', function() { var TestClass; beforeEach(function() { TestClass = function() {}; TestClass.prototype.someFunction = function() {}; - TestClass.prototype.someFunction.bob = "test"; + TestClass.prototype.someFunction.bob = 'test'; }); - it("preserves the properties of the spied function", function() { - var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction); + it('preserves the properties of the spied function', function() { + var spy = env.createSpy( + TestClass.prototype, + TestClass.prototype.someFunction + ); - expect(spy.bob).toEqual("test"); + expect(spy.bob).toEqual('test'); }); - it("should allow you to omit the name argument and only pass the originalFn argument", function() { + it('should allow you to omit the name argument and only pass the originalFn argument', function() { var fn = function test() {}; var spy = env.createSpy(fn); // IE doesn't do `.name` - if (fn.name === "test") { - expect(spy.and.identity).toEqual("test"); + if (fn.name === 'test') { + expect(spy.and.identity).toEqual('test'); } else { - expect(spy.and.identity).toEqual("unknown"); + expect(spy.and.identity).toEqual('unknown'); } - }) + }); - it("warns the user that we intend to overwrite an existing property", function() { - TestClass.prototype.someFunction.and = "turkey"; + it('warns the user that we intend to overwrite an existing property', function() { + TestClass.prototype.someFunction.and = 'turkey'; expect(function() { env.createSpy(TestClass.prototype, TestClass.prototype.someFunction); - }).toThrowError("Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon"); + }).toThrowError( + "Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon" + ); }); - it("adds a spyStrategy and callTracker to the spy", function() { - var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction); + it('adds a spyStrategy and callTracker to the spy', function() { + var spy = env.createSpy( + TestClass.prototype, + TestClass.prototype.someFunction + ); expect(spy.and).toEqual(jasmine.any(jasmineUnderTest.SpyStrategy)); expect(spy.calls).toEqual(jasmine.any(jasmineUnderTest.CallTracker)); }); - it("tracks the argument of calls", function () { - var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction); - var trackSpy = spyOn(spy.calls, "track"); + it('tracks the argument of calls', function() { + var spy = env.createSpy( + TestClass.prototype, + TestClass.prototype.someFunction + ); + var trackSpy = spyOn(spy.calls, 'track'); - spy("arg"); + spy('arg'); - expect(trackSpy.calls.mostRecent().args[0].args).toEqual(["arg"]); + expect(trackSpy.calls.mostRecent().args[0].args).toEqual(['arg']); }); - it("tracks the context of calls", function () { - var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction); - var trackSpy = spyOn(spy.calls, "track"); + it('tracks the context of calls', function() { + var spy = env.createSpy( + TestClass.prototype, + TestClass.prototype.someFunction + ); + var trackSpy = spyOn(spy.calls, 'track'); var contextObject = { spyMethod: spy }; contextObject.spyMethod(); @@ -66,39 +80,47 @@ describe('Spies', function () { expect(trackSpy.calls.mostRecent().args[0].object).toEqual(contextObject); }); - it("tracks the return value of calls", function () { - var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction); - var trackSpy = spyOn(spy.calls, "track"); + it('tracks the return value of calls', function() { + var spy = env.createSpy( + TestClass.prototype, + TestClass.prototype.someFunction + ); + var trackSpy = spyOn(spy.calls, 'track'); - spy.and.returnValue("return value"); + spy.and.returnValue('return value'); spy(); - expect(trackSpy.calls.mostRecent().args[0].returnValue).toEqual("return value"); + expect(trackSpy.calls.mostRecent().args[0].returnValue).toEqual( + 'return value' + ); }); - it("preserves arity of original function", function () { + it('preserves arity of original function', function() { var functions = [ - function nullary () {}, - function unary (arg) {}, - function binary (arg1, arg2) {}, - function ternary (arg1, arg2, arg3) {}, - function quaternary (arg1, arg2, arg3, arg4) {}, - function quinary (arg1, arg2, arg3, arg4, arg5) {}, - function senary (arg1, arg2, arg3, arg4, arg5, arg6) {} + function nullary() {}, + function unary(arg) {}, + function binary(arg1, arg2) {}, + function ternary(arg1, arg2, arg3) {}, + function quaternary(arg1, arg2, arg3, arg4) {}, + function quinary(arg1, arg2, arg3, arg4, arg5) {}, + function senary(arg1, arg2, arg3, arg4, arg5, arg6) {} ]; for (var arity = 0; arity < functions.length; arity++) { var someFunction = functions[arity], - spy = env.createSpy(someFunction.name, someFunction); + spy = env.createSpy(someFunction.name, someFunction); expect(spy.length).toEqual(arity); } }); }); - describe("createSpyObj", function() { - it("should create an object with spy methods and corresponding return values when you call jasmine.createSpyObj() with an object", function () { - var spyObj = env.createSpyObj('BaseName', {'method1': 42, 'method2': 'special sauce' }); + describe('createSpyObj', function() { + it('should create an object with spy methods and corresponding return values when you call jasmine.createSpyObj() with an object', function() { + var spyObj = env.createSpyObj('BaseName', { + method1: 42, + method2: 'special sauce' + }); expect(spyObj.method1()).toEqual(42); expect(spyObj.method1.and.identity).toEqual('BaseName.method1'); @@ -107,43 +129,54 @@ describe('Spies', function () { expect(spyObj.method2.and.identity).toEqual('BaseName.method2'); }); - - it("should create an object with a bunch of spy methods when you call jasmine.createSpyObj()", function() { + it('should create an object with a bunch of spy methods when you call jasmine.createSpyObj()', function() { var spyObj = env.createSpyObj('BaseName', ['method1', 'method2']); - expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function)}); + expect(spyObj).toEqual({ + method1: jasmine.any(Function), + method2: jasmine.any(Function) + }); expect(spyObj.method1.and.identity).toEqual('BaseName.method1'); expect(spyObj.method2.and.identity).toEqual('BaseName.method2'); }); - it("should allow you to omit the baseName", function() { + it('should allow you to omit the baseName', function() { var spyObj = env.createSpyObj(['method1', 'method2']); - expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function)}); + expect(spyObj).toEqual({ + method1: jasmine.any(Function), + method2: jasmine.any(Function) + }); expect(spyObj.method1.and.identity).toEqual('unknown.method1'); expect(spyObj.method2.and.identity).toEqual('unknown.method2'); }); - it("should throw if you do not pass an array or object argument", function() { + it('should throw if you do not pass an array or object argument', function() { expect(function() { env.createSpyObj('BaseName'); - }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); + }).toThrow( + 'createSpyObj requires a non-empty array or object of method names to create spies for' + ); }); - it("should throw if you pass an empty array argument", function() { + it('should throw if you pass an empty array argument', function() { expect(function() { env.createSpyObj('BaseName', []); - }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); + }).toThrow( + 'createSpyObj requires a non-empty array or object of method names to create spies for' + ); }); - it("should throw if you pass an empty object argument", function() { + it('should throw if you pass an empty object argument', function() { expect(function() { env.createSpyObj('BaseName', {}); - }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); + }).toThrow( + 'createSpyObj requires a non-empty array or object of method names to create spies for' + ); }); }); - it("can use different strategies for different arguments", function() { + it('can use different strategies for different arguments', function() { var spy = env.createSpy('foo'); spy.and.returnValue(42); spy.withArgs('baz', 'grault').and.returnValue(-1); @@ -155,7 +188,7 @@ describe('Spies', function () { expect(spy('baz', 'grault', 'waldo')).toEqual(42); }); - it("uses custom equality testers when selecting a strategy", function() { + it('uses custom equality testers when selecting a strategy', function() { var spy = env.createSpy('foo'); spy.and.returnValue(42); spy.withArgs(jasmineUnderTest.any(String)).and.returnValue(-1); @@ -164,7 +197,7 @@ describe('Spies', function () { expect(spy({})).toEqual(42); }); - it("can reconfigure an argument-specific strategy", function() { + it('can reconfigure an argument-specific strategy', function() { var spy = env.createSpy('foo'); spy.withArgs('foo').and.returnValue(42); spy.withArgs('foo').and.returnValue(17); @@ -176,14 +209,19 @@ describe('Spies', function () { jasmine.getEnv().requirePromises(); var spy = env.createSpy('foo').and.resolveWith(42); - spy().then(function(result) { - expect(result).toEqual(42); - done(); - }).catch(done.fail); + spy() + .then(function(result) { + expect(result).toEqual(42); + done(); + }) + .catch(done.fail); }); it('works with a custom Promise library', function() { - var customPromise = { resolve: jasmine.createSpy(), reject: jasmine.createSpy() }; + var customPromise = { + resolve: jasmine.createSpy(), + reject: jasmine.createSpy() + }; customPromise.resolve.and.returnValue('resolved'); env.configure({ Promise: customPromise }); @@ -193,8 +231,8 @@ describe('Spies', function () { }); }); - describe("when withArgs is used without a base strategy", function() { - it("uses the matching strategy", function() { + describe('when withArgs is used without a base strategy', function() { + it('uses the matching strategy', function() { var spy = env.createSpy('foo'); spy.withArgs('baz').and.returnValue(-1); @@ -205,7 +243,11 @@ describe('Spies', function () { var spy = env.createSpy('foo'); spy.withArgs('bar').and.returnValue(-1); - expect(function() { spy('baz', {qux: 42}); }).toThrowError('Spy \'foo\' received a call with arguments [ \'baz\', Object({ qux: 42 }) ] but all configured strategies specify other arguments.'); + expect(function() { + spy('baz', { qux: 42 }); + }).toThrowError( + "Spy 'foo' received a call with arguments [ 'baz', Object({ qux: 42 }) ] but all configured strategies specify other arguments." + ); }); }); }); diff --git a/spec/core/SpyStrategySpec.js b/spec/core/SpyStrategySpec.js index 709c268b..ae2679ac 100644 --- a/spec/core/SpyStrategySpec.js +++ b/spec/core/SpyStrategySpec.js @@ -1,20 +1,19 @@ -describe("SpyStrategy", function() { - - it("defaults its name to unknown", function() { +describe('SpyStrategy', function() { + it('defaults its name to unknown', function() { var spyStrategy = new jasmineUnderTest.SpyStrategy(); - expect(spyStrategy.identity).toEqual("unknown"); + expect(spyStrategy.identity).toEqual('unknown'); }); - it("takes a name", function() { - var spyStrategy = new jasmineUnderTest.SpyStrategy({name: "foo"}); + it('takes a name', function() { + var spyStrategy = new jasmineUnderTest.SpyStrategy({ name: 'foo' }); - expect(spyStrategy.identity).toEqual("foo"); + expect(spyStrategy.identity).toEqual('foo'); }); - it("stubs an original function, if provided", function() { - var originalFn = jasmine.createSpy("original"), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}); + it('stubs an original function, if provided', function() { + var originalFn = jasmine.createSpy('original'), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy.exec(); @@ -22,22 +21,22 @@ describe("SpyStrategy", function() { }); it("allows an original function to be called, passed through the params and returns it's value", function() { - var originalFn = jasmine.createSpy("original").and.returnValue(42), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}), - returnValue; + var originalFn = jasmine.createSpy('original').and.returnValue(42), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }), + returnValue; spyStrategy.callThrough(); - returnValue = spyStrategy.exec(null, ["foo"]); + returnValue = spyStrategy.exec(null, ['foo']); expect(originalFn).toHaveBeenCalled(); - expect(originalFn.calls.mostRecent().args).toEqual(["foo"]); + expect(originalFn.calls.mostRecent().args).toEqual(['foo']); expect(returnValue).toEqual(42); }); - it("can return a specified value when executed", function() { - var originalFn = jasmine.createSpy("original"), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}), - returnValue; + it('can return a specified value when executed', function() { + var originalFn = jasmine.createSpy('original'), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }), + returnValue; spyStrategy.returnValue(17); returnValue = spyStrategy.exec(); @@ -46,9 +45,9 @@ describe("SpyStrategy", function() { expect(returnValue).toEqual(17); }); - it("can return specified values in order specified when executed", function() { - var originalFn = jasmine.createSpy("original"), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}); + it('can return specified values in order specified when executed', function() { + var originalFn = jasmine.createSpy('original'), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy.returnValues('value1', 'value2', 'value3'); @@ -59,31 +58,35 @@ describe("SpyStrategy", function() { expect(originalFn).not.toHaveBeenCalled(); }); - it("allows an exception to be thrown when executed", function() { - var originalFn = jasmine.createSpy("original"), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}); + it('allows an exception to be thrown when executed', function() { + var originalFn = jasmine.createSpy('original'), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); - spyStrategy.throwError(new TypeError("bar")); + spyStrategy.throwError(new TypeError('bar')); - expect(function() { spyStrategy.exec(); }).toThrowError(TypeError, "bar"); + expect(function() { + spyStrategy.exec(); + }).toThrowError(TypeError, 'bar'); expect(originalFn).not.toHaveBeenCalled(); }); - it("allows a non-Error to be thrown, wrapping it into an exception when executed", function() { - var originalFn = jasmine.createSpy("original"), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}); + it('allows a non-Error to be thrown, wrapping it into an exception when executed', function() { + var originalFn = jasmine.createSpy('original'), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); - spyStrategy.throwError("bar"); + spyStrategy.throwError('bar'); - expect(function() { spyStrategy.exec(); }).toThrowError(Error, "bar"); + expect(function() { + spyStrategy.exec(); + }).toThrowError(Error, 'bar'); expect(originalFn).not.toHaveBeenCalled(); }); - it("allows a fake function to be called instead", function() { - var originalFn = jasmine.createSpy("original"), - fakeFn = jasmine.createSpy("fake").and.returnValue(67), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}), - returnValue; + it('allows a fake function to be called instead', function() { + var originalFn = jasmine.createSpy('original'), + fakeFn = jasmine.createSpy('fake').and.returnValue(67), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }), + returnValue; spyStrategy.callFake(fakeFn); returnValue = spyStrategy.exec(); @@ -92,92 +95,128 @@ describe("SpyStrategy", function() { expect(returnValue).toEqual(67); }); - it("allows a fake async function to be called instead", function(done) { + it('allows a fake async function to be called instead', function(done) { jasmine.getEnv().requireAsyncAwait(); - var originalFn = jasmine.createSpy("original"), - fakeFn = jasmine.createSpy("fake").and.callFake(eval("async () => { return 67; }")), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}), - returnValue; + var originalFn = jasmine.createSpy('original'), + fakeFn = jasmine + .createSpy('fake') + .and.callFake(eval('async () => { return 67; }')), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy.callFake(fakeFn); - spyStrategy.exec().then(function (returnValue) { - expect(originalFn).not.toHaveBeenCalled(); - expect(fakeFn).toHaveBeenCalled(); - expect(returnValue).toEqual(67); - done(); - }).catch(function (err) { - done.fail(err); - }) + spyStrategy + .exec() + .then(function(returnValue) { + expect(originalFn).not.toHaveBeenCalled(); + expect(fakeFn).toHaveBeenCalled(); + expect(returnValue).toEqual(67); + done(); + }) + .catch(function(err) { + done.fail(err); + }); }); - describe("#resolveWith", function() { - it("allows a resolved promise to be returned", function(done) { + describe('#resolveWith', function() { + it('allows a resolved promise to be returned', function(done) { jasmine.getEnv().requirePromises(); - var originalFn = jasmine.createSpy("original"), - getPromise = function() { return Promise; }, - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn, getPromise: getPromise}); + var originalFn = jasmine.createSpy('original'), + getPromise = function() { + return Promise; + }, + spyStrategy = new jasmineUnderTest.SpyStrategy({ + fn: originalFn, + getPromise: getPromise + }); spyStrategy.resolveWith(37); - spyStrategy.exec().then(function (returnValue) { - expect(returnValue).toEqual(37); - done(); - }).catch(done.fail); + spyStrategy + .exec() + .then(function(returnValue) { + expect(returnValue).toEqual(37); + done(); + }) + .catch(done.fail); }); - it("fails if promises are not available", function() { - var originalFn = jasmine.createSpy("original"), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}); + it('fails if promises are not available', function() { + var originalFn = jasmine.createSpy('original'), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); expect(function() { spyStrategy.resolveWith(37); - }).toThrowError('resolveWith requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`'); + }).toThrowError( + 'resolveWith requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`' + ); }); }); - describe("#rejectWith", function() { - it("allows a rejected promise to be returned", function(done) { + describe('#rejectWith', function() { + it('allows a rejected promise to be returned', function(done) { jasmine.getEnv().requirePromises(); - var originalFn = jasmine.createSpy("original"), - getPromise = function() { return Promise; }, - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn, getPromise: getPromise}); + var originalFn = jasmine.createSpy('original'), + getPromise = function() { + return Promise; + }, + spyStrategy = new jasmineUnderTest.SpyStrategy({ + fn: originalFn, + getPromise: getPromise + }); spyStrategy.rejectWith(new Error('oops')); - spyStrategy.exec().then(done.fail).catch(function (error) { - expect(error).toEqual(new Error('oops')); - done(); - }).catch(done.fail); + spyStrategy + .exec() + .then(done.fail) + .catch(function(error) { + expect(error).toEqual(new Error('oops')); + done(); + }) + .catch(done.fail); }); - it("allows a non-Error to be rejected, wrapping it in an exception when executed", function(done) { + it('allows a non-Error to be rejected, wrapping it in an exception when executed', function(done) { jasmine.getEnv().requirePromises(); - var originalFn = jasmine.createSpy("original"), - getPromise = function() { return Promise; }, - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn, getPromise: getPromise}); + var originalFn = jasmine.createSpy('original'), + getPromise = function() { + return Promise; + }, + spyStrategy = new jasmineUnderTest.SpyStrategy({ + fn: originalFn, + getPromise: getPromise + }); spyStrategy.rejectWith('oops'); - spyStrategy.exec().then(done.fail).catch(function (error) { - expect(error).toEqual(new Error('oops')); - done(); - }).catch(done.fail); + spyStrategy + .exec() + .then(done.fail) + .catch(function(error) { + expect(error).toEqual(new Error('oops')); + done(); + }) + .catch(done.fail); }); - it("fails if promises are not available", function() { - var originalFn = jasmine.createSpy("original"), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}); + it('fails if promises are not available', function() { + var originalFn = jasmine.createSpy('original'), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); expect(function() { spyStrategy.rejectWith(new Error('oops')); - }).toThrowError('rejectWith requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`'); + }).toThrowError( + 'rejectWith requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`' + ); }); }); - it("allows a custom strategy to be used", function() { - var plan = jasmine.createSpy('custom strategy') + it('allows a custom strategy to be used', function() { + var plan = jasmine + .createSpy('custom strategy') .and.returnValue('custom strategy result'), - customStrategy = jasmine.createSpy('custom strategy') + customStrategy = jasmine + .createSpy('custom strategy') .and.returnValue(plan), originalFn = jasmine.createSpy('original'), spyStrategy = new jasmineUnderTest.SpyStrategy({ @@ -189,8 +228,9 @@ describe("SpyStrategy", function() { spyStrategy.doSomething(1, 2, 3); expect(customStrategy).toHaveBeenCalledWith(1, 2, 3); - expect(spyStrategy.exec(null, ['some', 'args'])) - .toEqual('custom strategy result'); + expect(spyStrategy.exec(null, ['some', 'args'])).toEqual( + 'custom strategy result' + ); expect(plan).toHaveBeenCalledWith('some', 'args'); }); @@ -199,46 +239,49 @@ describe("SpyStrategy", function() { spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn, customStrategies: { - doSomething: function() { return 'not a function' } + doSomething: function() { + return 'not a function'; + } } }); - expect(function() { spyStrategy.doSomething(1, 2, 3) }).toThrowError('Spy strategy must return a function'); + expect(function() { + spyStrategy.doSomething(1, 2, 3); + }).toThrowError('Spy strategy must return a function'); }); - it("does not allow custom strategies to overwrite existing methods", function() { + it('does not allow custom strategies to overwrite existing methods', function() { var spyStrategy = new jasmineUnderTest.SpyStrategy({ - fn: function() {}, - customStrategies: { - exec: function() {} - } - }); + fn: function() {}, + customStrategies: { + exec: function() {} + } + }); expect(spyStrategy.exec).toBe(jasmineUnderTest.SpyStrategy.prototype.exec); }); it('throws an error when a non-function is passed to callFake strategy', function() { var originalFn = jasmine.createSpy('original'), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}), - invalidFakes = [5, 'foo', {}, true, false, null, void 0, new Date(), /.*/]; + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); spyOn(jasmineUnderTest, 'isFunction_').and.returnValue(false); spyOn(jasmineUnderTest, 'isAsyncFunction_').and.returnValue(false); - expect(function () { + expect(function() { spyStrategy.callFake(function() {}); }).toThrowError(/^Argument passed to callFake should be a function, got/); - expect(function () { + expect(function() { spyStrategy.callFake(function() {}); }).toThrowError(/^Argument passed to callFake should be a function, got/); }); - it("allows a return to plan stubbing after another strategy", function() { - var originalFn = jasmine.createSpy("original"), - fakeFn = jasmine.createSpy("fake").and.returnValue(67), - spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}), - returnValue; + it('allows a return to plan stubbing after another strategy', function() { + var originalFn = jasmine.createSpy('original'), + fakeFn = jasmine.createSpy('fake').and.returnValue(67), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }), + returnValue; spyStrategy.callFake(fakeFn); returnValue = spyStrategy.exec(); @@ -252,10 +295,10 @@ describe("SpyStrategy", function() { expect(returnValue).toEqual(void 0); }); - it("returns the spy after changing the strategy", function(){ + it('returns the spy after changing the strategy', function() { var spy = {}, - spyFn = jasmine.createSpy('spyFn').and.returnValue(spy), - spyStrategy = new jasmineUnderTest.SpyStrategy({getSpy: spyFn}); + spyFn = jasmine.createSpy('spyFn').and.returnValue(spy), + spyStrategy = new jasmineUnderTest.SpyStrategy({ getSpy: spyFn }); expect(spyStrategy.callThrough()).toBe(spy); expect(spyStrategy.returnValue()).toBe(spy); diff --git a/spec/core/StackTraceSpec.js b/spec/core/StackTraceSpec.js index dd8023f4..9cbffe33 100644 --- a/spec/core/StackTraceSpec.js +++ b/spec/core/StackTraceSpec.js @@ -1,5 +1,5 @@ -describe("StackTrace", function() { - it("understands Chrome/IE/Edge style traces", function() { +describe('StackTrace', function() { + it('understands Chrome/IE/Edge style traces', function() { var error = { message: 'nope', stack: @@ -14,13 +14,15 @@ describe("StackTrace", function() { expect(result.style).toEqual('v8'); expect(result.frames).toEqual([ { - raw: ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)', + raw: + ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)', func: 'UserContext.', file: 'http://localhost:8888/__spec__/core/UtilSpec.js', line: 115 }, { - raw: ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)', + raw: + ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)', func: 'QueueRunner.run', file: 'http://localhost:8888/__jasmine__/jasmine.js', line: 4320 @@ -28,7 +30,7 @@ describe("StackTrace", function() { ]); }); - it("understands Chrome/IE/Edge style traces with multiline messages", function() { + it('understands Chrome/IE/Edge style traces with multiline messages', function() { var error = { message: 'line 1\nline 2', stack: @@ -40,14 +42,16 @@ describe("StackTrace", function() { var result = new jasmineUnderTest.StackTrace(error); expect(result.message).toEqual('Error: line 1\nline 2'); - var rawFrames = result.frames.map(function(f) { return f.raw; }); + var rawFrames = result.frames.map(function(f) { + return f.raw; + }); expect(rawFrames).toEqual([ ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)', - ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)', + ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)' ]); }); - it("understands Node style traces", function() { + it('understands Node style traces', function() { var error = { message: 'nope', stack: @@ -69,13 +73,15 @@ describe("StackTrace", function() { line: 4255 }, { - raw: ' at QueueRunner.complete [as onComplete] (/somewhere/jasmine/lib/jasmine-core/jasmine.js:579:9)', + raw: + ' at QueueRunner.complete [as onComplete] (/somewhere/jasmine/lib/jasmine-core/jasmine.js:579:9)', func: 'QueueRunner.complete [as onComplete]', file: '/somewhere/jasmine/lib/jasmine-core/jasmine.js', line: 579 }, { - raw: ' at Immediate. (/somewhere/jasmine/lib/jasmine-core/jasmine.js:4314:12)', + raw: + ' at Immediate. (/somewhere/jasmine/lib/jasmine-core/jasmine.js:4314:12)', func: 'Immediate.', file: '/somewhere/jasmine/lib/jasmine-core/jasmine.js', line: 4314 @@ -89,7 +95,7 @@ describe("StackTrace", function() { ]); }); - it("understands Safari/Firefox/Phantom-OS X style traces", function() { + it('understands Safari/Firefox/Phantom-OS X style traces', function() { var error = { message: 'nope', stack: @@ -116,22 +122,20 @@ describe("StackTrace", function() { ]); }); - it("does not mistake gibberish for Safari/Firefox/Phantom-OS X style traces", function() { + it('does not mistake gibberish for Safari/Firefox/Phantom-OS X style traces', function() { var error = { message: 'nope', stack: 'randomcharsnotincludingwhitespace' }; var result = new jasmineUnderTest.StackTrace(error); expect(result.style).toBeNull(); - expect(result.frames).toEqual([ - { raw: error.stack } - ]); + expect(result.frames).toEqual([{ raw: error.stack }]); }); - it("understands Phantom-Linux style traces", function() { + it('understands Phantom-Linux style traces', function() { var error = { message: 'nope', - stack: + stack: ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' + ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)' }; @@ -142,13 +146,15 @@ describe("StackTrace", function() { expect(result.style).toEqual('v8'); expect(result.frames).toEqual([ { - raw: ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)', + raw: + ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)', func: 'UserContext.', file: 'http://localhost:8888/__spec__/core/UtilSpec.js', line: 115 }, { - raw: ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)', + raw: + ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)', func: 'QueueRunner.run', file: 'http://localhost:8888/__jasmine__/jasmine.js', line: 4320 @@ -156,7 +162,7 @@ describe("StackTrace", function() { ]); }); - it("ignores blank lines", function() { + it('ignores blank lines', function() { var error = { message: 'nope', stack: @@ -167,7 +173,8 @@ describe("StackTrace", function() { expect(result.frames).toEqual([ { - raw: ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)', + raw: + ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)', func: 'UserContext.', file: 'http://localhost:8888/__spec__/core/UtilSpec.js', line: 115 @@ -188,7 +195,8 @@ describe("StackTrace", function() { expect(result.style).toEqual('v8'); expect(result.frames).toEqual([ { - raw: ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)', + raw: + ' at UserContext. (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)', func: 'UserContext.', file: 'http://localhost:8888/__spec__/core/UtilSpec.js', line: 115 @@ -197,7 +205,8 @@ describe("StackTrace", function() { raw: ' but this is quite unexpected' }, { - raw: ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)', + raw: + ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)', func: 'QueueRunner.run', file: 'http://localhost:8888/__jasmine__/jasmine.js', line: 4320 diff --git a/spec/core/SuiteSpec.js b/spec/core/SuiteSpec.js index 1739259e..8470bad7 100644 --- a/spec/core/SuiteSpec.js +++ b/spec/core/SuiteSpec.js @@ -1,47 +1,46 @@ -describe("Suite", function() { - - it("keeps its id", function() { +describe('Suite', function() { + it('keeps its id', function() { var env = new jasmineUnderTest.Env(), suite = new jasmineUnderTest.Suite({ env: env, id: 456, - description: "I am a suite" + description: 'I am a suite' }); expect(suite.id).toEqual(456); }); - it("returns blank full name for top level suite", function() { + it('returns blank full name for top level suite', function() { var env = new jasmineUnderTest.Env(), suite = new jasmineUnderTest.Suite({ env: env, - description: "I am a suite" + description: 'I am a suite' }); - expect(suite.getFullName()).toEqual(""); + expect(suite.getFullName()).toEqual(''); }); - it("returns its full name when it has parent suites", function() { + it('returns its full name when it has parent suites', function() { var env = new jasmineUnderTest.Env(), parentSuite = new jasmineUnderTest.Suite({ env: env, - description: "I am a parent suite", + description: 'I am a parent suite', parentSuite: jasmine.createSpy('pretend top level suite') }), suite = new jasmineUnderTest.Suite({ env: env, - description: "I am a suite", + description: 'I am a suite', parentSuite: parentSuite }); - expect(suite.getFullName()).toEqual("I am a parent suite I am a suite"); + expect(suite.getFullName()).toEqual('I am a parent suite I am a suite'); }); - it("adds before functions in order of needed execution", function() { + it('adds before functions in order of needed execution', function() { var env = new jasmineUnderTest.Env(), suite = new jasmineUnderTest.Suite({ env: env, - description: "I am a suite" + description: 'I am a suite' }), outerBefore = jasmine.createSpy('outerBeforeEach'), innerBefore = jasmine.createSpy('insideBeforeEach'); @@ -52,11 +51,11 @@ describe("Suite", function() { expect(suite.beforeFns).toEqual([innerBefore, outerBefore]); }); - it("adds after functions in order of needed execution", function() { + it('adds after functions in order of needed execution', function() { var env = new jasmineUnderTest.Env(), suite = new jasmineUnderTest.Suite({ env: env, - description: "I am a suite" + description: 'I am a suite' }), outerAfter = jasmine.createSpy('outerAfterEach'), innerAfter = jasmine.createSpy('insideAfterEach'); @@ -69,29 +68,33 @@ describe("Suite", function() { it('has a status of failed if any expectations have failed', function() { var suite = new jasmineUnderTest.Suite({ - expectationResultFactory: function() { return 'hi'; } + expectationResultFactory: function() { + return 'hi'; + } }); suite.addExpectationResult(false); expect(suite.status()).toBe('failed'); }); - it("retrieves a result with updated status", function() { + it('retrieves a result with updated status', function() { var suite = new jasmineUnderTest.Suite({}); expect(suite.getResult().status).toBe('passed'); }); - it("retrieves a result with pending status", function() { + it('retrieves a result with pending status', function() { var suite = new jasmineUnderTest.Suite({}); suite.pend(); expect(suite.getResult().status).toBe('pending'); }); - it("throws an ExpectationFailed when receiving a failed expectation when throwOnExpectationFailure is set", function() { + it('throws an ExpectationFailed when receiving a failed expectation when throwOnExpectationFailure is set', function() { var suite = new jasmineUnderTest.Suite({ - expectationResultFactory: function(data) { return data; }, + expectationResultFactory: function(data) { + return data; + }, throwOnExpectationFailure: true }); @@ -103,7 +106,7 @@ describe("Suite", function() { expect(suite.result.failedExpectations).toEqual(['failed']); }); - it("does not add an additional failure when an expectation fails", function(){ + it('does not add an additional failure when an expectation fails', function() { var suite = new jasmineUnderTest.Suite({}); suite.onException(new jasmineUnderTest.errors.ExpectationFailed()); @@ -111,17 +114,17 @@ describe("Suite", function() { expect(suite.getResult().failedExpectations).toEqual([]); }); - it("calls timer to compute duration", function(){ - var env = new jasmineUnderTest.Env(), + it('calls timer to compute duration', function() { + var env = new jasmineUnderTest.Env(), suite = new jasmineUnderTest.Suite({ env: env, id: 456, - description: "I am a suite", - timer: jasmine.createSpyObj('timer', {'start': null, elapsed: 77000}), + description: 'I am a suite', + timer: jasmine.createSpyObj('timer', { start: null, elapsed: 77000 }) }); - suite.startTimer(); - suite.endTimer(); - expect(suite.getResult().duration).toEqual(77000); + suite.startTimer(); + suite.endTimer(); + expect(suite.getResult().duration).toEqual(77000); }); describe('#sharedUserContext', function() { @@ -130,7 +133,9 @@ describe("Suite", function() { }); it('returns a UserContext', function() { - expect(this.suite.sharedUserContext().constructor).toBe(jasmineUnderTest.UserContext); + expect(this.suite.sharedUserContext().constructor).toBe( + jasmineUnderTest.UserContext + ); }); }); }); diff --git a/spec/core/TimerSpec.js b/spec/core/TimerSpec.js index 96d8352a..f733f0d9 100644 --- a/spec/core/TimerSpec.js +++ b/spec/core/TimerSpec.js @@ -1,7 +1,7 @@ -describe("Timer", function() { - it("reports the time elapsed", function() { +describe('Timer', function() { + it('reports the time elapsed', function() { var fakeNow = jasmine.createSpy('fake Date.now'), - timer = new jasmineUnderTest.Timer({now: fakeNow}); + timer = new jasmineUnderTest.Timer({ now: fakeNow }); fakeNow.and.returnValue(100); timer.start(); @@ -11,7 +11,7 @@ describe("Timer", function() { expect(timer.elapsed()).toEqual(100); }); - describe("when date is stubbed, perhaps by other testing helpers", function() { + describe('when date is stubbed, perhaps by other testing helpers', function() { var origDate = Date; beforeEach(function() { Date = jasmine.createSpy('date spy'); @@ -21,7 +21,7 @@ describe("Timer", function() { Date = origDate; }); - it("does not throw even though Date was taken away", function() { + it('does not throw even though Date was taken away', function() { var timer = new jasmineUnderTest.Timer(); expect(timer.start).not.toThrow(); diff --git a/spec/core/TreeProcessorSpec.js b/spec/core/TreeProcessorSpec.js index 2e8a9ca8..18f4267f 100644 --- a/spec/core/TreeProcessorSpec.js +++ b/spec/core/TreeProcessorSpec.js @@ -1,5 +1,6 @@ -describe("TreeProcessor", function() { - var nodeNumber = 0, leafNumber = 0; +describe('TreeProcessor', function() { + var nodeNumber = 0, + leafNumber = 0; function Node(attrs) { attrs = attrs || {}; @@ -15,7 +16,7 @@ describe("TreeProcessor", function() { this.getResult = jasmine.createSpy(this.id + '#execute'); this.beforeAllFns = attrs.beforeAllFns || []; this.afterAllFns = attrs.afterAllFns || []; - this.cleanupBeforeAfter = function() { }; + this.cleanupBeforeAfter = function() {}; } function Leaf(attrs) { @@ -25,10 +26,13 @@ describe("TreeProcessor", function() { this.execute = jasmine.createSpy(this.id + '#execute'); } - it("processes a single leaf", function() { + it('processes a single leaf', function() { var leaf = new Leaf(), - processor = new jasmineUnderTest.TreeProcessor({ tree: leaf, runnableIds: [leaf.id] }), - result = processor.processTree(); + processor = new jasmineUnderTest.TreeProcessor({ + tree: leaf, + runnableIds: [leaf.id] + }), + result = processor.processTree(); expect(result.valid).toBe(true); @@ -39,10 +43,13 @@ describe("TreeProcessor", function() { }); }); - it("processes a single pending leaf", function() { + it('processes a single pending leaf', function() { var leaf = new Leaf({ markedPending: true }), - processor = new jasmineUnderTest.TreeProcessor({ tree: leaf, runnableIds: [leaf.id] }), - result = processor.processTree(); + processor = new jasmineUnderTest.TreeProcessor({ + tree: leaf, + runnableIds: [leaf.id] + }), + result = processor.processTree(); expect(result.valid).toBe(true); @@ -53,10 +60,13 @@ describe("TreeProcessor", function() { }); }); - it("processes a single non-specified leaf", function() { + it('processes a single non-specified leaf', function() { var leaf = new Leaf(), - processor = new jasmineUnderTest.TreeProcessor({ tree: leaf, runnableIds: [] }), - result = processor.processTree(); + processor = new jasmineUnderTest.TreeProcessor({ + tree: leaf, + runnableIds: [] + }), + result = processor.processTree(); expect(result.valid).toBe(true); @@ -67,14 +77,16 @@ describe("TreeProcessor", function() { }); }); - it("processes a single excluded leaf", function() { + it('processes a single excluded leaf', function() { var leaf = new Leaf(), - processor = new jasmineUnderTest.TreeProcessor({ - tree: leaf, - runnableIds: [leaf.id], - excludeNode: function(node) { return true; } - }), - result = processor.processTree(); + processor = new jasmineUnderTest.TreeProcessor({ + tree: leaf, + runnableIds: [leaf.id], + excludeNode: function(node) { + return true; + } + }), + result = processor.processTree(); expect(result.valid).toBe(true); @@ -85,11 +97,14 @@ describe("TreeProcessor", function() { }); }); - it("processes a tree with a single leaf with the root specified", function() { + it('processes a tree with a single leaf with the root specified', function() { var leaf = new Leaf(), - parent = new Node({ children: [leaf] }), - processor = new jasmineUnderTest.TreeProcessor({ tree: parent, runnableIds: [parent.id] }), - result = processor.processTree(); + parent = new Node({ children: [leaf] }), + processor = new jasmineUnderTest.TreeProcessor({ + tree: parent, + runnableIds: [parent.id] + }), + result = processor.processTree(); expect(result.valid).toBe(true); @@ -106,11 +121,14 @@ describe("TreeProcessor", function() { }); }); - it("processes a tree with a single pending leaf, with the root specified", function() { + it('processes a tree with a single pending leaf, with the root specified', function() { var leaf = new Leaf({ markedPending: true }), - parent = new Node({ children: [leaf] }), - processor = new jasmineUnderTest.TreeProcessor({ tree: parent, runnableIds: [parent.id] }), - result = processor.processTree(); + parent = new Node({ children: [leaf] }), + processor = new jasmineUnderTest.TreeProcessor({ + tree: parent, + runnableIds: [parent.id] + }), + result = processor.processTree(); expect(result.valid).toBe(true); @@ -127,17 +145,26 @@ describe("TreeProcessor", function() { }); }); - it("processes a complicated tree with the root specified", function() { + it('processes a complicated tree with the root specified', function() { var pendingLeaf = new Leaf({ markedPending: true }), - executableLeaf = new Leaf({ markedPending: false }), - parent = new Node({ children: [pendingLeaf, executableLeaf] }), - childless = new Node(), - childOfPending = new Leaf({ markedPending: true }), - pendingNode = new Node({ markedPending: true, children: [childOfPending] }), - parentOfPendings = new Node({ markedPending: false, children: [childless, pendingNode] }), - root = new Node({ children: [parent, parentOfPendings] }), - processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [root.id] }), - result = processor.processTree(); + executableLeaf = new Leaf({ markedPending: false }), + parent = new Node({ children: [pendingLeaf, executableLeaf] }), + childless = new Node(), + childOfPending = new Leaf({ markedPending: true }), + pendingNode = new Node({ + markedPending: true, + children: [childOfPending] + }), + parentOfPendings = new Node({ + markedPending: false, + children: [childless, pendingNode] + }), + root = new Node({ children: [parent, parentOfPendings] }), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [root.id] + }), + result = processor.processTree(); expect(result.valid).toBe(true); @@ -190,58 +217,73 @@ describe("TreeProcessor", function() { }); }); - it("marks the run order invalid if it would re-enter a node that does not allow re-entry", function() { + it('marks the run order invalid if it would re-enter a node that does not allow re-entry', function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - leaf3 = new Leaf(), - reentered = new Node({ noReenter: true, children: [leaf1, leaf2] }), - root = new Node({ children: [reentered, leaf3] }), - processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [leaf1.id, leaf3.id, leaf2.id] }), - result = processor.processTree(); + leaf2 = new Leaf(), + leaf3 = new Leaf(), + reentered = new Node({ noReenter: true, children: [leaf1, leaf2] }), + root = new Node({ children: [reentered, leaf3] }), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [leaf1.id, leaf3.id, leaf2.id] + }), + result = processor.processTree(); expect(result).toEqual({ valid: false }); }); - it("marks the run order valid if a node being re-entered allows re-entry", function() { + it('marks the run order valid if a node being re-entered allows re-entry', function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - leaf3 = new Leaf(), - reentered = new Node({ children: [leaf1, leaf2] }), - root = new Node({ children: [reentered, leaf3] }), - processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [leaf1.id, leaf3.id, leaf2.id] }), - result = processor.processTree(); + leaf2 = new Leaf(), + leaf3 = new Leaf(), + reentered = new Node({ children: [leaf1, leaf2] }), + root = new Node({ children: [reentered, leaf3] }), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [leaf1.id, leaf3.id, leaf2.id] + }), + result = processor.processTree(); expect(result.valid).toBe(true); }); it("marks the run order valid if a node which can't be re-entered is only entered once", function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - leaf3 = new Leaf(), - noReentry = new Node({ noReenter: true }), - root = new Node({ children: [noReentry] }), - processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [leaf2.id, leaf1.id, leaf3.id] }), - result = processor.processTree(); + leaf2 = new Leaf(), + leaf3 = new Leaf(), + noReentry = new Node({ noReenter: true }), + root = new Node({ children: [noReentry] }), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [leaf2.id, leaf1.id, leaf3.id] + }), + result = processor.processTree(); expect(result.valid).toBe(true); }); it("marks the run order valid if a node which can't be re-entered is run directly", function() { - var leaf1 = new Leaf(), - noReentry = new Node({ noReenter: true }), - root = new Node({ children: [noReentry] }), - processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [root.id] }), - result = processor.processTree(); + var noReentry = new Node({ noReenter: true }), + root = new Node({ children: [noReentry] }), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [root.id] + }), + result = processor.processTree(); expect(result.valid).toBe(true); }); - it("runs a single leaf", function() { + it('runs a single leaf', function() { var leaf = new Leaf(), - node = new Node({ children: [leaf], userContext: { root: 'context' } }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ tree: node, runnableIds: [leaf.id], queueRunnerFactory: queueRunner }), - treeComplete = jasmine.createSpy('treeComplete'); + node = new Node({ children: [leaf], userContext: { root: 'context' } }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: node, + runnableIds: [leaf.id], + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'); processor.execute(treeComplete); @@ -257,21 +299,21 @@ describe("TreeProcessor", function() { expect(leaf.execute).toHaveBeenCalledWith('foo', false); }); - it("runs a node with no children", function() { + it('runs a node with no children', function() { var node = new Node({ userContext: { node: 'context' } }), - root = new Node({ children: [node], userContext: { root: 'context' } }), - nodeStart = jasmine.createSpy('nodeStart'), - nodeComplete = jasmine.createSpy('nodeComplete'), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [node.id], - nodeStart: nodeStart, - nodeComplete: nodeComplete, - queueRunnerFactory: queueRunner - }), - treeComplete = jasmine.createSpy('treeComplete'), - nodeDone = jasmine.createSpy('nodeDone'); + root = new Node({ children: [node], userContext: { root: 'context' } }), + nodeStart = jasmine.createSpy('nodeStart'), + nodeComplete = jasmine.createSpy('nodeComplete'), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [node.id], + nodeStart: nodeStart, + nodeComplete: nodeComplete, + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'), + nodeDone = jasmine.createSpy('nodeDone'); processor.execute(treeComplete); @@ -297,22 +339,26 @@ describe("TreeProcessor", function() { node.getResult.and.returnValue({ my: 'result' }); queueRunner.calls.mostRecent().args[0].onComplete(); - expect(nodeComplete).toHaveBeenCalledWith(node, { my: 'result' }, jasmine.any(Function)); + expect(nodeComplete).toHaveBeenCalledWith( + node, + { my: 'result' }, + jasmine.any(Function) + ); }); - it("runs a node with children", function() { + it('runs a node with children', function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - node = new Node({ children: [leaf1, leaf2] }), - root = new Node({ children: [node] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [node.id], - queueRunnerFactory: queueRunner - }), - treeComplete = jasmine.createSpy('treeComplete'), - nodeDone = jasmine.createSpy('nodeDone'); + leaf2 = new Leaf(), + node = new Node({ children: [leaf1, leaf2] }), + root = new Node({ children: [node] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [node.id], + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'), + nodeDone = jasmine.createSpy('nodeDone'); processor.execute(treeComplete); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -328,20 +374,20 @@ describe("TreeProcessor", function() { expect(leaf2.execute).toHaveBeenCalledWith('bar', false); }); - it("cascades errors up the tree", function() { + it('cascades errors up the tree', function() { var leaf = new Leaf(), - node = new Node({ children: [leaf] }), - root = new Node({ children: [node] }), - queueRunner = jasmine.createSpy('queueRunner'), - nodeComplete = jasmine.createSpy('nodeComplete'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [node.id], - nodeComplete: nodeComplete, - queueRunnerFactory: queueRunner - }), - treeComplete = jasmine.createSpy('treeComplete'), - nodeDone = jasmine.createSpy('nodeDone'); + node = new Node({ children: [leaf] }), + root = new Node({ children: [node] }), + queueRunner = jasmine.createSpy('queueRunner'), + nodeComplete = jasmine.createSpy('nodeComplete'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [node.id], + nodeComplete: nodeComplete, + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'), + nodeDone = jasmine.createSpy('nodeDone'); processor.execute(treeComplete); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -359,22 +405,22 @@ describe("TreeProcessor", function() { expect(nodeDone).toHaveBeenCalledWith('things'); }); - it("runs an excluded node with leaf", function() { + it('runs an excluded node with leaf', function() { var leaf1 = new Leaf(), - node = new Node({ children: [leaf1] }), - root = new Node({ children: [node] }), - queueRunner = jasmine.createSpy('queueRunner'), - nodeStart = jasmine.createSpy('nodeStart'), - nodeComplete = jasmine.createSpy('nodeComplete'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [], - queueRunnerFactory: queueRunner, - nodeStart: nodeStart, - nodeComplete: nodeComplete - }), - treeComplete = jasmine.createSpy('treeComplete'), - nodeDone = jasmine.createSpy('nodeDone'); + node = new Node({ children: [leaf1] }), + root = new Node({ children: [node] }), + queueRunner = jasmine.createSpy('queueRunner'), + nodeStart = jasmine.createSpy('nodeStart'), + nodeComplete = jasmine.createSpy('nodeComplete'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [], + queueRunnerFactory: queueRunner, + nodeStart: nodeStart, + nodeComplete: nodeComplete + }), + treeComplete = jasmine.createSpy('treeComplete'), + nodeDone = jasmine.createSpy('nodeDone'); processor.execute(treeComplete); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -392,24 +438,28 @@ describe("TreeProcessor", function() { node.getResult.and.returnValue({ im: 'disabled' }); queueRunner.calls.mostRecent().args[0].onComplete(); - expect(nodeComplete).toHaveBeenCalledWith(node, { im: 'disabled' }, jasmine.any(Function)); + expect(nodeComplete).toHaveBeenCalledWith( + node, + { im: 'disabled' }, + jasmine.any(Function) + ); }); - it("runs beforeAlls for a node with children", function() { + it('runs beforeAlls for a node with children', function() { var leaf = new Leaf(), - node = new Node({ - children: [leaf], - beforeAllFns: ['beforeAll1', 'beforeAll2'] - }), - root = new Node({ children: [node] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [node.id], - queueRunnerFactory: queueRunner - }), - treeComplete = jasmine.createSpy('treeComplete'), - nodeDone = jasmine.createSpy('nodeDone'); + node = new Node({ + children: [leaf], + beforeAllFns: ['beforeAll1', 'beforeAll2'] + }), + root = new Node({ children: [node] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [node.id], + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'), + nodeDone = jasmine.createSpy('nodeDone'); processor.execute(treeComplete); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -417,24 +467,29 @@ describe("TreeProcessor", function() { queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; - expect(queueableFns).toEqual([{ fn: jasmine.any(Function) }, 'beforeAll1', 'beforeAll2', { fn: jasmine.any(Function) }]); + expect(queueableFns).toEqual([ + { fn: jasmine.any(Function) }, + 'beforeAll1', + 'beforeAll2', + { fn: jasmine.any(Function) } + ]); }); - it("runs afterAlls for a node with children", function() { + it('runs afterAlls for a node with children', function() { var leaf = new Leaf(), - node = new Node({ - children: [leaf], - afterAllFns: ['afterAll1', 'afterAll2'] - }), - root = new Node({ children: [node] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [node.id], - queueRunnerFactory: queueRunner - }), - treeComplete = jasmine.createSpy('treeComplete'), - nodeDone = jasmine.createSpy('nodeDone'); + node = new Node({ + children: [leaf], + afterAllFns: ['afterAll1', 'afterAll2'] + }), + root = new Node({ children: [node] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [node.id], + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'), + nodeDone = jasmine.createSpy('nodeDone'); processor.execute(treeComplete); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -442,23 +497,28 @@ describe("TreeProcessor", function() { queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; - expect(queueableFns).toEqual([{ fn: jasmine.any(Function) }, { fn: jasmine.any(Function) }, 'afterAll1', 'afterAll2']); + expect(queueableFns).toEqual([ + { fn: jasmine.any(Function) }, + { fn: jasmine.any(Function) }, + 'afterAll1', + 'afterAll2' + ]); }); - it("does not run beforeAlls or afterAlls for a node with no children", function() { + it('does not run beforeAlls or afterAlls for a node with no children', function() { var node = new Node({ - beforeAllFns: ['before'], - afterAllFns: ['after'] - }), - root = new Node({ children: [node] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [node.id], - queueRunnerFactory: queueRunner - }), - treeComplete = jasmine.createSpy('treeComplete'), - nodeDone = jasmine.createSpy('nodeDone'); + beforeAllFns: ['before'], + afterAllFns: ['after'] + }), + root = new Node({ children: [node] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [node.id], + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'), + nodeDone = jasmine.createSpy('nodeDone'); processor.execute(treeComplete); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -466,26 +526,26 @@ describe("TreeProcessor", function() { queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; - expect(queueableFns).toEqual([{fn: jasmine.any(Function)}]); + expect(queueableFns).toEqual([{ fn: jasmine.any(Function) }]); }); - it("does not run beforeAlls or afterAlls for a node with only pending children", function() { + it('does not run beforeAlls or afterAlls for a node with only pending children', function() { var leaf = new Leaf({ markedPending: true }), - node = new Node({ - children: [leaf], - beforeAllFns: ['before'], - afterAllFns: ['after'], - markedPending: false - }), - root = new Node({ children: [node] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [node.id], - queueRunnerFactory: queueRunner - }), - treeComplete = jasmine.createSpy('treeComplete'), - nodeDone = jasmine.createSpy('nodeDone'); + node = new Node({ + children: [leaf], + beforeAllFns: ['before'], + afterAllFns: ['after'], + markedPending: false + }), + root = new Node({ children: [node] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [node.id], + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'), + nodeDone = jasmine.createSpy('nodeDone'); processor.execute(treeComplete); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -493,20 +553,23 @@ describe("TreeProcessor", function() { queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; - expect(queueableFns).toEqual([{ fn: jasmine.any(Function) }, { fn: jasmine.any(Function) }]); + expect(queueableFns).toEqual([ + { fn: jasmine.any(Function) }, + { fn: jasmine.any(Function) } + ]); }); - it("runs leaves in the order specified", function() { + it('runs leaves in the order specified', function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - root = new Node({ children: [leaf1, leaf2] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [leaf2.id, leaf1.id], - queueRunnerFactory: queueRunner - }), - treeComplete = jasmine.createSpy('treeComplete'); + leaf2 = new Leaf(), + root = new Node({ children: [leaf1, leaf2] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [leaf2.id, leaf1.id], + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'); processor.execute(treeComplete); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -520,17 +583,17 @@ describe("TreeProcessor", function() { expect(leaf1.execute).toHaveBeenCalled(); }); - it("runs specified leaves before non-specified leaves within a parent node", function() { + it('runs specified leaves before non-specified leaves within a parent node', function() { var specified = new Leaf(), - nonSpecified = new Leaf(), - root = new Node({ children: [nonSpecified, specified] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [specified.id], - queueRunnerFactory: queueRunner - }), - treeComplete = jasmine.createSpy('treeComplete'); + nonSpecified = new Leaf(), + root = new Node({ children: [nonSpecified, specified] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [specified.id], + queueRunnerFactory: queueRunner + }), + treeComplete = jasmine.createSpy('treeComplete'); processor.execute(treeComplete); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -544,17 +607,17 @@ describe("TreeProcessor", function() { expect(nonSpecified.execute).toHaveBeenCalledWith(undefined, true); }); - it("runs nodes and leaves with a specified order", function() { + it('runs nodes and leaves with a specified order', function() { var specifiedLeaf = new Leaf(), - childLeaf = new Leaf(), - specifiedNode = new Node({ children: [childLeaf] }), - root = new Node({ children: [specifiedLeaf, specifiedNode] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [specifiedNode.id, specifiedLeaf.id], - queueRunnerFactory: queueRunner - }); + childLeaf = new Leaf(), + specifiedNode = new Node({ children: [childLeaf] }), + root = new Node({ children: [specifiedLeaf, specifiedNode] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [specifiedNode.id, specifiedLeaf.id], + queueRunnerFactory: queueRunner + }); processor.execute(); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -571,20 +634,20 @@ describe("TreeProcessor", function() { expect(specifiedLeaf.execute).toHaveBeenCalled(); }); - it("runs a node multiple times if the order specified leaves and re-enters it", function() { + it('runs a node multiple times if the order specified leaves and re-enters it', function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - leaf3 = new Leaf(), - leaf4 = new Leaf(), - leaf5 = new Leaf(), - reentered = new Node({ children: [leaf1, leaf2, leaf3] }), - root = new Node({ children: [reentered, leaf4, leaf5] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [leaf1.id, leaf4.id, leaf2.id, leaf5.id, leaf3.id], - queueRunnerFactory: queueRunner - }); + leaf2 = new Leaf(), + leaf3 = new Leaf(), + leaf4 = new Leaf(), + leaf5 = new Leaf(), + reentered = new Node({ children: [leaf1, leaf2, leaf3] }), + root = new Node({ children: [reentered, leaf4, leaf5] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [leaf1.id, leaf4.id, leaf2.id, leaf5.id, leaf3.id], + queueRunnerFactory: queueRunner + }); processor.execute(); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -614,21 +677,21 @@ describe("TreeProcessor", function() { expect(leaf3.execute).toHaveBeenCalled(); }); - it("runs a parent of a node with segments correctly", function() { + it('runs a parent of a node with segments correctly', function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - leaf3 = new Leaf(), - leaf4 = new Leaf(), - leaf5 = new Leaf(), - parent = new Node({ children: [leaf1, leaf2, leaf3] }), - grandparent = new Node({ children: [parent] }), - root = new Node({ children: [grandparent, leaf4, leaf5] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [leaf1.id, leaf4.id, leaf2.id, leaf5.id, leaf3.id], - queueRunnerFactory: queueRunner - }); + leaf2 = new Leaf(), + leaf3 = new Leaf(), + leaf4 = new Leaf(), + leaf5 = new Leaf(), + parent = new Node({ children: [leaf1, leaf2, leaf3] }), + grandparent = new Node({ children: [parent] }), + root = new Node({ children: [grandparent, leaf4, leaf5] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [leaf1.id, leaf4.id, leaf2.id, leaf5.id, leaf3.id], + queueRunnerFactory: queueRunner + }); processor.execute(); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -671,18 +734,18 @@ describe("TreeProcessor", function() { expect(leaf3.execute).toHaveBeenCalled(); }); - it("runs nodes in the order they were declared", function() { + it('runs nodes in the order they were declared', function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - leaf3 = new Leaf(), - parent = new Node({ children: [leaf2, leaf3] }), - root = new Node({ children: [leaf1, parent] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [root.id], - queueRunnerFactory: queueRunner - }); + leaf2 = new Leaf(), + leaf3 = new Leaf(), + parent = new Node({ children: [leaf2, leaf3] }), + root = new Node({ children: [leaf1, parent] }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [root.id], + queueRunnerFactory: queueRunner + }); processor.execute(); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -702,25 +765,39 @@ describe("TreeProcessor", function() { expect(leaf3.execute).toHaveBeenCalled(); }); - it("runs large segments of nodes in the order they were declared", function() { + it('runs large segments of nodes in the order they were declared', function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - leaf3 = new Leaf(), - leaf4 = new Leaf(), - leaf5 = new Leaf(), - leaf6 = new Leaf(), - leaf7 = new Leaf(), - leaf8 = new Leaf(), - leaf9 = new Leaf(), - leaf10 = new Leaf(), - leaf11 = new Leaf(), - root = new Node({ children: [leaf1, leaf2, leaf3, leaf4, leaf5, leaf6, leaf7, leaf8, leaf9, leaf10, leaf11] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [root.id], - queueRunnerFactory: queueRunner - }); + leaf2 = new Leaf(), + leaf3 = new Leaf(), + leaf4 = new Leaf(), + leaf5 = new Leaf(), + leaf6 = new Leaf(), + leaf7 = new Leaf(), + leaf8 = new Leaf(), + leaf9 = new Leaf(), + leaf10 = new Leaf(), + leaf11 = new Leaf(), + root = new Node({ + children: [ + leaf1, + leaf2, + leaf3, + leaf4, + leaf5, + leaf6, + leaf7, + leaf8, + leaf9, + leaf10, + leaf11 + ] + }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [root.id], + queueRunnerFactory: queueRunner + }); processor.execute(); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -760,29 +837,43 @@ describe("TreeProcessor", function() { expect(leaf11.execute).toHaveBeenCalled(); }); - it("runs nodes in a custom order when orderChildren is overridden", function() { + it('runs nodes in a custom order when orderChildren is overridden', function() { var leaf1 = new Leaf(), - leaf2 = new Leaf(), - leaf3 = new Leaf(), - leaf4 = new Leaf(), - leaf5 = new Leaf(), - leaf6 = new Leaf(), - leaf7 = new Leaf(), - leaf8 = new Leaf(), - leaf9 = new Leaf(), - leaf10 = new Leaf(), - leaf11 = new Leaf(), - root = new Node({ children: [leaf1, leaf2, leaf3, leaf4, leaf5, leaf6, leaf7, leaf8, leaf9, leaf10, leaf11] }), - queueRunner = jasmine.createSpy('queueRunner'), - processor = new jasmineUnderTest.TreeProcessor({ - tree: root, - runnableIds: [root.id], - queueRunnerFactory: queueRunner, - orderChildren: function(node) { - var children = node.children.slice(); - return children.reverse(); - } - }); + leaf2 = new Leaf(), + leaf3 = new Leaf(), + leaf4 = new Leaf(), + leaf5 = new Leaf(), + leaf6 = new Leaf(), + leaf7 = new Leaf(), + leaf8 = new Leaf(), + leaf9 = new Leaf(), + leaf10 = new Leaf(), + leaf11 = new Leaf(), + root = new Node({ + children: [ + leaf1, + leaf2, + leaf3, + leaf4, + leaf5, + leaf6, + leaf7, + leaf8, + leaf9, + leaf10, + leaf11 + ] + }), + queueRunner = jasmine.createSpy('queueRunner'), + processor = new jasmineUnderTest.TreeProcessor({ + tree: root, + runnableIds: [root.id], + queueRunnerFactory: queueRunner, + orderChildren: function(node) { + var children = node.children.slice(); + return children.reverse(); + } + }); processor.execute(); var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns; @@ -820,6 +911,5 @@ describe("TreeProcessor", function() { queueableFns[10].fn(); expect(leaf1.execute).toHaveBeenCalled(); - }); }); diff --git a/spec/core/UserContextSpec.js b/spec/core/UserContextSpec.js index ff71c84d..d8e90f69 100644 --- a/spec/core/UserContextSpec.js +++ b/spec/core/UserContextSpec.js @@ -1,7 +1,7 @@ -describe("UserContext", function() { - it("Behaves just like an plain object", function() { +describe('UserContext', function() { + it('Behaves just like an plain object', function() { var context = new jasmineUnderTest.UserContext(), - properties = []; + properties = []; for (var prop in context) { if (obj.hasOwnProperty(prop)) { @@ -51,4 +51,3 @@ describe("UserContext", function() { }); }); }); - diff --git a/spec/core/UtilSpec.js b/spec/core/UtilSpec.js index a097dc30..759ef8ce 100644 --- a/spec/core/UtilSpec.js +++ b/spec/core/UtilSpec.js @@ -1,11 +1,11 @@ -describe("jasmineUnderTest.util", function() { - describe("isArray_", function() { - it("should return true if the argument is an array", function() { +describe('jasmineUnderTest.util', function() { + describe('isArray_', function() { + it('should return true if the argument is an array', function() { expect(jasmineUnderTest.isArray_([])).toBe(true); expect(jasmineUnderTest.isArray_(['a'])).toBe(true); }); - it("should return false if the argument is not an array", function() { + it('should return false if the argument is not an array', function() { expect(jasmineUnderTest.isArray_(undefined)).toBe(false); expect(jasmineUnderTest.isArray_({})).toBe(false); expect(jasmineUnderTest.isArray_(function() {})).toBe(false); @@ -15,13 +15,13 @@ describe("jasmineUnderTest.util", function() { }); }); - describe("isObject_", function() { - it("should return true if the argument is an object", function() { + describe('isObject_', function() { + it('should return true if the argument is an object', function() { expect(jasmineUnderTest.isObject_({})).toBe(true); - expect(jasmineUnderTest.isObject_({an: "object"})).toBe(true); + expect(jasmineUnderTest.isObject_({ an: 'object' })).toBe(true); }); - it("should return false if the argument is not an object", function() { + it('should return false if the argument is not an object', function() { expect(jasmineUnderTest.isObject_(undefined)).toBe(false); expect(jasmineUnderTest.isObject_([])).toBe(false); expect(jasmineUnderTest.isObject_(function() {})).toBe(false); @@ -31,128 +31,126 @@ describe("jasmineUnderTest.util", function() { }); }); - describe("promise utils", function () { + describe('promise utils', function() { + var mockNativePromise, mockPromiseLikeObject; - var mockNativePromise, - mockPromiseLikeObject; + var mockPromiseLike = function() { + this.then = function() {}; + }; - var mockPromiseLike = function () {this.then = function () {};}; - - beforeEach(function () { + beforeEach(function() { jasmine.getEnv().requirePromises(); - mockNativePromise = new Promise(function (res, rej) {}); + mockNativePromise = new Promise(function(res, rej) {}); mockPromiseLikeObject = new mockPromiseLike(); }); - describe("isPromise", function () { - - it("should return true when passed a native promise", function () { + describe('isPromise', function() { + it('should return true when passed a native promise', function() { expect(jasmineUnderTest.isPromise(mockNativePromise)).toBe(true); }); - it("should return false for promise like objects", function () { + it('should return false for promise like objects', function() { expect(jasmineUnderTest.isPromise(mockPromiseLikeObject)).toBe(false); }); - it("should return false for strings", function () { - expect(jasmineUnderTest.isPromise("hello")).toBe(false); + it('should return false for strings', function() { + expect(jasmineUnderTest.isPromise('hello')).toBe(false); }); - it("should return false for numbers", function () { + it('should return false for numbers', function() { expect(jasmineUnderTest.isPromise(3)).toBe(false); }); - it("should return false for null", function () { + it('should return false for null', function() { expect(jasmineUnderTest.isPromise(null)).toBe(false); }); - it("should return false for undefined", function () { + it('should return false for undefined', function() { expect(jasmineUnderTest.isPromise(undefined)).toBe(false); }); - it("should return false for arrays", function () { + it('should return false for arrays', function() { expect(jasmineUnderTest.isPromise([])).toBe(false); }); - it("should return false for objects", function () { + it('should return false for objects', function() { expect(jasmineUnderTest.isPromise({})).toBe(false); }); - it("should return false for boolean values", function () { + it('should return false for boolean values', function() { expect(jasmineUnderTest.isPromise(true)).toBe(false); }); - }); - describe("isPromiseLike", function () { - - it("should return true when passed a native promise", function () { + describe('isPromiseLike', function() { + it('should return true when passed a native promise', function() { expect(jasmineUnderTest.isPromiseLike(mockNativePromise)).toBe(true); }); - it("should return true for promise like objects", function () { - expect(jasmineUnderTest.isPromiseLike(mockPromiseLikeObject)).toBe(true); + it('should return true for promise like objects', function() { + expect(jasmineUnderTest.isPromiseLike(mockPromiseLikeObject)).toBe( + true + ); }); - it("should return false if then is not a function", function () { - expect(jasmineUnderTest.isPromiseLike({then:{its:"Not a function :O"}})).toBe(false); + it('should return false if then is not a function', function() { + expect( + jasmineUnderTest.isPromiseLike({ then: { its: 'Not a function :O' } }) + ).toBe(false); }); - it("should return false for strings", function () { - expect(jasmineUnderTest.isPromiseLike("hello")).toBe(false); + it('should return false for strings', function() { + expect(jasmineUnderTest.isPromiseLike('hello')).toBe(false); }); - it("should return false for numbers", function () { + it('should return false for numbers', function() { expect(jasmineUnderTest.isPromiseLike(3)).toBe(false); }); - it("should return false for null", function () { + it('should return false for null', function() { expect(jasmineUnderTest.isPromiseLike(null)).toBe(false); }); - it("should return false for undefined", function () { + it('should return false for undefined', function() { expect(jasmineUnderTest.isPromiseLike(undefined)).toBe(false); }); - it("should return false for arrays", function () { + it('should return false for arrays', function() { expect(jasmineUnderTest.isPromiseLike([])).toBe(false); }); - it("should return false for objects", function () { + it('should return false for objects', function() { expect(jasmineUnderTest.isPromiseLike({})).toBe(false); }); - it("should return false for boolean values", function () { + it('should return false for boolean values', function() { expect(jasmineUnderTest.isPromiseLike(true)).toBe(false); }); - }); - }); - describe("isUndefined", function() { - it("reports if a variable is defined", function() { + describe('isUndefined', function() { + it('reports if a variable is defined', function() { var a; expect(jasmineUnderTest.util.isUndefined(a)).toBe(true); expect(jasmineUnderTest.util.isUndefined(undefined)).toBe(true); - var undefined = "diz be undefined yo"; + var undefined = 'diz be undefined yo'; expect(jasmineUnderTest.util.isUndefined(undefined)).toBe(false); }); }); - describe("getPropertyDescriptor", function() { - it("get property descriptor from object", function() { - var obj = {prop: 1}, + describe('getPropertyDescriptor', function() { + it('get property descriptor from object', function() { + var obj = { prop: 1 }, actual = jasmineUnderTest.util.getPropertyDescriptor(obj, 'prop'), expected = Object.getOwnPropertyDescriptor(obj, 'prop'); expect(actual).toEqual(expected); }); - it("get property descriptor from object property", function() { - var proto = {prop: 1}, - obj = Object.create(proto), + it('get property descriptor from object property', function() { + var proto = { prop: 1 }, actual = jasmineUnderTest.util.getPropertyDescriptor(proto, 'prop'), expected = Object.getOwnPropertyDescriptor(proto, 'prop'); @@ -160,8 +158,8 @@ describe("jasmineUnderTest.util", function() { }); }); - describe("objectDifference", function() { - it("given two objects A and B, returns the properties in A not present in B", function() { + describe('objectDifference', function() { + it('given two objects A and B, returns the properties in A not present in B', function() { var a = { foo: 3, bar: 4, @@ -173,10 +171,13 @@ describe("jasmineUnderTest.util", function() { quux: 7 }; - expect(jasmineUnderTest.util.objectDifference(a, b)).toEqual({foo: 3, baz: 5}) + expect(jasmineUnderTest.util.objectDifference(a, b)).toEqual({ + foo: 3, + baz: 5 + }); }); - it("only looks at own properties of both objects", function() { + it('only looks at own properties of both objects', function() { function Foo() {} Foo.prototype.x = 1; @@ -188,13 +189,13 @@ describe("jasmineUnderTest.util", function() { var b = new Foo(); b.y = 2; - expect(jasmineUnderTest.util.objectDifference(a, b)).toEqual({x: 1}); - expect(jasmineUnderTest.util.objectDifference(b, a)).toEqual({y: 2}); + expect(jasmineUnderTest.util.objectDifference(a, b)).toEqual({ x: 1 }); + expect(jasmineUnderTest.util.objectDifference(b, a)).toEqual({ y: 2 }); }); }); - describe("jasmineFile", function() { - it("returns the file containing jasmine.util", function() { + describe('jasmineFile', function() { + it('returns the file containing jasmine.util', function() { // Chrome sometimes reports foo.js as foo.js/, so tolerate // a trailing slash if present. expect(jasmineUnderTest.util.jasmineFile()).toMatch(/util.js\/?$/); diff --git a/spec/core/baseSpec.js b/spec/core/baseSpec.js index 7f17265b..07f94e19 100644 --- a/spec/core/baseSpec.js +++ b/spec/core/baseSpec.js @@ -1,6 +1,6 @@ describe('base helpers', function() { describe('isError_', function() { - it("correctly handles WebSocket events", function(done) { + it('correctly handles WebSocket events', function(done) { if (typeof jasmine.getGlobal().WebSocket === 'undefined') { done(); return; @@ -10,9 +10,11 @@ describe('base helpers', function() { var sock = new WebSocket('ws://localhost'); var event; sock.onerror = function(e) { - event = e + event = e; + }; + return function() { + return event; }; - return function() { return event }; })(); var left = 20; @@ -20,6 +22,7 @@ describe('base helpers', function() { if (obj() || left === 0) { var result = jasmineUnderTest.isError_(obj()); expect(result).toBe(false); + clearInterval(int); done(); } else { left--; diff --git a/spec/core/formatErrorMsgSpec.js b/spec/core/formatErrorMsgSpec.js index 12812443..a85665e9 100644 --- a/spec/core/formatErrorMsgSpec.js +++ b/spec/core/formatErrorMsgSpec.js @@ -1,4 +1,4 @@ -describe('formatErrorMsg', function () { +describe('formatErrorMsg', function() { it('should format an error with a domain', function() { var formator = jasmineUnderTest.formatErrorMsg('api'); expect(formator('message')).toBe('api : message'); diff --git a/spec/helpers/BrowserFlags.js b/spec/helpers/BrowserFlags.js index 9cf630e7..248fc274 100644 --- a/spec/helpers/BrowserFlags.js +++ b/spec/helpers/BrowserFlags.js @@ -1,7 +1,9 @@ (function(env) { function browserVersion(matchFn) { var userAgent = jasmine.getGlobal().navigator.userAgent; - if (!userAgent) { return void 0; } + if (!userAgent) { + return void 0; + } var match = matchFn(userAgent); @@ -11,5 +13,4 @@ env.firefoxVersion = browserVersion(function(userAgent) { return /Firefox\/([0-9]{0,})/.exec(userAgent); }); - })(jasmine.getEnv()); diff --git a/spec/helpers/asyncAwait.js b/spec/helpers/asyncAwait.js index 866d9526..9cdead0d 100644 --- a/spec/helpers/asyncAwait.js +++ b/spec/helpers/asyncAwait.js @@ -1,7 +1,7 @@ (function(env) { function getAsyncCtor() { try { - eval("var func = async function(){};"); + eval('var func = async function(){};'); } catch (e) { return null; } @@ -15,13 +15,12 @@ env.makeAsyncAwaitFunction = function() { var AsyncFunction = getAsyncCtor(); - return new AsyncFunction(""); + return new AsyncFunction(''); }; env.requireAsyncAwait = function() { if (!hasAsyncAwaitSupport()) { - env.pending("Environment does not support async/await functions"); + env.pending('Environment does not support async/await functions'); } }; })(jasmine.getEnv()); - diff --git a/spec/helpers/checkForMap.js b/spec/helpers/checkForMap.js index 697d5738..64e32cdc 100644 --- a/spec/helpers/checkForMap.js +++ b/spec/helpers/checkForMap.js @@ -1,37 +1,46 @@ (function(env) { function hasFunctioningMaps() { - if (typeof Map === 'undefined') { return false; } + if (typeof Map === 'undefined') { + return false; + } try { var s = new Map(); - s.set('a',1); - s.set('b',2); + s.set('a', 1); + s.set('b', 2); - if (s.size !== 2) { return false; } - if (s.has('a') !== true) { return false; } + if (s.size !== 2) { + return false; + } + if (s.has('a') !== true) { + return false; + } var iterations = 0; var ifForEachWorking = true; s.forEach(function(value, key, map) { ifForEachWorking = ifForEachWorking && map === s; - if (key==='a') { - ifForEachWorking = ifForEachWorking && value===1; + if (key === 'a') { + ifForEachWorking = ifForEachWorking && value === 1; } iterations++; }); - if (iterations !== 2) { return false; } - if (ifForEachWorking !== true) { return false; } + if (iterations !== 2) { + return false; + } + if (ifForEachWorking !== true) { + return false; + } return true; - } catch(e) { + } catch (e) { return false; } } env.requireFunctioningMaps = function() { if (!hasFunctioningMaps()) { - env.pending("Browser has incomplete or missing support for Maps"); + env.pending('Browser has incomplete or missing support for Maps'); } }; - })(jasmine.getEnv()); diff --git a/spec/helpers/checkForSet.js b/spec/helpers/checkForSet.js index d12e847b..1be8de45 100644 --- a/spec/helpers/checkForSet.js +++ b/spec/helpers/checkForSet.js @@ -1,41 +1,50 @@ (function(env) { function hasFunctioningSets() { - if (typeof Set === 'undefined') { return false; } + if (typeof Set === 'undefined') { + return false; + } try { var s = new Set(); s.add(1); s.add(2); - if (s.size !== 2) { return false; } - if (s.has(1) !== true) { return false; } + if (s.size !== 2) { + return false; + } + if (s.has(1) !== true) { + return false; + } var iterations = 0; var isForEachWorking = true; s.forEach(function(value, key, set) { isForEachWorking = isForEachWorking && set === s; - if (iterations===0) { - isForEachWorking = isForEachWorking && (key===value) && value===1; - } else if (iterations===1) { - isForEachWorking = isForEachWorking && (key===value) && value===2; + if (iterations === 0) { + isForEachWorking = isForEachWorking && key === value && value === 1; + } else if (iterations === 1) { + isForEachWorking = isForEachWorking && key === value && value === 2; } iterations++; }); - if (iterations !== 2) { return false; } - if (isForEachWorking !== true) { return false; } + if (iterations !== 2) { + return false; + } + if (isForEachWorking !== true) { + return false; + } return true; - } catch(e) { + } catch (e) { return false; } } env.requireFunctioningSets = function() { if (!hasFunctioningSets()) { - env.pending("Browser has incomplete or missing support for Sets"); + env.pending('Browser has incomplete or missing support for Sets'); } }; - })(jasmine.getEnv()); diff --git a/spec/helpers/checkForSymbol.js b/spec/helpers/checkForSymbol.js index 93e414ee..c1ed5415 100644 --- a/spec/helpers/checkForSymbol.js +++ b/spec/helpers/checkForSymbol.js @@ -21,8 +21,7 @@ env.requireFunctioningSymbols = function() { if (!hasFunctioningSymbols()) { - env.pending("Browser has incomplete or missing support for Symbols"); + env.pending('Browser has incomplete or missing support for Symbols'); } }; - })(jasmine.getEnv()); diff --git a/spec/helpers/checkForTypedArrays.js b/spec/helpers/checkForTypedArrays.js index ddbdcc9f..3b5d6b35 100644 --- a/spec/helpers/checkForTypedArrays.js +++ b/spec/helpers/checkForTypedArrays.js @@ -1,20 +1,23 @@ (function(env) { function hasFunctioningTypedArrays() { - if (typeof Uint32Array === 'undefined') { return false; } + if (typeof Uint32Array === 'undefined') { + return false; + } try { var a = new Uint32Array([1, 2, 3]); - if (a.length !== 3) { return false; } + if (a.length !== 3) { + return false; + } return true; - } catch(e) { + } catch (e) { return false; } } env.requireFunctioningTypedArrays = function() { if (!hasFunctioningTypedArrays()) { - env.pending("Browser has incomplete or missing support for typed arrays"); + env.pending('Browser has incomplete or missing support for typed arrays'); } }; - })(jasmine.getEnv()); diff --git a/spec/helpers/integrationMatchers.js b/spec/helpers/integrationMatchers.js index 8b524946..694ccd6e 100644 --- a/spec/helpers/integrationMatchers.js +++ b/spec/helpers/integrationMatchers.js @@ -1,10 +1,15 @@ (function(env) { env.registerIntegrationMatchers = function() { jasmine.addMatchers({ - toHaveFailedExpectationsForRunnable: function (util, customeEqualityTesters) { + toHaveFailedExpectationsForRunnable: function( + util, + customeEqualityTesters + ) { return { - compare: function (actual, fullName, expectedFailures) { - var foundRunnable = false, expectations = true, foundFailures = []; + compare: function(actual, fullName, expectedFailures) { + var foundRunnable = false, + expectations = true, + foundFailures = []; for (var i = 0; i < actual.calls.count(); i++) { var args = actual.calls.argsFor(i)[0]; @@ -19,8 +24,12 @@ var failure = foundFailures[j]; var expectedFailure = expectedFailures[j]; - if (Object.prototype.toString.call(expectedFailure) === '[object RegExp]') { - expectations = expectations && expectedFailure.test(failure); + if ( + Object.prototype.toString.call(expectedFailure) === + '[object RegExp]' + ) { + expectations = + expectations && expectedFailure.test(failure); } else { expectations = expectations && failure === expectedFailure; } @@ -31,8 +40,14 @@ return { pass: foundRunnable && expectations, - message: !foundRunnable ? 'The runnable "' + fullName + '" never finished' : - 'Expected runnable "' + fullName + '" to have failures ' + jasmine.pp(expectedFailures) + ' but it had ' + jasmine.pp(foundFailures) + message: !foundRunnable + ? 'The runnable "' + fullName + '" never finished' + : 'Expected runnable "' + + fullName + + '" to have failures ' + + jasmine.pp(expectedFailures) + + ' but it had ' + + jasmine.pp(foundFailures) }; } }; @@ -40,4 +55,3 @@ }); }; })(jasmine.getEnv()); - diff --git a/spec/helpers/nodeDefineJasmineUnderTest.js b/spec/helpers/nodeDefineJasmineUnderTest.js index 119265af..739c20af 100644 --- a/spec/helpers/nodeDefineJasmineUnderTest.js +++ b/spec/helpers/nodeDefineJasmineUnderTest.js @@ -1,21 +1,19 @@ (function() { - var path = require("path"), - fg = require("fast-glob"); + var path = require('path'), + fg = require('fast-glob'); - var jasmineUnderTestRequire = require(path.join(__dirname, "../../src/core/requireCore.js")); + var jasmineUnderTestRequire = require(path.join( + __dirname, + '../../src/core/requireCore.js' + )); - global.getJasmineRequireObj = function () { + global.getJasmineRequireObj = function() { return jasmineUnderTestRequire; }; - function extend(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; - } - function getSourceFiles() { var src_files = ['core/**/*.js', 'version.js'].map(function(file) { - return path.join(__dirname, "../../", 'src/', file); + return path.join(__dirname, '../../', 'src/', file); }); fg.sync(src_files).forEach(function(resolvedFile) { @@ -24,5 +22,7 @@ } getSourceFiles(); - global.jasmineUnderTest = jasmineUnderTestRequire.core(jasmineUnderTestRequire); + global.jasmineUnderTest = jasmineUnderTestRequire.core( + jasmineUnderTestRequire + ); })(); diff --git a/spec/helpers/promises.js b/spec/helpers/promises.js index 76c6c024..a194af0c 100644 --- a/spec/helpers/promises.js +++ b/spec/helpers/promises.js @@ -1,8 +1,7 @@ (function(env) { env.requirePromises = function() { if (typeof Promise !== 'function') { - env.pending("Environment does not support promises"); + env.pending('Environment does not support promises'); } }; })(jasmine.getEnv()); - diff --git a/spec/html/HtmlReporterSpec.js b/spec/html/HtmlReporterSpec.js index 8b40139c..a8790f87 100644 --- a/spec/html/HtmlReporterSpec.js +++ b/spec/html/HtmlReporterSpec.js @@ -1,178 +1,244 @@ -describe("HtmlReporter", function() { - it("builds the initial DOM elements, including the title banner", function() { +describe('HtmlReporter', function() { + it('builds the initial DOM elements, including the title banner', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); // Main top-level elements - expect(container.querySelector("div.jasmine_html-reporter")).toBeTruthy(); - expect(container.querySelector("div.jasmine-banner")).toBeTruthy(); - expect(container.querySelector("div.jasmine-alert")).toBeTruthy(); - expect(container.querySelector("div.jasmine-results")).toBeTruthy(); + expect(container.querySelector('div.jasmine_html-reporter')).toBeTruthy(); + expect(container.querySelector('div.jasmine-banner')).toBeTruthy(); + expect(container.querySelector('div.jasmine-alert')).toBeTruthy(); + expect(container.querySelector('div.jasmine-results')).toBeTruthy(); - expect(container.querySelector("ul.jasmine-symbol-summary")).toBeTruthy(); + expect(container.querySelector('ul.jasmine-symbol-summary')).toBeTruthy(); // title banner - var banner = container.querySelector(".jasmine-banner"); + var banner = container.querySelector('.jasmine-banner'); - var title = banner.querySelector("a.jasmine-title"); + var title = banner.querySelector('a.jasmine-title'); expect(title.getAttribute('href')).toEqual('http://jasmine.github.io/'); expect(title.getAttribute('target')).toEqual('_blank'); - var version = banner.querySelector(".jasmine-version"); + var version = banner.querySelector('.jasmine-version'); expect(version.textContent).toEqual(jasmineUnderTest.version); }); - it("builds a single reporter even if initialized multiple times", function() { + it('builds a single reporter even if initialized multiple times', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); reporter.initialize(); reporter.initialize(); - expect(container.querySelectorAll("div.jasmine_html-reporter").length).toEqual(1); + expect( + container.querySelectorAll('div.jasmine_html-reporter').length + ).toEqual(1); }); - it("starts the timer when jasmine begins", function() { + it('starts the timer when jasmine begins', function() { var env = new jasmine.Env(), - startTimerSpy = jasmine.createSpy("start-timer-spy"), - reporter = new jasmineUnderTest.HtmlReporter({ - env: env, - createElement: function() { return document.createElement.apply(document, arguments); }, - timer: { start: startTimerSpy } - }); + startTimerSpy = jasmine.createSpy('start-timer-spy'), + reporter = new jasmineUnderTest.HtmlReporter({ + env: env, + createElement: function() { + return document.createElement.apply(document, arguments); + }, + timer: { start: startTimerSpy } + }); reporter.jasmineStarted({}); expect(startTimerSpy).toHaveBeenCalled(); }); - describe("when a spec is done", function() { - it("logs errors to the console and prints a special symbol if it is an empty spec", function() { - if (typeof console === "undefined") { - console = { error: function(){} }; + describe('when a spec is done', function() { + it('logs errors to the console and prints a special symbol if it is an empty spec', function() { + if (typeof console === 'undefined') { + console = { error: function() {} }; } var env = new jasmineUnderTest.Env(), - container = document.createElement('div'), - getContainer = function() {return container;}, - reporter = new jasmineUnderTest.HtmlReporter({ - env: env, - getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } - }); + container = document.createElement('div'), + getContainer = function() { + return container; + }, + reporter = new jasmineUnderTest.HtmlReporter({ + env: env, + getContainer: getContainer, + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } + }); spyOn(console, 'error'); reporter.initialize(); reporter.specDone({ - status: "passed", + status: 'passed', fullName: 'Some Name', passedExpectations: [], failedExpectations: [] }); - expect(console.error).toHaveBeenCalledWith("Spec \'Some Name\' has no expectations."); + expect(console.error).toHaveBeenCalledWith( + "Spec 'Some Name' has no expectations." + ); var specEl = container.querySelector('.jasmine-symbol-summary li'); - expect(specEl.getAttribute("class")).toEqual("jasmine-empty"); + expect(specEl.getAttribute('class')).toEqual('jasmine-empty'); }); - it("reports the status symbol of a excluded spec", function() { + it('reports the status symbol of a excluded spec', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); - reporter.specDone({id: 789, status: "excluded", fullName: "symbols should have titles", passedExpectations: [], failedExpectations: []}); + reporter.specDone({ + id: 789, + status: 'excluded', + fullName: 'symbols should have titles', + passedExpectations: [], + failedExpectations: [] + }); var specEl = container.querySelector('.jasmine-symbol-summary li'); - expect(specEl.getAttribute("class")).toEqual("jasmine-excluded"); - expect(specEl.getAttribute("id")).toEqual("spec_789"); - expect(specEl.getAttribute("title")).toEqual("symbols should have titles"); + expect(specEl.getAttribute('class')).toEqual('jasmine-excluded'); + expect(specEl.getAttribute('id')).toEqual('spec_789'); + expect(specEl.getAttribute('title')).toEqual( + 'symbols should have titles' + ); }); - it("reports the status symbol of a pending spec", function() { + it('reports the status symbol of a pending spec', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); - reporter.specDone({id: 789, status: "pending", passedExpectations: [], failedExpectations: []}); + reporter.specDone({ + id: 789, + status: 'pending', + passedExpectations: [], + failedExpectations: [] + }); var specEl = container.querySelector('.jasmine-symbol-summary li'); - expect(specEl.getAttribute("class")).toEqual("jasmine-pending"); - expect(specEl.getAttribute("id")).toEqual("spec_789"); + expect(specEl.getAttribute('class')).toEqual('jasmine-pending'); + expect(specEl.getAttribute('id')).toEqual('spec_789'); }); - it("reports the status symbol of a passing spec", function() { + it('reports the status symbol of a passing spec', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); - reporter.specDone({id: 123, status: "passed", passedExpectations: [{passed: true}], failedExpectations: []}); + reporter.specDone({ + id: 123, + status: 'passed', + passedExpectations: [{ passed: true }], + failedExpectations: [] + }); - var statuses = container.querySelector(".jasmine-symbol-summary"); - var specEl = statuses.querySelector("li"); - expect(specEl.getAttribute("class")).toEqual("jasmine-passed"); - expect(specEl.getAttribute("id")).toEqual("spec_123"); + var statuses = container.querySelector('.jasmine-symbol-summary'); + var specEl = statuses.querySelector('li'); + expect(specEl.getAttribute('class')).toEqual('jasmine-passed'); + expect(specEl.getAttribute('id')).toEqual('spec_123'); }); - it("reports the status symbol of a failing spec", function() { + it('reports the status symbol of a failing spec', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); reporter.specDone({ id: 345, - status: "failed", + status: 'failed', failedExpectations: [], passedExpectations: [] }); - var specEl = container.querySelector(".jasmine-symbol-summary li"); - expect(specEl.getAttribute("class")).toEqual("jasmine-failed"); - expect(specEl.getAttribute("id")).toEqual("spec_345"); + var specEl = container.querySelector('.jasmine-symbol-summary li'); + expect(specEl.getAttribute('class')).toEqual('jasmine-failed'); + expect(specEl.getAttribute('id')).toEqual('spec_345'); }); }); @@ -180,12 +246,18 @@ describe("HtmlReporter", function() { it('displays the messages in their own alert bars', function() { var env = new jasmineUnderTest.Env(), container = document.createElement('div'), - getContainer = function() { return container; }, + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); @@ -207,37 +279,49 @@ describe("HtmlReporter", function() { failedExpectations: [] }); - var alertBars = container.querySelectorAll(".jasmine-alert .jasmine-bar"); + var alertBars = container.querySelectorAll('.jasmine-alert .jasmine-bar'); expect(alertBars.length).toEqual(4); expect(alertBars[1].innerHTML).toMatch(/spec deprecation/); - expect(alertBars[1].getAttribute("class")).toEqual('jasmine-bar jasmine-warning'); + expect(alertBars[1].getAttribute('class')).toEqual( + 'jasmine-bar jasmine-warning' + ); expect(alertBars[2].innerHTML).toMatch(/suite deprecation/); expect(alertBars[3].innerHTML).toMatch(/global deprecation/); }); }); - describe("when Jasmine is done", function() { - it("adds a warning to the link title of specs that have no expectations", function() { + describe('when Jasmine is done', function() { + it('adds a warning to the link title of specs that have no expectations', function() { if (!window.console) { - window.console = { error: function(){} }; + window.console = { error: function() {} }; } var env = new jasmineUnderTest.Env(), - container = document.createElement('div'), - getContainer = function() {return container;}, - reporter = new jasmineUnderTest.HtmlReporter({ - env: env, - getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } - }); + container = document.createElement('div'), + getContainer = function() { + return container; + }, + reporter = new jasmineUnderTest.HtmlReporter({ + env: env, + getContainer: getContainer, + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } + }); spyOn(console, 'error'); reporter.initialize(); reporter.jasmineStarted({}); - reporter.suiteStarted({id: 1}); - reporter.specStarted({id: 1, passedExpectations: [], failedExpectations: []}); + reporter.suiteStarted({ id: 1 }); + reporter.specStarted({ + id: 1, + passedExpectations: [], + failedExpectations: [] + }); reporter.specDone({ id: 1, status: 'passed', @@ -245,7 +329,7 @@ describe("HtmlReporter", function() { passedExpectations: [], failedExpectations: [] }); - reporter.suiteDone({id: 1}); + reporter.suiteDone({ id: 1 }); reporter.jasmineDone({}); var summary = container.querySelector('.jasmine-summary'); @@ -256,16 +340,22 @@ describe("HtmlReporter", function() { expect(specLink.innerHTML).toMatch(/SPEC HAS NO EXPECTATIONS/); }); - it("reports the run time", function() { + it('reports the run time', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), timer = jasmine.createSpyObj('timer', ['start', 'elapsed']), - getContainer = function() { return container; }, + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); }, + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + }, timer: timer }); @@ -276,54 +366,64 @@ describe("HtmlReporter", function() { timer.elapsed.and.returnValue(100); reporter.jasmineDone({}); - var duration = container.querySelector(".jasmine-alert .jasmine-duration"); + var duration = container.querySelector( + '.jasmine-alert .jasmine-duration' + ); expect(duration.innerHTML).toMatch(/finished in 0.1s/); }); - it("reports the suite and spec names with status", function() { + it('reports the suite and spec names with status', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); }, - addToExistingQueryString: function(key, value) { return "?foo=bar&" + key + "=" + value; } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + }, + addToExistingQueryString: function(key, value) { + return '?foo=bar&' + key + '=' + value; + } }); reporter.initialize(); reporter.jasmineStarted({}); reporter.suiteStarted({ id: 1, - description: "A Suite", - fullName: "A Suite" + description: 'A Suite', + fullName: 'A Suite' }); var specResult = { id: 123, - description: "with a spec", - fullName: "A Suite with a spec", - status: "passed", + description: 'with a spec', + fullName: 'A Suite with a spec', + status: 'passed', failedExpectations: [], - passedExpectations: [{passed: true}] + passedExpectations: [{ passed: true }] }; reporter.specStarted(specResult); reporter.specDone(specResult); reporter.suiteStarted({ id: 2, - description: "inner suite", - fullName: "A Suite inner suite" + description: 'inner suite', + fullName: 'A Suite inner suite' }); var specResult = { id: 124, - description: "with another spec", - fullName: "A Suite inner suite with another spec", - status: "passed", + description: 'with another spec', + fullName: 'A Suite inner suite with another spec', + status: 'passed', failedExpectations: [], - passedExpectations: [{passed: true}] + passedExpectations: [{ passed: true }] }; reporter.specStarted(specResult); reporter.specDone(specResult); @@ -331,15 +431,15 @@ describe("HtmlReporter", function() { reporter.suiteDone({ id: 2, status: 'things', - description: "inner suite", - fullName: "A Suite inner suite" + description: 'inner suite', + fullName: 'A Suite inner suite' }); specResult = { id: 209, - description: "with a failing spec", - fullName: "A Suite inner with a failing spec", - status: "failed", + description: 'with a failing spec', + fullName: 'A Suite inner with a failing spec', + status: 'failed', failedExpectations: [{}], passedExpectations: [] }; @@ -349,12 +449,12 @@ describe("HtmlReporter", function() { reporter.suiteDone({ id: 1, status: 'things', - description: "A Suite", - fullName: "A Suite" + description: 'A Suite', + fullName: 'A Suite' }); reporter.jasmineDone({}); - var summary = container.querySelector(".jasmine-summary"); + var summary = container.querySelector('.jasmine-summary'); expect(summary.childNodes.length).toEqual(1); @@ -364,28 +464,35 @@ describe("HtmlReporter", function() { var classes = []; for (var i = 0; i < outerSuite.childNodes.length; i++) { var node = outerSuite.childNodes[i]; - classes.push(node.getAttribute("class")); + classes.push(node.getAttribute('class')); } - expect(classes).toEqual(["jasmine-suite-detail jasmine-things", "jasmine-specs", "jasmine-suite", "jasmine-specs"]); + expect(classes).toEqual([ + 'jasmine-suite-detail jasmine-things', + 'jasmine-specs', + 'jasmine-suite', + 'jasmine-specs' + ]); var suiteDetail = outerSuite.childNodes[0]; var suiteLink = suiteDetail.childNodes[0]; - expect(suiteLink.innerHTML).toEqual("A Suite"); - expect(suiteLink.getAttribute('href')).toEqual("?foo=bar&spec=A Suite"); + expect(suiteLink.innerHTML).toEqual('A Suite'); + expect(suiteLink.getAttribute('href')).toEqual('?foo=bar&spec=A Suite'); var specs = outerSuite.childNodes[1]; var spec = specs.childNodes[0]; - expect(spec.getAttribute("class")).toEqual("jasmine-passed"); - expect(spec.getAttribute("id")).toEqual("spec-123"); + expect(spec.getAttribute('class')).toEqual('jasmine-passed'); + expect(spec.getAttribute('id')).toEqual('spec-123'); var specLink = spec.childNodes[0]; - expect(specLink.innerHTML).toEqual("with a spec"); - expect(specLink.getAttribute("href")).toEqual("?foo=bar&spec=A Suite with a spec"); + expect(specLink.innerHTML).toEqual('with a spec'); + expect(specLink.getAttribute('href')).toEqual( + '?foo=bar&spec=A Suite with a spec' + ); }); - it("has an options menu", function() { + it('has an options menu', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), getContainer = function() { return container; }, @@ -403,8 +510,12 @@ describe("HtmlReporter", function() { reporter.initialize(); reporter.jasmineDone({}); - var trigger = container.querySelector('.jasmine-run-options .jasmine-trigger'), - payload = container.querySelector('.jasmine-run-options .jasmine-payload'); + var trigger = container.querySelector( + '.jasmine-run-options .jasmine-trigger' + ), + payload = container.querySelector( + '.jasmine-run-options .jasmine-payload' + ); expect(payload).not.toHaveClass('jasmine-open'); @@ -417,69 +528,100 @@ describe("HtmlReporter", function() { expect(payload).not.toHaveClass('jasmine-open'); }); - describe("when there are global errors", function() { - it("displays the exceptions in their own alert bars", function(){ + describe('when there are global errors', function() { + it('displays the exceptions in their own alert bars', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); reporter.jasmineStarted({}); - reporter.jasmineDone({ failedExpectations: [ - { message: 'Global After All Failure', globalErrorType: 'afterAll' }, + reporter.jasmineDone({ + failedExpectations: [ + { + message: 'Global After All Failure', + globalErrorType: 'afterAll' + }, { message: 'Your JS is borken', globalErrorType: 'load' } - ] }); + ] + }); - var alertBars = container.querySelectorAll(".jasmine-alert .jasmine-bar"); + var alertBars = container.querySelectorAll( + '.jasmine-alert .jasmine-bar' + ); expect(alertBars.length).toEqual(3); - expect(alertBars[1].getAttribute("class")).toEqual('jasmine-bar jasmine-errored'); - expect(alertBars[1].innerHTML).toMatch(/AfterAll Global After All Failure/); - expect(alertBars[2].innerHTML).toMatch(/Error during loading: Your JS is borken/); + expect(alertBars[1].getAttribute('class')).toEqual( + 'jasmine-bar jasmine-errored' + ); + expect(alertBars[1].innerHTML).toMatch( + /AfterAll Global After All Failure/ + ); + expect(alertBars[2].innerHTML).toMatch( + /Error during loading: Your JS is borken/ + ); expect(alertBars[2].innerHTML).not.toMatch(/line/); }); - it("displays file and line information if available", function() { + it('displays file and line information if available', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); reporter.jasmineStarted({}); - reporter.jasmineDone({ failedExpectations: [ + reporter.jasmineDone({ + failedExpectations: [ { message: 'Your JS is borken', globalErrorType: 'load', filename: 'some/file.js', lineno: 42 } - ] }); + ] + }); - var alertBars = container.querySelectorAll(".jasmine-alert .jasmine-bar"); + var alertBars = container.querySelectorAll( + '.jasmine-alert .jasmine-bar' + ); expect(alertBars.length).toEqual(2); - expect(alertBars[1].innerHTML).toMatch(/Error during loading: Your JS is borken in some\/file.js line 42/); + expect(alertBars[1].innerHTML).toMatch( + /Error during loading: Your JS is borken in some\/file.js line 42/ + ); }); }); - describe("UI for stop on spec failure", function() { - it("should be unchecked for full execution", function() { + describe('UI for stop on spec failure', function() { + it('should be unchecked for full execution', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), getContainer = function() { return container; }, @@ -497,13 +639,13 @@ describe("HtmlReporter", function() { reporter.initialize(); reporter.jasmineDone({}); - var stopOnFailureUI = container.querySelector(".jasmine-fail-fast"); + var stopOnFailureUI = container.querySelector('.jasmine-fail-fast'); expect(stopOnFailureUI.checked).toBe(false); }); - it("should be checked if stopping short", function() { + it('should be checked if stopping short', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), getContainer = function() { return container; }, @@ -518,18 +660,18 @@ describe("HtmlReporter", function() { } }); - env.configure({failFast: true}); + env.configure({ failFast: true }); reporter.initialize(); reporter.jasmineDone({}); - var stopOnFailureUI = container.querySelector(".jasmine-fail-fast"); + var stopOnFailureUI = container.querySelector('.jasmine-fail-fast'); expect(stopOnFailureUI.checked).toBe(true); }); - it("should navigate and turn the setting on", function() { + it('should navigate and turn the setting on', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), navigationHandler = jasmine.createSpy('navigate'), getContainer = function() { return container; @@ -549,15 +691,15 @@ describe("HtmlReporter", function() { reporter.initialize(); reporter.jasmineDone({}); - var stopOnFailureUI = container.querySelector(".jasmine-fail-fast"); + var stopOnFailureUI = container.querySelector('.jasmine-fail-fast'); stopOnFailureUI.click(); expect(navigationHandler).toHaveBeenCalledWith('failFast', true); }); - it("should navigate and turn the setting off", function() { + it('should navigate and turn the setting off', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), navigationHandler = jasmine.createSpy('navigate'), getContainer = function() { return container; @@ -574,22 +716,22 @@ describe("HtmlReporter", function() { } }); - env.configure({failFast: true}); + env.configure({ failFast: true }); reporter.initialize(); reporter.jasmineDone({}); - var stopOnFailureUI = container.querySelector(".jasmine-fail-fast"); + var stopOnFailureUI = container.querySelector('.jasmine-fail-fast'); stopOnFailureUI.click(); expect(navigationHandler).toHaveBeenCalledWith('failFast', false); }); }); - describe("UI for throwing errors on expectation failures", function() { - it("should be unchecked if not throwing", function() { + describe('UI for throwing errors on expectation failures', function() { + it('should be unchecked if not throwing', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), getContainer = function() { return container; }, @@ -607,13 +749,13 @@ describe("HtmlReporter", function() { reporter.initialize(); reporter.jasmineDone({}); - var throwingExpectationsUI = container.querySelector(".jasmine-throw"); + var throwingExpectationsUI = container.querySelector('.jasmine-throw'); expect(throwingExpectationsUI.checked).toBe(false); }); - it("should be checked if throwing", function() { + it('should be checked if throwing', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), getContainer = function() { return container; }, @@ -628,18 +770,18 @@ describe("HtmlReporter", function() { } }); - env.configure({oneFailurePerSpec: true}); + env.configure({ oneFailurePerSpec: true }); reporter.initialize(); reporter.jasmineDone({}); - var throwingExpectationsUI = container.querySelector(".jasmine-throw"); + var throwingExpectationsUI = container.querySelector('.jasmine-throw'); expect(throwingExpectationsUI.checked).toBe(true); }); - it("should navigate and change the setting to on", function() { + it('should navigate and change the setting to on', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), navigateHandler = jasmine.createSpy('navigate'), getContainer = function() { return container; @@ -659,15 +801,15 @@ describe("HtmlReporter", function() { reporter.initialize(); reporter.jasmineDone({}); - var throwingExpectationsUI = container.querySelector(".jasmine-throw"); + var throwingExpectationsUI = container.querySelector('.jasmine-throw'); throwingExpectationsUI.click(); expect(navigateHandler).toHaveBeenCalledWith('throwFailures', true); }); - it("should navigate and change the setting to off", function() { + it('should navigate and change the setting to off', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), navigateHandler = jasmine.createSpy('navigate'), getContainer = function() { return container; @@ -684,21 +826,21 @@ describe("HtmlReporter", function() { } }); - env.configure({oneFailurePerSpec: true}); + env.configure({ oneFailurePerSpec: true }); reporter.initialize(); reporter.jasmineDone({}); - var throwingExpectationsUI = container.querySelector(".jasmine-throw"); + var throwingExpectationsUI = container.querySelector('.jasmine-throw'); throwingExpectationsUI.click(); expect(navigateHandler).toHaveBeenCalledWith('throwFailures', false); }); }); - describe("UI for hiding disabled specs", function() { - it("should be unchecked if not hiding disabled specs", function() { + describe('UI for hiding disabled specs', function() { + it('should be unchecked if not hiding disabled specs', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), getContainer = function() { return container; }, @@ -713,17 +855,17 @@ describe("HtmlReporter", function() { } }); - env.configure({hideDisabled: false}); + env.configure({ hideDisabled: false }); reporter.initialize(); reporter.jasmineDone({}); - var disabledUI = container.querySelector(".jasmine-disabled"); + var disabledUI = container.querySelector('.jasmine-disabled'); expect(disabledUI.checked).toBe(false); }); - it("should be checked if hiding disabled", function() { + it('should be checked if hiding disabled', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), getContainer = function() { return container; }, @@ -738,43 +880,17 @@ describe("HtmlReporter", function() { } }); - env.configure({hideDisabled: true}); + env.configure({ hideDisabled: true }); reporter.initialize(); reporter.jasmineDone({}); - var disabledUI = container.querySelector(".jasmine-disabled"); + var disabledUI = container.querySelector('.jasmine-disabled'); expect(disabledUI.checked).toBe(true); }); - it("should not display specs that have been disabled", function() { + it('should not display specs that have been disabled', function() { var env = new jasmineUnderTest.Env(), container = document.createElement('div'), - getContainer = function() {return container;}, - reporter = new jasmineUnderTest.HtmlReporter({ - env: env, - getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } - }); - - env.configure({hideDisabled: true}); - reporter.initialize(); - reporter.specDone({ - id: 789, - status: "excluded", - fullName: "symbols should have titles", - passedExpectations: [], - failedExpectations: [] - }); - - var specEl = container.querySelector('.jasmine-symbol-summary li'); - expect(specEl.getAttribute("class")).toEqual("jasmine-excluded-no-display"); - }); - }); - describe("UI for running tests in random order", function() { - it("should be unchecked if not randomizing", function() { - var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), getContainer = function() { return container; }, @@ -789,17 +905,51 @@ describe("HtmlReporter", function() { } }); - env.configure({random: false}); + env.configure({ hideDisabled: true }); + reporter.initialize(); + reporter.specDone({ + id: 789, + status: 'excluded', + fullName: 'symbols should have titles', + passedExpectations: [], + failedExpectations: [] + }); + + var specEl = container.querySelector('.jasmine-symbol-summary li'); + expect(specEl.getAttribute('class')).toEqual( + 'jasmine-excluded-no-display' + ); + }); + }); + describe('UI for running tests in random order', function() { + it('should be unchecked if not randomizing', function() { + var env = new jasmineUnderTest.Env(), + container = document.createElement('div'), + getContainer = function() { + return container; + }, + reporter = new jasmineUnderTest.HtmlReporter({ + env: env, + getContainer: getContainer, + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } + }); + + env.configure({ random: false }); reporter.initialize(); reporter.jasmineDone({}); - var randomUI = container.querySelector(".jasmine-random"); + var randomUI = container.querySelector('.jasmine-random'); expect(randomUI.checked).toBe(false); }); - it("should be checked if randomizing", function() { + it('should be checked if randomizing', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), getContainer = function() { return container; }, @@ -814,17 +964,17 @@ describe("HtmlReporter", function() { } }); - env.configure({random: true}); + env.configure({ random: true }); reporter.initialize(); reporter.jasmineDone({}); - var randomUI = container.querySelector(".jasmine-random"); + var randomUI = container.querySelector('.jasmine-random'); expect(randomUI.checked).toBe(true); }); - it("should navigate and change the setting to on", function() { + it('should navigate and change the setting to on', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), navigateHandler = jasmine.createSpy('navigate'), getContainer = function() { return container; @@ -841,19 +991,19 @@ describe("HtmlReporter", function() { } }); - env.configure({random: false}); + env.configure({ random: false }); reporter.initialize(); reporter.jasmineDone({}); - var randomUI = container.querySelector(".jasmine-random"); + var randomUI = container.querySelector('.jasmine-random'); randomUI.click(); expect(navigateHandler).toHaveBeenCalledWith('random', true); }); - it("should navigate and change the setting to off", function() { + it('should navigate and change the setting to off', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), navigateHandler = jasmine.createSpy('navigate'), getContainer = function() { return container; @@ -870,32 +1020,32 @@ describe("HtmlReporter", function() { } }); - env.configure({random: true}); + env.configure({ random: true }); reporter.initialize(); reporter.jasmineDone({}); - var randomUI = container.querySelector(".jasmine-random"); + var randomUI = container.querySelector('.jasmine-random'); randomUI.click(); expect(navigateHandler).toHaveBeenCalledWith('random', false); }); - it("should show the seed bar if randomizing", function() { + it('should show the seed bar if randomizing', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { - return container; + container = document.createElement('div'), + getContainer = function() { + return container; + }, + reporter = new jasmineUnderTest.HtmlReporter({ + env: env, + getContainer: getContainer, + createElement: function() { + return document.createElement.apply(document, arguments); }, - reporter = new jasmineUnderTest.HtmlReporter({ - env: env, - getContainer: getContainer, - createElement: function() { - return document.createElement.apply(document, arguments); - }, - createTextNode: function() { - return document.createTextNode.apply(document, arguments); - } - }); + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } + }); reporter.initialize(); reporter.jasmineDone({ @@ -905,132 +1055,154 @@ describe("HtmlReporter", function() { } }); - var seedBar = container.querySelector(".jasmine-seed-bar"); + var seedBar = container.querySelector('.jasmine-seed-bar'); expect(seedBar.textContent).toBe(', randomized with seed 424242'); - var seedLink = container.querySelector(".jasmine-seed-bar a"); + var seedLink = container.querySelector('.jasmine-seed-bar a'); expect(seedLink.getAttribute('href')).toBe('?seed=424242'); }); - it("should not show the current seed bar if not randomizing", function() { + it('should not show the current seed bar if not randomizing', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { - return container; + container = document.createElement('div'), + getContainer = function() { + return container; + }, + reporter = new jasmineUnderTest.HtmlReporter({ + env: env, + getContainer: getContainer, + createElement: function() { + return document.createElement.apply(document, arguments); }, - reporter = new jasmineUnderTest.HtmlReporter({ - env: env, - getContainer: getContainer, - createElement: function() { - return document.createElement.apply(document, arguments); - }, - createTextNode: function() { - return document.createTextNode.apply(document, arguments); - } - }); + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } + }); reporter.initialize(); reporter.jasmineDone({}); - var seedBar = container.querySelector(".jasmine-seed-bar"); + var seedBar = container.querySelector('.jasmine-seed-bar'); expect(seedBar).toBeNull(); }); - it("should include non-spec query params in the jasmine-skipped link when present", function(){ + it('should include non-spec query params in the jasmine-skipped link when present', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), + container = document.createElement('div'), reporter = new jasmineUnderTest.HtmlReporter({ env: env, - getContainer: function() { return container; }, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); }, - addToExistingQueryString: function(key, value) { return "?foo=bar&" + key + "=" + value; } + getContainer: function() { + return container; + }, + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + }, + addToExistingQueryString: function(key, value) { + return '?foo=bar&' + key + '=' + value; + } }); reporter.initialize(); reporter.jasmineStarted({ totalSpecsDefined: 1 }); reporter.jasmineDone({ order: { random: true } }); - var skippedLink = container.querySelector(".jasmine-skipped a"); + var skippedLink = container.querySelector('.jasmine-skipped a'); expect(skippedLink.getAttribute('href')).toEqual('?foo=bar&spec='); }); }); - describe("and all specs pass", function() { - var env, container, reporter; + describe('and all specs pass', function() { + var env, container; beforeEach(function() { env = new jasmineUnderTest.Env(); - container = document.createElement("div"); - var getContainer = function() { return container; }, + container = document.createElement('div'); + var getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); reporter.jasmineStarted({ totalSpecsDefined: 2 }); reporter.specDone({ id: 123, - description: "with a spec", - fullName: "A Suite with a spec", - status: "passed", - passedExpectations: [{passed: true}], + description: 'with a spec', + fullName: 'A Suite with a spec', + status: 'passed', + passedExpectations: [{ passed: true }], failedExpectations: [] }); reporter.specDone({ id: 124, - description: "with another spec", - fullName: "A Suite inner suite with another spec", - status: "passed", - passedExpectations: [{passed: true}], + description: 'with another spec', + fullName: 'A Suite inner suite with another spec', + status: 'passed', + passedExpectations: [{ passed: true }], failedExpectations: [] }); reporter.jasmineDone({}); }); - it("reports the specs counts", function() { - var alertBars = container.querySelectorAll(".jasmine-alert .jasmine-bar"); + it('reports the specs counts', function() { + var alertBars = container.querySelectorAll( + '.jasmine-alert .jasmine-bar' + ); expect(alertBars.length).toEqual(1); expect(alertBars[0].innerHTML).toMatch(/2 specs, 0 failures/); }); - it("reports no failure details", function() { - var specFailure = container.querySelector(".jasmine-failures"); + it('reports no failure details', function() { + var specFailure = container.querySelector('.jasmine-failures'); expect(specFailure.childNodes.length).toEqual(0); }); - it("reports no pending specs", function() { - var alertBar = container.querySelector(".jasmine-alert .jasmine-bar"); + it('reports no pending specs', function() { + var alertBar = container.querySelector('.jasmine-alert .jasmine-bar'); expect(alertBar.innerHTML).not.toMatch(/pending spec[s]/); }); }); - describe("and there are excluded specs", function() { + describe('and there are excluded specs', function() { var env, container, reporter, reporterConfig, specStatus; beforeEach(function() { env = new jasmineUnderTest.Env(); - container = document.createElement("div"); + container = document.createElement('div'); reporterConfig = { env: env, - getContainer: function() { return container; }, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + getContainer: function() { + return container; + }, + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }; specStatus = { id: 123, - description: "with a excluded spec", - fullName: "A Suite with a excluded spec", - status: "excluded", + description: 'with a excluded spec', + fullName: 'A Suite with a excluded spec', + status: 'excluded', passedExpectations: [], failedExpectations: [] }; }); - describe("when the specs are not filtered", function() { + describe('when the specs are not filtered', function() { beforeEach(function() { reporterConfig.filterSpecs = false; reporter = new jasmineUnderTest.HtmlReporter(reporterConfig); @@ -1041,14 +1213,14 @@ describe("HtmlReporter", function() { reporter.jasmineDone({}); }); - it("shows the excluded spec in the spec list", function() { - var specList = container.querySelector(".jasmine-summary"); + it('shows the excluded spec in the spec list', function() { + var specList = container.querySelector('.jasmine-summary'); expect(specList.innerHTML).toContain('with a excluded spec'); }); }); - describe("when the specs are filtered", function() { + describe('when the specs are filtered', function() { beforeEach(function() { reporterConfig.filterSpecs = true; reporter = new jasmineUnderTest.HtmlReporter(reporterConfig); @@ -1060,108 +1232,131 @@ describe("HtmlReporter", function() { }); it("doesn't show the excluded spec in the spec list", function() { - var specList = container.querySelector(".jasmine-summary"); + var specList = container.querySelector('.jasmine-summary'); expect(specList.innerHTML).toEqual(''); }); }); }); - describe("and there are pending specs", function() { + describe('and there are pending specs', function() { var env, container, reporter; beforeEach(function() { env = new jasmineUnderTest.Env(); - container = document.createElement("div"); - var getContainer = function() { return container; }; + container = document.createElement('div'); + var getContainer = function() { + return container; + }; reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); reporter.jasmineStarted({ totalSpecsDefined: 1 }); var specStatus = { id: 123, - description: "with a spec", - fullName: "A Suite with a spec", - status: "pending", + description: 'with a spec', + fullName: 'A Suite with a spec', + status: 'pending', passedExpectations: [], failedExpectations: [], - pendingReason: "my custom pending reason" + pendingReason: 'my custom pending reason' }; reporter.specStarted(specStatus); reporter.specDone(specStatus); reporter.jasmineDone({}); }); - it("reports the pending specs count", function() { - var alertBar = container.querySelector(".jasmine-alert .jasmine-bar"); + it('reports the pending specs count', function() { + var alertBar = container.querySelector('.jasmine-alert .jasmine-bar'); - expect(alertBar.innerHTML).toMatch(/1 spec, 0 failures, 1 pending spec/); + expect(alertBar.innerHTML).toMatch( + /1 spec, 0 failures, 1 pending spec/ + ); }); - it("reports no failure details", function() { - var specFailure = container.querySelector(".jasmine-failures"); + it('reports no failure details', function() { + var specFailure = container.querySelector('.jasmine-failures'); expect(specFailure.childNodes.length).toEqual(0); }); - it("displays the custom pending reason", function() { - var pendingDetails = container.querySelector(".jasmine-summary .jasmine-pending"); + it('displays the custom pending reason', function() { + var pendingDetails = container.querySelector( + '.jasmine-summary .jasmine-pending' + ); - expect(pendingDetails.innerHTML).toContain("my custom pending reason"); + expect(pendingDetails.innerHTML).toContain('my custom pending reason'); }); }); - describe("and some tests fail", function() { + describe('and some tests fail', function() { var env, container, reporter; beforeEach(function() { env = new jasmineUnderTest.Env(); - container = document.createElement("div"); - var getContainer = function() { return container; }; + container = document.createElement('div'); + var getContainer = function() { + return container; + }; reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); }, - addToExistingQueryString: function(key, value) { return "?foo=bar&" + key + "=" + value; } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + }, + addToExistingQueryString: function(key, value) { + return '?foo=bar&' + key + '=' + value; + } }); reporter.initialize(); reporter.jasmineStarted({ totalSpecsDefined: 1 }); reporter.suiteStarted({ id: 1, - description: "A suite" + description: 'A suite' }); reporter.suiteStarted({ id: 2, - description: "inner suite" + description: 'inner suite' }); - var passingSpecResult = {id: 123, status: "passed", passedExpectations: [{passed: true}], failedExpectations: []}; + var passingSpecResult = { + id: 123, + status: 'passed', + passedExpectations: [{ passed: true }], + failedExpectations: [] + }; reporter.specStarted(passingSpecResult); reporter.specDone(passingSpecResult); var failingSpecResult = { id: 124, - status: "failed", - description: "a failing spec", - fullName: "a suite inner suite a failing spec", + status: 'failed', + description: 'a failing spec', + fullName: 'a suite inner suite a failing spec', passedExpectations: [], failedExpectations: [ { - message: "a failure message", - stack: "a stack trace" + message: 'a failure message', + stack: 'a stack trace' } ] }; var passingSuiteResult = { id: 1, - description: "A suite" + description: 'A suite' }; var failingSuiteResult = { id: 2, @@ -1178,52 +1373,64 @@ describe("HtmlReporter", function() { reporter.jasmineDone({}); }); - it("reports the specs counts", function() { - var alertBar = container.querySelector(".jasmine-alert .jasmine-bar"); + it('reports the specs counts', function() { + var alertBar = container.querySelector('.jasmine-alert .jasmine-bar'); expect(alertBar.innerHTML).toMatch(/2 specs, 2 failure/); }); - it("reports failure messages and stack traces", function() { - var specFailures = container.querySelector(".jasmine-failures"); + it('reports failure messages and stack traces', function() { + var specFailures = container.querySelector('.jasmine-failures'); expect(specFailures.childNodes.length).toEqual(2); var specFailure = specFailures.childNodes[0]; - expect(specFailure.getAttribute("class")).toMatch(/jasmine-failed/); - expect(specFailure.getAttribute("class")).toMatch(/jasmine-spec-detail/); + expect(specFailure.getAttribute('class')).toMatch(/jasmine-failed/); + expect(specFailure.getAttribute('class')).toMatch( + /jasmine-spec-detail/ + ); var specDiv = specFailure.childNodes[0]; - expect(specDiv.getAttribute("class")).toEqual("jasmine-description"); + expect(specDiv.getAttribute('class')).toEqual('jasmine-description'); var message = specFailure.childNodes[1].childNodes[0]; - expect(message.getAttribute("class")).toEqual("jasmine-result-message"); - expect(message.innerHTML).toEqual("a failure message"); + expect(message.getAttribute('class')).toEqual('jasmine-result-message'); + expect(message.innerHTML).toEqual('a failure message'); var stackTrace = specFailure.childNodes[1].childNodes[1]; - expect(stackTrace.getAttribute("class")).toEqual("jasmine-stack-trace"); - expect(stackTrace.innerHTML).toEqual("a stack trace"); + expect(stackTrace.getAttribute('class')).toEqual('jasmine-stack-trace'); + expect(stackTrace.innerHTML).toEqual('a stack trace'); var suiteFailure = specFailures.childNodes[0]; - expect(suiteFailure.getAttribute("class")).toMatch(/jasmine-failed/); - expect(suiteFailure.getAttribute("class")).toMatch(/jasmine-spec-detail/); + expect(suiteFailure.getAttribute('class')).toMatch(/jasmine-failed/); + expect(suiteFailure.getAttribute('class')).toMatch( + /jasmine-spec-detail/ + ); var suiteDiv = suiteFailure.childNodes[0]; - expect(suiteDiv.getAttribute("class")).toEqual("jasmine-description"); + expect(suiteDiv.getAttribute('class')).toEqual('jasmine-description'); var suiteMessage = suiteFailure.childNodes[1].childNodes[0]; - expect(suiteMessage.getAttribute("class")).toEqual("jasmine-result-message"); - expect(suiteMessage.innerHTML).toEqual("a failure message"); + expect(suiteMessage.getAttribute('class')).toEqual( + 'jasmine-result-message' + ); + expect(suiteMessage.innerHTML).toEqual('a failure message'); var suiteStackTrace = suiteFailure.childNodes[1].childNodes[1]; - expect(suiteStackTrace.getAttribute("class")).toEqual("jasmine-stack-trace"); - expect(suiteStackTrace.innerHTML).toEqual("a stack trace"); + expect(suiteStackTrace.getAttribute('class')).toEqual( + 'jasmine-stack-trace' + ); + expect(suiteStackTrace.innerHTML).toEqual('a stack trace'); }); it('provides links to focus on a failure and each containing suite', function() { - var description = container.querySelector('.jasmine-failures .jasmine-description'); + var description = container.querySelector( + '.jasmine-failures .jasmine-description' + ); var links = description.querySelectorAll('a'); - expect(description.textContent).toEqual('A suite > inner suite > a failing spec'); + expect(description.textContent).toEqual( + 'A suite > inner suite > a failing spec' + ); expect(links.length).toEqual(3); expect(links[0].textContent).toEqual('A suite'); @@ -1231,40 +1438,52 @@ describe("HtmlReporter", function() { expect(links[0].getAttribute('href')).toMatch(/\?foo=bar&spec=A suite/); expect(links[1].textContent).toEqual('inner suite'); - expect(links[1].getAttribute('href')).toMatch(/\?foo=bar&spec=A suite inner suite/); + expect(links[1].getAttribute('href')).toMatch( + /\?foo=bar&spec=A suite inner suite/ + ); expect(links[2].textContent).toEqual('a failing spec'); - expect(links[2].getAttribute('href')).toMatch(/\?foo=bar&spec=a suite inner suite a failing spec/); + expect(links[2].getAttribute('href')).toMatch( + /\?foo=bar&spec=a suite inner suite a failing spec/ + ); }); - it("allows switching between failure details and the spec summary", function() { - var menuBar = container.querySelectorAll(".jasmine-bar")[1]; + it('allows switching between failure details and the spec summary', function() { + var menuBar = container.querySelectorAll('.jasmine-bar')[1]; - expect(menuBar.getAttribute("class")).not.toMatch(/hidden/); + expect(menuBar.getAttribute('class')).not.toMatch(/hidden/); var link = menuBar.querySelector('a'); - expect(link.innerHTML).toEqual("Failures"); - expect(link.getAttribute("href")).toEqual("#"); + expect(link.innerHTML).toEqual('Failures'); + expect(link.getAttribute('href')).toEqual('#'); }); it("sets the reporter to 'Failures List' mode", function() { - var reporterNode = container.querySelector(".jasmine_html-reporter"); - expect(reporterNode.getAttribute("class")).toMatch("jasmine-failure-list"); + var reporterNode = container.querySelector('.jasmine_html-reporter'); + expect(reporterNode.getAttribute('class')).toMatch( + 'jasmine-failure-list' + ); }); }); }); - describe("The overall result bar", function() { + describe('The overall result bar', function() { describe("When the jasmineDone event's overallStatus is 'passed'", function() { - it("has class jasmine-passed", function() { + it('has class jasmine-passed', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); @@ -1275,21 +1494,27 @@ describe("HtmlReporter", function() { failedExpectations: [] }); - var alertBar = container.querySelector(".jasmine-overall-result"); - expect(alertBar).toHaveClass("jasmine-passed"); + var alertBar = container.querySelector('.jasmine-overall-result'); + expect(alertBar).toHaveClass('jasmine-passed'); }); }); describe("When the jasmineDone event's overallStatus is 'failed'", function() { - it("has class jasmine-failed", function() { + it('has class jasmine-failed', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); @@ -1300,21 +1525,27 @@ describe("HtmlReporter", function() { failedExpectations: [] }); - var alertBar = container.querySelector(".jasmine-overall-result"); - expect(alertBar).toHaveClass("jasmine-failed"); + var alertBar = container.querySelector('.jasmine-overall-result'); + expect(alertBar).toHaveClass('jasmine-failed'); }); }); describe("When the jasmineDone event's overallStatus is 'incomplete'", function() { - it("has class jasmine-incomplete", function() { + it('has class jasmine-incomplete', function() { var env = new jasmineUnderTest.Env(), - container = document.createElement("div"), - getContainer = function() { return container; }, + container = document.createElement('div'), + getContainer = function() { + return container; + }, reporter = new jasmineUnderTest.HtmlReporter({ env: env, getContainer: getContainer, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); } + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } }); reporter.initialize(); @@ -1326,9 +1557,9 @@ describe("HtmlReporter", function() { failedExpectations: [] }); - var alertBar = container.querySelector(".jasmine-overall-result"); - expect(alertBar).toHaveClass("jasmine-incomplete"); - expect(alertBar.textContent).toContain("Incomplete: because nope"); + var alertBar = container.querySelector('.jasmine-overall-result'); + expect(alertBar).toHaveClass('jasmine-incomplete'); + expect(alertBar.textContent).toContain('Incomplete: because nope'); }); }); }); diff --git a/spec/html/HtmlSpecFilterSpec.js b/spec/html/HtmlSpecFilterSpec.js index 8a3387c0..887ee07c 100644 --- a/spec/html/HtmlSpecFilterSpec.js +++ b/spec/html/HtmlSpecFilterSpec.js @@ -1,18 +1,19 @@ -describe("jasmineUnderTest.HtmlSpecFilter", function() { - - it("should match when no string is provided", function() { +describe('jasmineUnderTest.HtmlSpecFilter', function() { + it('should match when no string is provided', function() { var specFilter = new jasmineUnderTest.HtmlSpecFilter(); - expect(specFilter.matches("foo")).toBe(true); - expect(specFilter.matches("*bar")).toBe(true); + expect(specFilter.matches('foo')).toBe(true); + expect(specFilter.matches('*bar')).toBe(true); }); - it("should only match the provided string", function() { + it('should only match the provided string', function() { var specFilter = new jasmineUnderTest.HtmlSpecFilter({ - filterString: function() { return "foo"; } + filterString: function() { + return 'foo'; + } }); - expect(specFilter.matches("foo")).toBe(true); - expect(specFilter.matches("bar")).toBe(false); + expect(specFilter.matches('foo')).toBe(true); + expect(specFilter.matches('bar')).toBe(false); }); }); diff --git a/spec/html/MatchersHtmlSpec.js b/spec/html/MatchersHtmlSpec.js index 39660c2b..75256f9d 100644 --- a/spec/html/MatchersHtmlSpec.js +++ b/spec/html/MatchersHtmlSpec.js @@ -1,12 +1,11 @@ -describe("MatchersSpec - HTML Dependent", function () { +describe('MatchersSpec - HTML Dependent', function() { var env, spec; beforeEach(function() { env = new jasmineUnderTest.Env(); - var suite = env.describe("suite", function() { - spec = env.it("spec", function() { - }); + env.describe('suite', function() { + spec = env.it('spec', function() {}); }); spyOn(spec, 'addExpectationResult'); @@ -28,10 +27,10 @@ describe("MatchersSpec - HTML Dependent", function () { return spec.addExpectationResult.mostRecentCall.args[1]; } - xit("toEqual with DOM nodes", function() { + xit('toEqual with DOM nodes', function() { var nodeA = document.createElement('div'); var nodeB = document.createElement('div'); - expect((match(nodeA).toEqual(nodeA))).toPass(); - expect((match(nodeA).toEqual(nodeB))).toFail(); + expect(match(nodeA).toEqual(nodeA)).toPass(); + expect(match(nodeA).toEqual(nodeB)).toFail(); }); }); diff --git a/spec/html/PrettyPrintHtmlSpec.js b/spec/html/PrettyPrintHtmlSpec.js index b4eb1158..77bb2bac 100644 --- a/spec/html/PrettyPrintHtmlSpec.js +++ b/spec/html/PrettyPrintHtmlSpec.js @@ -1,17 +1,19 @@ -describe("jasmineUnderTest.pp (HTML Dependent)", function () { - it("should stringify non-element HTML nodes properly", function() { - var sampleNode = document.createTextNode(""); - expect(jasmineUnderTest.pp(sampleNode)).toEqual("HTMLNode"); - expect(jasmineUnderTest.pp({foo: sampleNode})).toEqual("Object({ foo: HTMLNode })"); +describe('jasmineUnderTest.pp (HTML Dependent)', function() { + it('should stringify non-element HTML nodes properly', function() { + var sampleNode = document.createTextNode(''); + expect(jasmineUnderTest.pp(sampleNode)).toEqual('HTMLNode'); + expect(jasmineUnderTest.pp({ foo: sampleNode })).toEqual( + 'Object({ foo: HTMLNode })' + ); }); - it("should stringify empty HTML elements as their opening tags", function () { + it('should stringify empty HTML elements as their opening tags', function() { var simple = document.createElement('div'); simple.className = 'foo'; expect(jasmineUnderTest.pp(simple)).toEqual('
'); }); - it("should stringify non-empty HTML elements as tags with placeholders", function() { + it('should stringify non-empty HTML elements as tags with placeholders', function() { var nonEmpty = document.createElement('div'); nonEmpty.className = 'foo'; nonEmpty.innerHTML = '

Irrelevant

'; @@ -19,14 +21,20 @@ describe("jasmineUnderTest.pp (HTML Dependent)", function () { }); it("should print Firefox's wrapped native objects correctly", function() { - if(jasmine.getEnv().firefoxVersion) { - try { new CustomEvent(); } catch(e) { var err = e; }; + if (jasmine.getEnv().firefoxVersion) { + try { + new CustomEvent(); + } catch (e) { + var err = e; + } // Different versions of FF produce different error messages. - expect(jasmineUnderTest.pp(err)).toMatch(/Not enough arguments|CustomEvent requires at least 1 argument, but only 0 were passed/); + expect(jasmineUnderTest.pp(err)).toMatch( + /Not enough arguments|CustomEvent requires at least 1 argument, but only 0 were passed/ + ); } }); - it("should stringify HTML element with text and attributes", function() { + it('should stringify HTML element with text and attributes', function() { var el = document.createElement('div'); el.setAttribute('things', 'foo'); el.innerHTML = 'foo'; diff --git a/spec/html/QueryStringSpec.js b/spec/html/QueryStringSpec.js index 2b9c8cd6..de2f5721 100644 --- a/spec/html/QueryStringSpec.js +++ b/spec/html/QueryStringSpec.js @@ -1,28 +1,31 @@ -describe("QueryString", function() { - - describe("#navigateWithNewParam", function() { - it("sets the query string to include the given key/value pair", function() { +describe('QueryString', function() { + describe('#navigateWithNewParam', function() { + it('sets the query string to include the given key/value pair', function() { var windowLocation = { - search: "" + search: '' }, queryString = new jasmineUnderTest.QueryString({ - getWindowLocation: function() { return windowLocation } + getWindowLocation: function() { + return windowLocation; + } }); - queryString.navigateWithNewParam("foo", "bar baz"); + queryString.navigateWithNewParam('foo', 'bar baz'); expect(windowLocation.search).toMatch(/foo=bar%20baz/); }); - it("leaves existing params alone", function() { + it('leaves existing params alone', function() { var windowLocation = { - search: "?foo=bar" - }, - queryString = new jasmineUnderTest.QueryString({ - getWindowLocation: function() { return windowLocation } - }); + search: '?foo=bar' + }, + queryString = new jasmineUnderTest.QueryString({ + getWindowLocation: function() { + return windowLocation; + } + }); - queryString.navigateWithNewParam("baz", "quux"); + queryString.navigateWithNewParam('baz', 'quux'); expect(windowLocation.search).toMatch(/foo=bar/); expect(windowLocation.search).toMatch(/baz=quux/); @@ -30,43 +33,48 @@ describe("QueryString", function() { }); describe('#fullStringWithNewParam', function() { - it("gets the query string including the given key/value pair", function() { + it('gets the query string including the given key/value pair', function() { var windowLocation = { - search: "?foo=bar" - }, - queryString = new jasmineUnderTest.QueryString({ - getWindowLocation: function() { return windowLocation } - }); + search: '?foo=bar' + }, + queryString = new jasmineUnderTest.QueryString({ + getWindowLocation: function() { + return windowLocation; + } + }); - var result = queryString.fullStringWithNewParam("baz", "quux"); + var result = queryString.fullStringWithNewParam('baz', 'quux'); expect(result).toMatch(/foo=bar/); expect(result).toMatch(/baz=quux/); }); }); - describe("#getParam", function() { - - it("returns the value of the requested key", function() { + describe('#getParam', function() { + it('returns the value of the requested key', function() { var windowLocation = { - search: "?baz=quux%20corge" + search: '?baz=quux%20corge' }, queryString = new jasmineUnderTest.QueryString({ - getWindowLocation: function() { return windowLocation } + getWindowLocation: function() { + return windowLocation; + } }); - expect(queryString.getParam("baz")).toEqual("quux corge"); + expect(queryString.getParam('baz')).toEqual('quux corge'); }); - it("returns null if the key is not present", function() { + it('returns null if the key is not present', function() { var windowLocation = { - search: "" + search: '' }, queryString = new jasmineUnderTest.QueryString({ - getWindowLocation: function() { return windowLocation } + getWindowLocation: function() { + return windowLocation; + } }); - expect(queryString.getParam("baz")).toBeFalsy(); + expect(queryString.getParam('baz')).toBeFalsy(); }); }); }); diff --git a/spec/html/ResultsNodeSpec.js b/spec/html/ResultsNodeSpec.js index 34ed589d..0a57a8fc 100644 --- a/spec/html/ResultsNodeSpec.js +++ b/spec/html/ResultsNodeSpec.js @@ -1,61 +1,61 @@ -describe("ResultsNode", function() { - it("wraps a result", function() { +describe('ResultsNode', function() { + it('wraps a result', function() { var fakeResult = { id: 123, - message: "foo" + message: 'foo' }, - node = new jasmineUnderTest.ResultsNode(fakeResult, "suite", null); + node = new jasmineUnderTest.ResultsNode(fakeResult, 'suite', null); expect(node.result).toBe(fakeResult); - expect(node.type).toEqual("suite"); + expect(node.type).toEqual('suite'); }); - it("can add children with a type", function() { + it('can add children with a type', function() { var fakeResult = { id: 123, - message: "foo" + message: 'foo' }, fakeChildResult = { id: 456, - message: "bar" + message: 'bar' }, - node = new jasmineUnderTest.ResultsNode(fakeResult, "suite", null); + node = new jasmineUnderTest.ResultsNode(fakeResult, 'suite', null); - node.addChild(fakeChildResult, "spec"); + node.addChild(fakeChildResult, 'spec'); expect(node.children.length).toEqual(1); expect(node.children[0].result).toEqual(fakeChildResult); - expect(node.children[0].type).toEqual("spec"); + expect(node.children[0].type).toEqual('spec'); }); - it("has a pointer back to its parent ResultNode", function() { + it('has a pointer back to its parent ResultNode', function() { var fakeResult = { id: 123, - message: "foo" + message: 'foo' }, fakeChildResult = { id: 456, - message: "bar" + message: 'bar' }, - node = new jasmineUnderTest.ResultsNode(fakeResult, "suite", null); + node = new jasmineUnderTest.ResultsNode(fakeResult, 'suite', null); - node.addChild(fakeChildResult, "spec"); + node.addChild(fakeChildResult, 'spec'); expect(node.children[0].parent).toBe(node); }); - it("can provide the most recent child", function() { + it('can provide the most recent child', function() { var fakeResult = { id: 123, - message: "foo" + message: 'foo' }, fakeChildResult = { id: 456, - message: "bar" + message: 'bar' }, - node = new jasmineUnderTest.ResultsNode(fakeResult, "suite", null); + node = new jasmineUnderTest.ResultsNode(fakeResult, 'suite', null); - node.addChild(fakeChildResult, "spec"); + node.addChild(fakeChildResult, 'spec'); expect(node.last()).toBe(node.children[node.children.length - 1]); }); diff --git a/spec/html/SpyRegistryHtmlSpec.js b/spec/html/SpyRegistryHtmlSpec.js index c51308b8..e43e9eeb 100644 --- a/spec/html/SpyRegistryHtmlSpec.js +++ b/spec/html/SpyRegistryHtmlSpec.js @@ -8,7 +8,9 @@ describe('Spy Registry browser-specific behavior', function() { var spies = [], spyRegistry = new jasmineUnderTest.SpyRegistry({ - currentSpies: function() { return spies; }, + currentSpies: function() { + return spies; + }, createSpy: createSpy, global: window }), @@ -28,7 +30,7 @@ describe('Spy Registry browser-specific behavior', function() { try { descriptor = Object.getOwnPropertyDescriptor(window, 'onerror'); - } catch(e) { + } catch (e) { // IE 8 doesn't support `definePropery` on non-DOM nodes } diff --git a/spec/npmPackage/npmPackageSpec.js b/spec/npmPackage/npmPackageSpec.js index 3460f539..5248d88c 100644 --- a/spec/npmPackage/npmPackageSpec.js +++ b/spec/npmPackage/npmPackageSpec.js @@ -1,19 +1,24 @@ describe('npm package', function() { var path = require('path'), - temp = require('temp').track(), - fs = require('fs'); + temp = require('temp').track(), + fs = require('fs'); beforeAll(function() { var shell = require('shelljs'), - pack = shell.exec('npm pack', { silent: true}); + pack = shell.exec('npm pack', { silent: true }); this.tarball = pack.stdout.split('\n')[0]; this.tmpDir = temp.mkdirSync(); // automatically deleted on exit - var untar = shell.exec('tar -xzf ' + this.tarball + ' -C ' + this.tmpDir, { silent: true }); + var untar = shell.exec('tar -xzf ' + this.tarball + ' -C ' + this.tmpDir, { + silent: true + }); expect(untar.code).toBe(0); - this.packagedCore = require(path.join(this.tmpDir, 'package/lib/jasmine-core.js')); + this.packagedCore = require(path.join( + this.tmpDir, + 'package/lib/jasmine-core.js' + )); }); beforeEach(function() { @@ -32,25 +37,19 @@ describe('npm package', function() { }); afterAll(function() { - var cleanup = function (parent, fileOrFolder) { - var fullPath = path.join(parent, fileOrFolder); - if (fs.statSync(fullPath).isFile()) { - fs.unlinkSync(fullPath); - } else { - fs.readdirSync(fullPath).forEach(cleanup.bind(null, fullPath)); - fs.rmdirSync(fullPath); - } - }; - fs.unlinkSync(this.tarball); }); it('has a root path', function() { - expect(this.packagedCore.files.path).toEqual(fs.realpathSync(path.resolve(this.tmpDir, 'package/lib/jasmine-core'))); + expect(this.packagedCore.files.path).toEqual( + fs.realpathSync(path.resolve(this.tmpDir, 'package/lib/jasmine-core')) + ); }); it('has a bootDir', function() { - expect(this.packagedCore.files.bootDir).toEqual(fs.realpathSync(path.resolve(this.tmpDir, 'package/lib/jasmine-core'))); + expect(this.packagedCore.files.bootDir).toEqual( + fs.realpathSync(path.resolve(this.tmpDir, 'package/lib/jasmine-core')) + ); }); it('has jsFiles', function() { @@ -91,7 +90,9 @@ describe('npm package', function() { }); it('has an imagesDir', function() { - expect(this.packagedCore.files.imagesDir).toEqual(fs.realpathSync(path.resolve(this.tmpDir, 'package/images'))); + expect(this.packagedCore.files.imagesDir).toEqual( + fs.realpathSync(path.resolve(this.tmpDir, 'package/images')) + ); var images = fs.readdirSync(path.resolve(this.tmpDir, 'package/images')); expect(images).toContain('jasmine-horizontal.png'); diff --git a/spec/performance/large_object_test.js b/spec/performance/large_object_test.js index a59bb105..65b28863 100644 --- a/spec/performance/large_object_test.js +++ b/spec/performance/large_object_test.js @@ -1,4 +1,4 @@ -describe('Printing a big object', function(){ +describe('Printing a big object', function() { var bigObject; function rand(upper) { return Math.round(upper * Math.random()); @@ -11,26 +11,24 @@ describe('Printing a big object', function(){ var decide = rand(2); switch (decide) { case 0: - object["cycle" + i] = object; - break; + object['cycle' + i] = object; + break; case 1: - object["number" + i] = rand(100); - break; + object['number' + i] = rand(100); + break; case 2: if (level < 3) { - object["nesting" + i] = generateObject(level + 1); - } - break; + object['nesting' + i] = generateObject(level + 1); + } + break; } - } return object; } - it('takes a reasonable amount of time', function(){ + it('takes a reasonable amount of time', function() { bigObject = generateObject(0); expect(jasmineUnderTest.pp(bigObject)).toMatch(/cycle/); }); }); - diff --git a/spec/performance/performance_test.js b/spec/performance/performance_test.js index 0c97d20c..a9139bdd 100644 --- a/spec/performance/performance_test.js +++ b/spec/performance/performance_test.js @@ -1,9 +1,9 @@ -describe("performance", function() { +describe('performance', function() { for (var i = 0; i < 10000; i++) { - it("should pass", function() { + it('should pass', function() { expect(true).toBe(true); }); - it("should fail", function() { + it('should fail', function() { expect(true).toBe(false); }); } diff --git a/src/core/CallTracker.js b/src/core/CallTracker.js index 9a26b38b..e856d2ad 100644 --- a/src/core/CallTracker.js +++ b/src/core/CallTracker.js @@ -1,5 +1,4 @@ getJasmineRequireObj().CallTracker = function(j$) { - /** * @namespace Spy#calls */ @@ -8,7 +7,7 @@ getJasmineRequireObj().CallTracker = function(j$) { var opts = {}; this.track = function(context) { - if(opts.cloneArgs) { + if (opts.cloneArgs) { context.args = j$.util.cloneArgs(context.args); } calls.push(context); @@ -64,7 +63,7 @@ getJasmineRequireObj().CallTracker = function(j$) { */ this.allArgs = function() { var callArgs = []; - for(var i = 0; i < calls.length; i++) { + for (var i = 0; i < calls.length; i++) { callArgs.push(calls[i].args); } @@ -108,7 +107,6 @@ getJasmineRequireObj().CallTracker = function(j$) { this.saveArgumentsByValue = function() { opts.cloneArgs = true; }; - } return CallTracker; diff --git a/src/core/ClearStack.js b/src/core/ClearStack.js index df5d8753..b80de2b8 100644 --- a/src/core/ClearStack.js +++ b/src/core/ClearStack.js @@ -3,8 +3,8 @@ getJasmineRequireObj().clearStack = function(j$) { function messageChannelImpl(global, setTimeout) { var channel = new global.MessageChannel(), - head = {}, - tail = head; + head = {}, + tail = head; var taskRunning = false; channel.port1.onmessage = function() { @@ -42,7 +42,7 @@ getJasmineRequireObj().clearStack = function(j$) { var currentCallCount = 0; var realSetTimeout = global.setTimeout; var setTimeoutImpl = function clearStack(fn) { - Function.prototype.apply.apply(realSetTimeout, [global, [fn, 0]]); + Function.prototype.apply.apply(realSetTimeout, [global, [fn, 0]]); }; if (j$.isFunction_(global.setImmediate)) { diff --git a/src/core/Clock.js b/src/core/Clock.js index f80244e0..370eca18 100644 --- a/src/core/Clock.js +++ b/src/core/Clock.js @@ -1,7 +1,9 @@ getJasmineRequireObj().Clock = function() { - /* global process */ - var NODE_JS = typeof process !== 'undefined' && process.versions && typeof process.versions.node === 'string'; + var NODE_JS = + typeof process !== 'undefined' && + process.versions && + typeof process.versions.node === 'string'; /** * _Note:_ Do not construct this directly, Jasmine will make one during booting. You can get the current clock with {@link jasmine.clock}. @@ -35,8 +37,10 @@ getJasmineRequireObj().Clock = function() { * @return {Clock} */ self.install = function() { - if(!originalTimingFunctionsIntact()) { - throw new Error('Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?'); + if (!originalTimingFunctionsIntact()) { + throw new Error( + 'Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?' + ); } replace(global, fakeTimingFunctions); timer = fakeTimingFunctions; @@ -88,11 +92,17 @@ getJasmineRequireObj().Clock = function() { }; self.setTimeout = function(fn, delay, params) { - return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]); + return Function.prototype.apply.apply(timer.setTimeout, [ + global, + arguments + ]); }; self.setInterval = function(fn, delay, params) { - return Function.prototype.apply.apply(timer.setInterval, [global, arguments]); + return Function.prototype.apply.apply(timer.setInterval, [ + global, + arguments + ]); }; self.clearTimeout = function(id) { @@ -111,19 +121,25 @@ getJasmineRequireObj().Clock = function() { */ self.tick = function(millis) { if (installed) { - delayedFunctionScheduler.tick(millis, function(millis) { mockDate.tick(millis); }); + delayedFunctionScheduler.tick(millis, function(millis) { + mockDate.tick(millis); + }); } else { - throw new Error('Mock clock is not installed, use jasmine.clock().install()'); + throw new Error( + 'Mock clock is not installed, use jasmine.clock().install()' + ); } }; return self; function originalTimingFunctionsIntact() { - return global.setTimeout === realTimingFunctions.setTimeout && + return ( + global.setTimeout === realTimingFunctions.setTimeout && global.clearTimeout === realTimingFunctions.clearTimeout && global.setInterval === realTimingFunctions.setInterval && - global.clearInterval === realTimingFunctions.clearInterval; + global.clearInterval === realTimingFunctions.clearInterval + ); } function replace(dest, source) { @@ -134,12 +150,22 @@ getJasmineRequireObj().Clock = function() { function setTimeout(fn, delay) { if (!NODE_JS) { - return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2)); + return delayedFunctionScheduler.scheduleFunction( + fn, + delay, + argSlice(arguments, 2) + ); } var timeout = new FakeTimeout(); - delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2), false, timeout); + delayedFunctionScheduler.scheduleFunction( + fn, + delay, + argSlice(arguments, 2), + false, + timeout + ); return timeout; } @@ -150,12 +176,23 @@ getJasmineRequireObj().Clock = function() { function setInterval(fn, interval) { if (!NODE_JS) { - return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true); + return delayedFunctionScheduler.scheduleFunction( + fn, + interval, + argSlice(arguments, 2), + true + ); } var timeout = new FakeTimeout(); - delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true, timeout); + delayedFunctionScheduler.scheduleFunction( + fn, + interval, + argSlice(arguments, 2), + true, + timeout + ); return timeout; } @@ -174,11 +211,11 @@ getJasmineRequireObj().Clock = function() { */ function FakeTimeout() {} - FakeTimeout.prototype.ref = function () { + FakeTimeout.prototype.ref = function() { return this; }; - FakeTimeout.prototype.unref = function () { + FakeTimeout.prototype.unref = function() { return this; }; diff --git a/src/core/DelayedFunctionScheduler.js b/src/core/DelayedFunctionScheduler.js index f41e7ada..eb84c48a 100644 --- a/src/core/DelayedFunctionScheduler.js +++ b/src/core/DelayedFunctionScheduler.js @@ -15,11 +15,20 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { currentTime = endTime; }; - self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) { + self.scheduleFunction = function( + funcToCall, + millis, + params, + recurring, + timeoutKey, + runAtMillis + ) { var f; - if (typeof(funcToCall) === 'string') { + if (typeof funcToCall === 'string') { /* jshint evil: true */ - f = function() { return eval(funcToCall); }; + f = function() { + return eval(funcToCall); + }; /* jshint evil: false */ } else { f = funcToCall; @@ -27,7 +36,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { millis = millis || 0; timeoutKey = timeoutKey || ++delayedFnCount; - runAtMillis = runAtMillis || (currentTime + millis); + runAtMillis = runAtMillis || currentTime + millis; var funcToSchedule = { runAtMillis: runAtMillis, @@ -43,7 +52,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { } else { scheduledFunctions[runAtMillis] = [funcToSchedule]; scheduledLookup.push(runAtMillis); - scheduledLookup.sort(function (a, b) { + scheduledLookup.sort(function(a, b) { return a - b; }); } @@ -56,7 +65,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { for (var runAtMillis in scheduledFunctions) { var funcs = scheduledFunctions[runAtMillis]; - var i = indexOfFirstToPass(funcs, function (func) { + var i = indexOfFirstToPass(funcs, function(func) { return func.timeoutKey === timeoutKey; }); @@ -92,7 +101,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { function deleteFromLookup(key) { var value = Number(key); - var i = indexOfFirstToPass(scheduledLookup, function (millis) { + var i = indexOfFirstToPass(scheduledLookup, function(millis) { return millis === value; }); @@ -102,12 +111,14 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { } function reschedule(scheduledFn) { - self.scheduleFunction(scheduledFn.funcToCall, + self.scheduleFunction( + scheduledFn.funcToCall, scheduledFn.millis, scheduledFn.params, true, scheduledFn.timeoutKey, - scheduledFn.runAtMillis + scheduledFn.millis); + scheduledFn.runAtMillis + scheduledFn.millis + ); } function forEachFunction(funcsToRun, callback) { @@ -148,11 +159,13 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { funcToRun.funcToCall.apply(null, funcToRun.params || []); }); deletedKeys = []; - } while (scheduledLookup.length > 0 && - // checking first if we're out of time prevents setTimeout(0) - // scheduled in a funcToRun from forcing an extra iteration - currentTime !== endTime && - scheduledLookup[0] <= endTime); + } while ( + scheduledLookup.length > 0 && + // checking first if we're out of time prevents setTimeout(0) + // scheduled in a funcToRun from forcing an extra iteration + currentTime !== endTime && + scheduledLookup[0] <= endTime + ); // ran out of functions to call, but still time left on the clock if (currentTime !== endTime) { diff --git a/src/core/Env.js b/src/core/Env.js index b0c09040..18924dcd 100644 --- a/src/core/Env.js +++ b/src/core/Env.js @@ -17,7 +17,13 @@ getJasmineRequireObj().Env = function(j$) { var realSetTimeout = global.setTimeout; var realClearTimeout = global.clearTimeout; var clearStack = j$.getClearStack(global); - this.clock = new j$.Clock(global, function () { return new j$.DelayedFunctionScheduler(); }, new j$.MockDate(global)); + this.clock = new j$.Clock( + global, + function() { + return new j$.DelayedFunctionScheduler(); + }, + new j$.MockDate(global) + ); var runnableResources = {}; @@ -110,7 +116,13 @@ getJasmineRequireObj().Env = function(j$) { if (!options.suppressLoadErrors) { installGlobalErrors(); - globalErrors.pushListener(function(message, filename, lineno, colNo, err) { + globalErrors.pushListener(function( + message, + filename, + lineno, + colNo, + err + ) { topSuite.result.failedExpectations.push({ passed: false, globalErrorType: 'load', @@ -154,11 +166,15 @@ getJasmineRequireObj().Env = function(j$) { } if (configuration.hasOwnProperty('Promise')) { - if (typeof configuration.Promise.resolve === 'function' && - typeof configuration.Promise.reject === 'function') { + if ( + typeof configuration.Promise.resolve === 'function' && + typeof configuration.Promise.reject === 'function' + ) { customPromise = configuration.Promise; } else { - throw new Error('Custom promise library missing `resolve`/`reject` functions'); + throw new Error( + 'Custom promise library missing `resolve`/`reject` functions' + ); } } }; @@ -179,34 +195,47 @@ getJasmineRequireObj().Env = function(j$) { Object.defineProperty(this, 'specFilter', { get: function() { - self.deprecated('Getting specFilter directly from Env is deprecated and will be removed in a future version of Jasmine, please check the specFilter option from `configuration`'); + self.deprecated( + 'Getting specFilter directly from Env is deprecated and will be removed in a future version of Jasmine, please check the specFilter option from `configuration`' + ); return config.specFilter; }, set: function(val) { - self.deprecated('Setting specFilter directly on Env is deprecated and will be removed in a future version of Jasmine, please use the specFilter option in `configure`'); + self.deprecated( + 'Setting specFilter directly on Env is deprecated and will be removed in a future version of Jasmine, please use the specFilter option in `configure`' + ); config.specFilter = val; } }); this.addSpyStrategy = function(name, fn) { - if(!currentRunnable()) { - throw new Error('Custom spy strategies must be added in a before function or a spec'); + if (!currentRunnable()) { + throw new Error( + 'Custom spy strategies must be added in a before function or a spec' + ); } runnableResources[currentRunnable().id].customSpyStrategies[name] = fn; }; this.addCustomEqualityTester = function(tester) { - if(!currentRunnable()) { - throw new Error('Custom Equalities must be added in a before function or a spec'); + if (!currentRunnable()) { + throw new Error( + 'Custom Equalities must be added in a before function or a spec' + ); } - runnableResources[currentRunnable().id].customEqualityTesters.push(tester); + runnableResources[currentRunnable().id].customEqualityTesters.push( + tester + ); }; this.addMatchers = function(matchersToAdd) { - if(!currentRunnable()) { - throw new Error('Matchers must be added in a before function or a spec'); + if (!currentRunnable()) { + throw new Error( + 'Matchers must be added in a before function or a spec' + ); } - var customMatchers = runnableResources[currentRunnable().id].customMatchers; + var customMatchers = + runnableResources[currentRunnable().id].customMatchers; for (var matcherName in matchersToAdd) { customMatchers[matcherName] = matchersToAdd[matcherName]; } @@ -253,19 +282,28 @@ getJasmineRequireObj().Env = function(j$) { }; var defaultResourcesForRunnable = function(id, parentRunnableId) { - var resources = {spies: [], customEqualityTesters: [], customMatchers: {}, customSpyStrategies: {}}; + var resources = { + spies: [], + customEqualityTesters: [], + customMatchers: {}, + customSpyStrategies: {} + }; - if(runnableResources[parentRunnableId]) { - resources.customEqualityTesters = j$.util.clone(runnableResources[parentRunnableId].customEqualityTesters); - resources.customMatchers = j$.util.clone(runnableResources[parentRunnableId].customMatchers); + if (runnableResources[parentRunnableId]) { + resources.customEqualityTesters = j$.util.clone( + runnableResources[parentRunnableId].customEqualityTesters + ); + resources.customMatchers = j$.util.clone( + runnableResources[parentRunnableId].customMatchers + ); } runnableResources[id] = resources; }; var clearResourcesForRunnable = function(id) { - spyRegistry.clearSpies(); - delete runnableResources[id]; + spyRegistry.clearSpies(); + delete runnableResources[id]; }; var beforeAndAfterFns = function(suite) { @@ -273,7 +311,7 @@ getJasmineRequireObj().Env = function(j$) { var befores = [], afters = []; - while(suite) { + while (suite) { befores = befores.concat(suite.beforeFns); afters = afters.concat(suite.afterFns); @@ -289,7 +327,7 @@ getJasmineRequireObj().Env = function(j$) { var getSpecName = function(spec, suite) { var fullName = [spec.description], - suiteFullName = suite.getFullName(); + suiteFullName = suite.getFullName(); if (suiteFullName !== '') { fullName.unshift(suiteFullName); @@ -299,13 +337,13 @@ getJasmineRequireObj().Env = function(j$) { // TODO: we may just be able to pass in the fn instead of wrapping here var buildExpectationResult = j$.buildExpectationResult, - exceptionFormatter = new j$.ExceptionFormatter(), - expectationResultFactory = function(attrs) { - attrs.messageFormatter = exceptionFormatter.message; - attrs.stackFormatter = exceptionFormatter.stack; + exceptionFormatter = new j$.ExceptionFormatter(), + expectationResultFactory = function(attrs) { + attrs.messageFormatter = exceptionFormatter.message; + attrs.stackFormatter = exceptionFormatter.stack; - return buildExpectationResult(attrs); - }; + return buildExpectationResult(attrs); + }; /** * Sets whether Jasmine should throw an Error when an expectation fails. @@ -316,12 +354,16 @@ getJasmineRequireObj().Env = function(j$) { * @deprecated Use the `oneFailurePerSpec` option with {@link Env#configure} */ this.throwOnExpectationFailure = function(value) { - this.deprecated('Setting throwOnExpectationFailure directly on Env is deprecated and will be removed in a future version of Jasmine, please use the oneFailurePerSpec option in `configure`'); - this.configure({oneFailurePerSpec: !!value}); + this.deprecated( + 'Setting throwOnExpectationFailure directly on Env is deprecated and will be removed in a future version of Jasmine, please use the oneFailurePerSpec option in `configure`' + ); + this.configure({ oneFailurePerSpec: !!value }); }; this.throwingExpectationFailures = function() { - this.deprecated('Getting throwingExpectationFailures directly from Env is deprecated and will be removed in a future version of Jasmine, please check the oneFailurePerSpec option from `configuration`'); + this.deprecated( + 'Getting throwingExpectationFailures directly from Env is deprecated and will be removed in a future version of Jasmine, please check the oneFailurePerSpec option from `configuration`' + ); return config.oneFailurePerSpec; }; @@ -333,12 +375,16 @@ getJasmineRequireObj().Env = function(j$) { * @deprecated Use the `failFast` option with {@link Env#configure} */ this.stopOnSpecFailure = function(value) { - this.deprecated('Setting stopOnSpecFailure directly is deprecated and will be removed in a future version of Jasmine, please use the failFast option in `configure`'); - this.configure({failFast: !!value}); + this.deprecated( + 'Setting stopOnSpecFailure directly is deprecated and will be removed in a future version of Jasmine, please use the failFast option in `configure`' + ); + this.configure({ failFast: !!value }); }; this.stoppingOnSpecFailure = function() { - this.deprecated('Getting stoppingOnSpecFailure directly from Env is deprecated and will be removed in a future version of Jasmine, please check the failFast option from `configuration`'); + this.deprecated( + 'Getting stoppingOnSpecFailure directly from Env is deprecated and will be removed in a future version of Jasmine, please check the failFast option from `configuration`' + ); return config.failFast; }; @@ -350,12 +396,16 @@ getJasmineRequireObj().Env = function(j$) { * @deprecated Use the `random` option with {@link Env#configure} */ this.randomizeTests = function(value) { - this.deprecated('Setting randomizeTests directly is deprecated and will be removed in a future version of Jasmine, please use the random option in `configure`'); + this.deprecated( + 'Setting randomizeTests directly is deprecated and will be removed in a future version of Jasmine, please use the random option in `configure`' + ); config.random = !!value; }; this.randomTests = function() { - this.deprecated('Getting randomTests directly from Env is deprecated and will be removed in a future version of Jasmine, please check the random option from `configuration`'); + this.deprecated( + 'Getting randomTests directly from Env is deprecated and will be removed in a future version of Jasmine, please check the random option from `configuration`' + ); return config.random; }; @@ -367,7 +417,9 @@ getJasmineRequireObj().Env = function(j$) { * @deprecated Use the `seed` option with {@link Env#configure} */ this.seed = function(value) { - this.deprecated('Setting seed directly is deprecated and will be removed in a future version of Jasmine, please use the seed option in `configure`'); + this.deprecated( + 'Setting seed directly is deprecated and will be removed in a future version of Jasmine, please use the seed option in `configure`' + ); if (value) { config.seed = value; } @@ -375,7 +427,9 @@ getJasmineRequireObj().Env = function(j$) { }; this.hidingDisabled = function(value) { - this.deprecated('Getting hidingDisabled directly from Env is deprecated and will be removed in a future version of Jasmine, please check the hideDisabled option from `configuration`'); + this.deprecated( + 'Getting hidingDisabled directly from Env is deprecated and will be removed in a future version of Jasmine, please check the hideDisabled option from `configuration`' + ); return config.hideDisabled; }; @@ -384,14 +438,19 @@ getJasmineRequireObj().Env = function(j$) { * @function */ this.hideDisabled = function(value) { - this.deprecated('Setting hideDisabled directly is deprecated and will be removed in a future version of Jasmine, please use the hideDisabled option in `configure`'); + this.deprecated( + 'Setting hideDisabled directly is deprecated and will be removed in a future version of Jasmine, please use the hideDisabled option in `configure`' + ); config.hideDisabled = !!value; }; this.deprecated = function(deprecation) { var runnable = currentRunnable() || topSuite; runnable.addDeprecationWarning(deprecation); - if(typeof console !== 'undefined' && typeof console.error === 'function') { + if ( + typeof console !== 'undefined' && + typeof console.error === 'function' + ) { console.error('DEPRECATION:', deprecation); } }; @@ -404,13 +463,18 @@ getJasmineRequireObj().Env = function(j$) { failFast = config.failFast; } options.clearStack = options.clearStack || clearStack; - options.timeout = {setTimeout: realSetTimeout, clearTimeout: realClearTimeout}; + options.timeout = { + setTimeout: realSetTimeout, + clearTimeout: realClearTimeout + }; options.fail = self.fail; options.globalErrors = globalErrors; options.completeOnFirstError = failFast; - options.onException = options.onException || function(e) { - (currentRunnable() || topSuite).onException(e); - }; + options.onException = + options.onException || + function(e) { + (currentRunnable() || topSuite).onException(e); + }; options.deprecated = self.deprecated; new j$.QueueRunner(options).execute(args); @@ -436,78 +500,80 @@ getJasmineRequireObj().Env = function(j$) { * @interface Reporter * @see custom_reporter */ - var reporter = new j$.ReportDispatcher([ - /** - * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. - * @function - * @name Reporter#jasmineStarted - * @param {JasmineStartedInfo} suiteInfo Information about the full Jasmine suite that is being run - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'jasmineStarted', - /** - * When the entire suite has finished execution `jasmineDone` is called - * @function - * @name Reporter#jasmineDone - * @param {JasmineDoneInfo} suiteInfo Information about the full Jasmine suite that just finished running. - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'jasmineDone', - /** - * `suiteStarted` is invoked when a `describe` starts to run - * @function - * @name Reporter#suiteStarted - * @param {SuiteResult} result Information about the individual {@link describe} being run - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'suiteStarted', - /** - * `suiteDone` is invoked when all of the child specs and suites for a given suite have been run - * - * While jasmine doesn't require any specific functions, not defining a `suiteDone` will make it impossible for a reporter to know when a suite has failures in an `afterAll`. - * @function - * @name Reporter#suiteDone - * @param {SuiteResult} result - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'suiteDone', - /** - * `specStarted` is invoked when an `it` starts to run (including associated `beforeEach` functions) - * @function - * @name Reporter#specStarted - * @param {SpecResult} result Information about the individual {@link it} being run - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'specStarted', - /** - * `specDone` is invoked when an `it` and its associated `beforeEach` and `afterEach` functions have been run. - * - * While jasmine doesn't require any specific functions, not defining a `specDone` will make it impossible for a reporter to know when a spec has failed. - * @function - * @name Reporter#specDone - * @param {SpecResult} result - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'specDone' - ], queueRunnerFactory); + var reporter = new j$.ReportDispatcher( + [ + /** + * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. + * @function + * @name Reporter#jasmineStarted + * @param {JasmineStartedInfo} suiteInfo Information about the full Jasmine suite that is being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'jasmineStarted', + /** + * When the entire suite has finished execution `jasmineDone` is called + * @function + * @name Reporter#jasmineDone + * @param {JasmineDoneInfo} suiteInfo Information about the full Jasmine suite that just finished running. + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'jasmineDone', + /** + * `suiteStarted` is invoked when a `describe` starts to run + * @function + * @name Reporter#suiteStarted + * @param {SuiteResult} result Information about the individual {@link describe} being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'suiteStarted', + /** + * `suiteDone` is invoked when all of the child specs and suites for a given suite have been run + * + * While jasmine doesn't require any specific functions, not defining a `suiteDone` will make it impossible for a reporter to know when a suite has failures in an `afterAll`. + * @function + * @name Reporter#suiteDone + * @param {SuiteResult} result + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'suiteDone', + /** + * `specStarted` is invoked when an `it` starts to run (including associated `beforeEach` functions) + * @function + * @name Reporter#specStarted + * @param {SpecResult} result Information about the individual {@link it} being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'specStarted', + /** + * `specDone` is invoked when an `it` and its associated `beforeEach` and `afterEach` functions have been run. + * + * While jasmine doesn't require any specific functions, not defining a `specDone` will make it impossible for a reporter to know when a spec has failed. + * @function + * @name Reporter#specDone + * @param {SpecResult} result + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'specDone' + ], + queueRunnerFactory + ); this.execute = function(runnablesToRun) { - var self = this; installGlobalErrors(); - if(!runnablesToRun) { + if (!runnablesToRun) { if (focusedRunnables.length) { runnablesToRun = focusedRunnables; } else { @@ -552,8 +618,10 @@ getJasmineRequireObj().Env = function(j$) { } }); - if(!processor.processTree().valid) { - throw new Error('Invalid order: would cause a beforeAll or afterAll to be run multiple times'); + if (!processor.processTree().valid) { + throw new Error( + 'Invalid order: would cause a beforeAll or afterAll to be run multiple times' + ); } /** @@ -562,47 +630,53 @@ getJasmineRequireObj().Env = function(j$) { * @property {Int} totalSpecsDefined - The total number of specs defined in this suite. * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. */ - reporter.jasmineStarted({ - totalSpecsDefined: totalSpecsDefined, - order: order - }, function() { - currentlyExecutingSuites.push(topSuite); + reporter.jasmineStarted( + { + totalSpecsDefined: totalSpecsDefined, + order: order + }, + function() { + currentlyExecutingSuites.push(topSuite); - processor.execute(function () { - clearResourcesForRunnable(topSuite.id); - currentlyExecutingSuites.pop(); - var overallStatus, incompleteReason; + processor.execute(function() { + clearResourcesForRunnable(topSuite.id); + currentlyExecutingSuites.pop(); + var overallStatus, incompleteReason; - if (hasFailures || topSuite.result.failedExpectations.length > 0) { - overallStatus = 'failed'; - } else if (focusedRunnables.length > 0) { - overallStatus = 'incomplete'; - incompleteReason = 'fit() or fdescribe() was found'; - } else if (totalSpecsDefined === 0) { - overallStatus = 'incomplete'; - incompleteReason = 'No specs found'; - } else { - overallStatus = 'passed'; - } + if (hasFailures || topSuite.result.failedExpectations.length > 0) { + overallStatus = 'failed'; + } else if (focusedRunnables.length > 0) { + overallStatus = 'incomplete'; + incompleteReason = 'fit() or fdescribe() was found'; + } else if (totalSpecsDefined === 0) { + overallStatus = 'incomplete'; + incompleteReason = 'No specs found'; + } else { + overallStatus = 'passed'; + } - /** - * Information passed to the {@link Reporter#jasmineDone} event. - * @typedef JasmineDoneInfo - * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. - * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. - * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. - * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. - * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. - */ - reporter.jasmineDone({ - overallStatus: overallStatus, - incompleteReason: incompleteReason, - order: order, - failedExpectations: topSuite.result.failedExpectations, - deprecationWarnings: topSuite.result.deprecationWarnings - }, function() {}); - }); - }); + /** + * Information passed to the {@link Reporter#jasmineDone} event. + * @typedef JasmineDoneInfo + * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. + * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. + * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. + * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. + * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. + */ + reporter.jasmineDone( + { + overallStatus: overallStatus, + incompleteReason: incompleteReason, + order: order, + failedExpectations: topSuite.result.failedExpectations, + deprecationWarnings: topSuite.result.deprecationWarnings + }, + function() {} + ); + }); + } + ); }; /** @@ -653,8 +727,10 @@ getJasmineRequireObj().Env = function(j$) { var spyRegistry = new j$.SpyRegistry({ currentSpies: function() { - if(!currentRunnable()) { - throw new Error('Spies must be created in a before function or a spec'); + if (!currentRunnable()) { + throw new Error( + 'Spies must be created in a before function or a spec' + ); } return runnableResources[currentRunnable().id].spies; }, @@ -694,20 +770,26 @@ getJasmineRequireObj().Env = function(j$) { var ensureIsFunction = function(fn, caller) { if (!j$.isFunction_(fn)) { - throw new Error(caller + ' expects a function argument; received ' + j$.getType_(fn)); + throw new Error( + caller + ' expects a function argument; received ' + j$.getType_(fn) + ); } }; var ensureIsFunctionOrAsync = function(fn, caller) { if (!j$.isFunction_(fn) && !j$.isAsyncFunction_(fn)) { - throw new Error(caller + ' expects a function argument; received ' + j$.getType_(fn)); + throw new Error( + caller + ' expects a function argument; received ' + j$.getType_(fn) + ); } }; function ensureIsNotNested(method) { var runnable = currentRunnable(); if (runnable !== null && runnable !== undefined) { - throw new Error('\'' + method + '\' should only be used in \'describe\' function'); + throw new Error( + "'" + method + "' should only be used in 'describe' function" + ); } } @@ -821,7 +903,9 @@ getJasmineRequireObj().Env = function(j$) { description: description, expectationResultFactory: expectationResultFactory, queueRunnerFactory: queueRunnerFactory, - userContext: function() { return suite.clonedSharedUserContext(); }, + userContext: function() { + return suite.clonedSharedUserContext(); + }, queueableFn: { fn: fn, timeout: timeout || 0 @@ -888,7 +972,9 @@ getJasmineRequireObj().Env = function(j$) { this.expect = function(actual) { if (!currentRunnable()) { - throw new Error('\'expect\' was used when there was no current spec, this could be because an asynchronous test timed out'); + throw new Error( + "'expect' was used when there was no current spec, this could be because an asynchronous test timed out" + ); } return currentRunnable().expect(actual); @@ -896,7 +982,9 @@ getJasmineRequireObj().Env = function(j$) { this.expectAsync = function(actual) { if (!currentRunnable()) { - throw new Error('\'expectAsync\' was used when there was no current spec, this could be because an asynchronous test timed out'); + throw new Error( + "'expectAsync' was used when there was no current spec, this could be because an asynchronous test timed out" + ); } return currentRunnable().expectAsync(actual); @@ -941,7 +1029,7 @@ getJasmineRequireObj().Env = function(j$) { this.pending = function(message) { var fullMessage = j$.Spec.pendingSpecExceptionMessage; - if(message) { + if (message) { fullMessage += message; } throw fullMessage; @@ -949,7 +1037,9 @@ getJasmineRequireObj().Env = function(j$) { this.fail = function(error) { if (!currentRunnable()) { - throw new Error('\'fail\' was used when there was no current spec, this could be because an asynchronous test timed out'); + throw new Error( + "'fail' was used when there was no current spec, this could be because an asynchronous test timed out" + ); } var message = 'Failed'; diff --git a/src/core/ExceptionFormatter.js b/src/core/ExceptionFormatter.js index adbf984c..14534bb2 100644 --- a/src/core/ExceptionFormatter.js +++ b/src/core/ExceptionFormatter.js @@ -1,6 +1,16 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { - - var ignoredProperties = ['name', 'message', 'stack', 'fileName', 'sourceURL', 'line', 'lineNumber', 'column', 'description', 'jasmineMessage']; + var ignoredProperties = [ + 'name', + 'message', + 'stack', + 'fileName', + 'sourceURL', + 'line', + 'lineNumber', + 'column', + 'description', + 'jasmineMessage' + ]; function ExceptionFormatter(options) { var jasmineFile = (options && options.jasmineFile) || j$.util.jasmineFile(); @@ -49,7 +59,8 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { function filterJasmine(stackTrace) { var result = [], - jasmineMarker = stackTrace.style === 'webkit' ? '' : ' at '; + jasmineMarker = + stackTrace.style === 'webkit' ? '' : ' at '; stackTrace.frames.forEach(function(frame) { if (frame.file && frame.file !== jasmineFile) { diff --git a/src/core/Expectation.js b/src/core/Expectation.js index 2de1c15f..e1833433 100644 --- a/src/core/Expectation.js +++ b/src/core/Expectation.js @@ -1,6 +1,8 @@ getJasmineRequireObj().Expectation = function(j$) { var promiseForMessage = { - jasmineToString: function() { return 'a promise'; } + jasmineToString: function() { + return 'a promise'; + } }; /** @@ -12,7 +14,10 @@ getJasmineRequireObj().Expectation = function(j$) { var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { - this[matcherName] = wrapSyncCompare(matcherName, customMatchers[matcherName]); + this[matcherName] = wrapSyncCompare( + matcherName, + customMatchers[matcherName] + ); } } @@ -50,7 +55,9 @@ getJasmineRequireObj().Expectation = function(j$) { this.expector = new j$.Expector(options); if (!global.Promise) { - throw new Error('expectAsync is unavailable because the environment does not support promises.'); + throw new Error( + 'expectAsync is unavailable because the environment does not support promises.' + ); } if (!j$.isPromiseLike(this.expector.actual)) { @@ -100,9 +107,11 @@ getJasmineRequireObj().Expectation = function(j$) { // frames that are relevant to the user instead of just parts of Jasmine. var errorForStack = j$.util.errorWithStack(); - return this.expector.compare(name, matcherFactory, arguments).then(function(result) { - self.expector.processResult(result, errorForStack, promiseForMessage); - }); + return this.expector + .compare(name, matcherFactory, arguments) + .then(function(result) { + self.expector.processResult(result, errorForStack, promiseForMessage); + }); }; } diff --git a/src/core/ExpectationFilterChain.js b/src/core/ExpectationFilterChain.js index 83018bd6..6ecbd17c 100644 --- a/src/core/ExpectationFilterChain.js +++ b/src/core/ExpectationFilterChain.js @@ -12,7 +12,12 @@ getJasmineRequireObj().ExpectationFilterChain = function() { return this.callFirst_('selectComparisonFunc', arguments).result; }; - ExpectationFilterChain.prototype.buildFailureMessage = function(result, matcherName, args, util) { + ExpectationFilterChain.prototype.buildFailureMessage = function( + result, + matcherName, + args, + util + ) { return this.callFirst_('buildFailureMessage', arguments).result; }; @@ -39,7 +44,7 @@ getJasmineRequireObj().ExpectationFilterChain = function() { }; } - return {found: false}; + return { found: false }; }; return ExpectationFilterChain; diff --git a/src/core/ExpectationResult.js b/src/core/ExpectationResult.js index 869d5d24..43545c43 100644 --- a/src/core/ExpectationResult.js +++ b/src/core/ExpectationResult.js @@ -20,7 +20,7 @@ getJasmineRequireObj().buildExpectationResult = function() { passed: options.passed }; - if(!result.passed) { + if (!result.passed) { result.expected = options.expected; result.actual = options.actual; } diff --git a/src/core/Expector.js b/src/core/Expector.js index 55667f51..bfc443f8 100644 --- a/src/core/Expector.js +++ b/src/core/Expector.js @@ -7,7 +7,11 @@ getJasmineRequireObj().Expector = function(j$) { this.filters = new j$.ExpectationFilterChain(); } - Expector.prototype.instantiateMatcher = function(matcherName, matcherFactory, args) { + Expector.prototype.instantiateMatcher = function( + matcherName, + matcherFactory, + args + ) { this.matcherName = matcherName; this.args = Array.prototype.slice.call(args, 0); this.expected = this.args.slice(0); @@ -26,7 +30,13 @@ getJasmineRequireObj().Expector = function(j$) { return ''; } - var msg = this.filters.buildFailureMessage(result, this.matcherName, this.args, this.util, defaultMessage); + var msg = this.filters.buildFailureMessage( + result, + this.matcherName, + this.args, + this.util, + defaultMessage + ); return this.filters.modifyFailureMessage(msg || defaultMessage()); function defaultMessage() { @@ -44,7 +54,11 @@ getJasmineRequireObj().Expector = function(j$) { }; Expector.prototype.compare = function(matcherName, matcherFactory, args) { - var matcherCompare = this.instantiateMatcher(matcherName, matcherFactory, args); + var matcherCompare = this.instantiateMatcher( + matcherName, + matcherFactory, + args + ); return matcherCompare.apply(null, this.args); }; @@ -54,7 +68,11 @@ getJasmineRequireObj().Expector = function(j$) { return result; }; - Expector.prototype.processResult = function(result, errorForStack, actualOverride) { + Expector.prototype.processResult = function( + result, + errorForStack, + actualOverride + ) { this.args[0] = actualOverride || this.args[0]; var message = this.buildMessage(result); @@ -62,18 +80,15 @@ getJasmineRequireObj().Expector = function(j$) { this.expected = this.expected[0]; } - this.addExpectationResult( - result.pass, - { - matcherName: this.matcherName, - passed: result.pass, - message: message, - error: errorForStack ? undefined : result.error, - errorForStack: errorForStack || undefined, - actual: this.actual, - expected: this.expected // TODO: this may need to be arrayified/sliced - } - ); + this.addExpectationResult(result.pass, { + matcherName: this.matcherName, + passed: result.pass, + message: message, + error: errorForStack ? undefined : result.error, + errorForStack: errorForStack || undefined, + actual: this.actual, + expected: this.expected // TODO: this may need to be arrayified/sliced + }); }; return Expector; diff --git a/src/core/GlobalErrors.js b/src/core/GlobalErrors.js index 56c10c82..2c58e684 100644 --- a/src/core/GlobalErrors.js +++ b/src/core/GlobalErrors.js @@ -38,7 +38,10 @@ getJasmineRequireObj().GlobalErrors = function(j$) { var errorTypes = Object.keys(this.originalHandlers); for (var iType = 0; iType < errorTypes.length; iType++) { var errorType = errorTypes[iType]; - global.process.removeListener(errorType, this.jasmineHandlers[errorType]); + global.process.removeListener( + errorType, + this.jasmineHandlers[errorType] + ); for (var i = 0; i < this.originalHandlers[errorType].length; i++) { global.process.on(errorType, this.originalHandlers[errorType][i]); } @@ -49,7 +52,11 @@ getJasmineRequireObj().GlobalErrors = function(j$) { }; this.install = function install() { - if (global.process && global.process.listeners && j$.isFunction_(global.process.on)) { + if ( + global.process && + global.process.listeners && + j$.isFunction_(global.process.on) + ) { this.installOne_('uncaughtException', 'Uncaught exception'); this.installOne_('unhandledRejection', 'Unhandled promise rejection'); } else { diff --git a/src/core/JsApiReporter.js b/src/core/JsApiReporter.js index 241deccf..514b3a6c 100644 --- a/src/core/JsApiReporter.js +++ b/src/core/JsApiReporter.js @@ -7,7 +7,7 @@ getJasmineRequireObj().JsApiReporter = function(j$) { */ function JsApiReporter(options) { var timer = options.timer || j$.noopTimer, - status = 'loaded'; + status = 'loaded'; this.started = false; this.finished = false; @@ -117,7 +117,6 @@ getJasmineRequireObj().JsApiReporter = function(j$) { this.executionTime = function() { return executionTime; }; - } return JsApiReporter; diff --git a/src/core/MockDate.js b/src/core/MockDate.js index 9dfc0628..7b642038 100644 --- a/src/core/MockDate.js +++ b/src/core/MockDate.js @@ -37,7 +37,7 @@ getJasmineRequireObj().MockDate = function() { return self; function FakeDate() { - switch(arguments.length) { + switch (arguments.length) { case 0: return new GlobalDate(currentTime); case 1: @@ -47,16 +47,39 @@ getJasmineRequireObj().MockDate = function() { case 3: return new GlobalDate(arguments[0], arguments[1], arguments[2]); case 4: - return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3]); + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3] + ); case 5: - return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], - arguments[4]); + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4] + ); case 6: - return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], - arguments[4], arguments[5]); + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4], + arguments[5] + ); default: - return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], - arguments[4], arguments[5], arguments[6]); + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4], + arguments[5], + arguments[6] + ); } } diff --git a/src/core/Order.js b/src/core/Order.js index de35ca8e..050e1001 100644 --- a/src/core/Order.js +++ b/src/core/Order.js @@ -3,7 +3,7 @@ getJasmineRequireObj().Order = function() { function Order(options) { this.random = 'random' in options ? options.random : true; - var seed = this.seed = options.seed || generateSeed(); + var seed = (this.seed = options.seed || generateSeed()); this.sort = this.random ? randomOrder : naturalOrder; function naturalOrder(items) { @@ -29,17 +29,16 @@ getJasmineRequireObj().Order = function() { function jenkinsHash(key) { var hash, i; - for(hash = i = 0; i < key.length; ++i) { + for (hash = i = 0; i < key.length; ++i) { hash += key.charCodeAt(i); - hash += (hash << 10); - hash ^= (hash >> 6); + hash += hash << 10; + hash ^= hash >> 6; } - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); + hash += hash << 3; + hash ^= hash >> 11; + hash += hash << 15; return hash; } - } return Order; diff --git a/src/core/PrettyPrinter.js b/src/core/PrettyPrinter.js index 5b3dd55f..67cb34d6 100644 --- a/src/core/PrettyPrinter.js +++ b/src/core/PrettyPrinter.js @@ -1,5 +1,4 @@ getJasmineRequireObj().pp = function(j$) { - function PrettyPrinter() { this.ppNestLevel_ = 0; this.seen = []; @@ -10,7 +9,11 @@ getJasmineRequireObj().pp = function(j$) { function hasCustomToString(value) { // value.toString !== Object.prototype.toString if value has no custom toString but is from another context (e.g. // iframe, web worker) - return j$.isFunction_(value.toString) && value.toString !== Object.prototype.toString && (value.toString() !== Object.prototype.toString.call(value)); + return ( + j$.isFunction_(value.toString) && + value.toString !== Object.prototype.toString && + value.toString() !== Object.prototype.toString.call(value) + ); } PrettyPrinter.prototype.format = function(value) { @@ -20,7 +23,7 @@ getJasmineRequireObj().pp = function(j$) { this.emitScalar('undefined'); } else if (value === null) { this.emitScalar('null'); - } else if (value === 0 && 1/value === -Infinity) { + } else if (value === 0 && 1 / value === -Infinity) { this.emitScalar('-0'); } else if (value === j$.getGlobal()) { this.emitScalar(''); @@ -50,10 +53,19 @@ getJasmineRequireObj().pp = function(j$) { this.emitMap(value); } else if (j$.isTypedArray_(value)) { this.emitTypedArray(value); - } else if (value.toString && typeof value === 'object' && !j$.isArray_(value) && hasCustomToString(value)) { + } else if ( + value.toString && + typeof value === 'object' && + !j$.isArray_(value) && + hasCustomToString(value) + ) { this.emitScalar(value.toString()); } else if (j$.util.arrayContains(this.seen, value)) { - this.emitScalar(''); + this.emitScalar( + '' + ); } else if (j$.isArray_(value) || j$.isA_('Object', value)) { this.seen.push(value); if (j$.isArray_(value)) { @@ -83,7 +95,6 @@ getJasmineRequireObj().pp = function(j$) { var getter = obj.__lookupGetter__(prop); return !j$.util.isUndefined(getter) && getter !== null; }; - } var length = Math.min(objKeys.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); for (var i = 0; i < length; i++) { @@ -99,7 +110,7 @@ getJasmineRequireObj().pp = function(j$) { }; PrettyPrinter.prototype.emitString = function(value) { - this.append('\'' + value + '\''); + this.append("'" + value + "'"); }; PrettyPrinter.prototype.emitArray = function(array) { @@ -115,7 +126,7 @@ getJasmineRequireObj().pp = function(j$) { } this.format(array[i]); } - if(array.length > length) { + if (array.length > length) { this.append(', ...'); } @@ -131,7 +142,9 @@ getJasmineRequireObj().pp = function(j$) { self.formatProperty(array, property, isGetter); }); - if (truncated) { this.append(', ...'); } + if (truncated) { + this.append(', ...'); + } this.append(' ]'); }; @@ -144,7 +157,7 @@ getJasmineRequireObj().pp = function(j$) { this.append('Set( '); var size = Math.min(set.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); var i = 0; - set.forEach( function( value, key ) { + set.forEach(function(value, key) { if (i >= size) { return; } @@ -154,7 +167,7 @@ getJasmineRequireObj().pp = function(j$) { this.format(value); i++; - }, this ); + }, this); if (set.size > size) { this.append(', ...'); } @@ -169,17 +182,17 @@ getJasmineRequireObj().pp = function(j$) { this.append('Map( '); var size = Math.min(map.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); var i = 0; - map.forEach( function( value, key ) { + map.forEach(function(value, key) { if (i >= size) { return; } if (i > 0) { this.append(', '); } - this.format([key,value]); + this.format([key, value]); i++; - }, this ); + }, this); if (map.size > size) { this.append(', ...'); } @@ -188,11 +201,12 @@ getJasmineRequireObj().pp = function(j$) { PrettyPrinter.prototype.emitObject = function(obj) { var ctor = obj.constructor, - constructorName; + constructorName; - constructorName = typeof ctor === 'function' && obj instanceof ctor ? - j$.fnNameFor(obj.constructor) : - 'null'; + constructorName = + typeof ctor === 'function' && obj instanceof ctor + ? j$.fnNameFor(obj.constructor) + : 'null'; this.append(constructorName); @@ -214,14 +228,20 @@ getJasmineRequireObj().pp = function(j$) { self.formatProperty(obj, property, isGetter); }); - if (truncated) { this.append(', ...'); } + if (truncated) { + this.append(', ...'); + } this.append(' })'); }; PrettyPrinter.prototype.emitTypedArray = function(arr) { var constructorName = j$.fnNameFor(arr.constructor), - limitedArray = Array.prototype.slice.call(arr, 0, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH), + limitedArray = Array.prototype.slice.call( + arr, + 0, + j$.MAX_PRETTY_PRINT_ARRAY_LENGTH + ), itemsString = Array.prototype.join.call(limitedArray, ', '); if (limitedArray.length !== arr.length) { @@ -258,13 +278,13 @@ getJasmineRequireObj().pp = function(j$) { }; PrettyPrinter.prototype.formatProperty = function(obj, property, isGetter) { - this.append(property); - this.append(': '); - if (isGetter) { - this.append(''); - } else { - this.format(obj[property]); - } + this.append(property); + this.append(': '); + if (isGetter) { + this.append(''); + } else { + this.format(obj[property]); + } }; PrettyPrinter.prototype.append = function(value) { @@ -283,7 +303,6 @@ getJasmineRequireObj().pp = function(j$) { } }; - function truncate(s, maxlen) { if (s.length <= maxlen) { return { value: s, truncated: false }; @@ -294,30 +313,33 @@ getJasmineRequireObj().pp = function(j$) { } function MaxCharsReachedError() { - this.message = 'Exceeded ' + j$.MAX_PRETTY_PRINT_CHARS + + this.message = + 'Exceeded ' + + j$.MAX_PRETTY_PRINT_CHARS + ' characters while pretty-printing a value'; } MaxCharsReachedError.prototype = new Error(); function keys(obj, isArray) { - var allKeys = Object.keys ? Object.keys(obj) : - (function(o) { + var allKeys = Object.keys + ? Object.keys(obj) + : (function(o) { var keys = []; for (var key in o) { - if (j$.util.has(o, key)) { - keys.push(key); - } + if (j$.util.has(o, key)) { + keys.push(key); + } } return keys; - })(obj); + })(obj); if (!isArray) { return allKeys; } if (allKeys.length === 0) { - return allKeys; + return allKeys; } var extraKeys = []; diff --git a/src/core/QueueRunner.js b/src/core/QueueRunner.js index c183c1d4..27b57695 100644 --- a/src/core/QueueRunner.js +++ b/src/core/QueueRunner.js @@ -22,16 +22,26 @@ getJasmineRequireObj().QueueRunner = function(j$) { this.queueableFns = queueableFns.concat(attrs.cleanupFns || []); this.firstCleanupIx = queueableFns.length; this.onComplete = attrs.onComplete || emptyFn; - this.clearStack = attrs.clearStack || function(fn) { fn(); }; + this.clearStack = + attrs.clearStack || + function(fn) { + fn(); + }; this.onException = attrs.onException || emptyFn; this.userContext = attrs.userContext || new j$.UserContext(); - this.timeout = attrs.timeout || {setTimeout: setTimeout, clearTimeout: clearTimeout}; + this.timeout = attrs.timeout || { + setTimeout: setTimeout, + clearTimeout: clearTimeout + }; this.fail = attrs.fail || emptyFn; - this.globalErrors = attrs.globalErrors || { pushListener: emptyFn, popListener: emptyFn }; + this.globalErrors = attrs.globalErrors || { + pushListener: emptyFn, + popListener: emptyFn + }; this.completeOnFirstError = !!attrs.completeOnFirstError; this.errored = false; - if (typeof(this.onComplete) !== 'function') { + if (typeof this.onComplete !== 'function') { throw new Error('invalid onComplete ' + JSON.stringify(this.onComplete)); } this.deprecated = attrs.deprecated; @@ -55,15 +65,22 @@ getJasmineRequireObj().QueueRunner = function(j$) { }; QueueRunner.prototype.clearTimeout = function(timeoutId) { - Function.prototype.apply.apply(this.timeout.clearTimeout, [j$.getGlobal(), [timeoutId]]); + Function.prototype.apply.apply(this.timeout.clearTimeout, [ + j$.getGlobal(), + [timeoutId] + ]); }; QueueRunner.prototype.setTimeout = function(fn, timeout) { - return Function.prototype.apply.apply(this.timeout.setTimeout, [j$.getGlobal(), [fn, timeout]]); + return Function.prototype.apply.apply(this.timeout.setTimeout, [ + j$.getGlobal(), + [fn, timeout] + ]); }; QueueRunner.prototype.attempt = function attempt(iterativeIndex) { - var self = this, completedSynchronously = true, + var self = this, + completedSynchronously = true, handleError = function handleError(error) { onException(error); next(error); @@ -114,8 +131,12 @@ getJasmineRequireObj().QueueRunner = function(j$) { var timeoutInterval = queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL; timeoutId = self.setTimeout(function() { var error = new Error( - 'Timeout - Async callback was not invoked within ' + timeoutInterval + 'ms ' + - (queueableFn.timeout ? '(custom timeout)' : '(set by jasmine.DEFAULT_TIMEOUT_INTERVAL)') + 'Timeout - Async callback was not invoked within ' + + timeoutInterval + + 'ms ' + + (queueableFn.timeout + ? '(custom timeout)' + : '(set by jasmine.DEFAULT_TIMEOUT_INTERVAL)') ); onException(error); next(); @@ -160,8 +181,11 @@ getJasmineRequireObj().QueueRunner = function(j$) { self = this, iterativeIndex; - - for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) { + for ( + iterativeIndex = recursiveIndex; + iterativeIndex < length; + iterativeIndex++ + ) { var result = this.attempt(iterativeIndex); if (!result.completedSynchronously) { @@ -180,7 +204,6 @@ getJasmineRequireObj().QueueRunner = function(j$) { self.globalErrors.popListener(self.handleFinalError); self.onComplete(self.errored && new StopExecutionError()); }); - }; return QueueRunner; diff --git a/src/core/ReportDispatcher.js b/src/core/ReportDispatcher.js index 5b2fad25..d254fb59 100644 --- a/src/core/ReportDispatcher.js +++ b/src/core/ReportDispatcher.js @@ -1,6 +1,5 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { function ReportDispatcher(methods, queueRunnerFactory) { - var dispatchedMethods = methods || []; for (var i = 0; i < dispatchedMethods.length; i++) { @@ -9,7 +8,7 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { return function() { dispatch(m, arguments); }; - }(method)); + })(method); } var reporters = []; @@ -31,7 +30,7 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { function dispatch(method, args) { if (reporters.length === 0 && fallbackReporter !== null) { - reporters.push(fallbackReporter); + reporters.push(fallbackReporter); } var onComplete = args[args.length - 1]; args = j$.util.argsToArray(args).splice(0, args.length - 1); @@ -57,13 +56,13 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { var thisArgs = j$.util.cloneArgs(args); if (fn.length <= 1) { fns.push({ - fn: function () { + fn: function() { return fn.apply(reporter, thisArgs); } }); } else { fns.push({ - fn: function (done) { + fn: function(done) { return fn.apply(reporter, thisArgs.concat([done])); } }); @@ -73,4 +72,3 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { return ReportDispatcher; }; - diff --git a/src/core/Spec.js b/src/core/Spec.js index 4b31925d..53a4f0ef 100644 --- a/src/core/Spec.js +++ b/src/core/Spec.js @@ -6,13 +6,30 @@ getJasmineRequireObj().Spec = function(j$) { this.id = attrs.id; this.description = attrs.description || ''; this.queueableFn = attrs.queueableFn; - this.beforeAndAfterFns = attrs.beforeAndAfterFns || function() { return {befores: [], afters: []}; }; - this.userContext = attrs.userContext || function() { return {}; }; + this.beforeAndAfterFns = + attrs.beforeAndAfterFns || + function() { + return { befores: [], afters: [] }; + }; + this.userContext = + attrs.userContext || + function() { + return {}; + }; this.onStart = attrs.onStart || function() {}; - this.getSpecName = attrs.getSpecName || function() { return ''; }; - this.expectationResultFactory = attrs.expectationResultFactory || function() { }; + this.getSpecName = + attrs.getSpecName || + function() { + return ''; + }; + this.expectationResultFactory = + attrs.expectationResultFactory || function() {}; this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; - this.catchingExceptions = attrs.catchingExceptions || function() { return true; }; + this.catchingExceptions = + attrs.catchingExceptions || + function() { + return true; + }; this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.timer = attrs.timer || j$.noopTimer; @@ -90,12 +107,15 @@ getJasmineRequireObj().Spec = function(j$) { isLeaf: true, queueableFns: regularFns, cleanupFns: fns.afters, - onException: function () { + onException: function() { self.onException.apply(self, arguments); }, onComplete: function() { self.result.duration = self.timer.elapsed(); - onComplete(self.result.status === 'failed' && new j$.StopExecutionError('spec failed')); + onComplete( + self.result.status === 'failed' && + new j$.StopExecutionError('spec failed') + ); }, userContext: this.userContext() }; @@ -121,13 +141,17 @@ getJasmineRequireObj().Spec = function(j$) { return; } - this.addExpectationResult(false, { - matcherName: '', - passed: false, - expected: '', - actual: '', - error: e - }, true); + this.addExpectationResult( + false, + { + matcherName: '', + passed: false, + expected: '', + actual: '', + error: e + }, + true + ); }; Spec.prototype.pend = function(message) { @@ -166,13 +190,16 @@ getJasmineRequireObj().Spec = function(j$) { if (typeof deprecation === 'string') { deprecation = { message: deprecation }; } - this.result.deprecationWarnings.push(this.expectationResultFactory(deprecation)); + this.result.deprecationWarnings.push( + this.expectationResultFactory(deprecation) + ); }; var extractCustomPendingMessage = function(e) { var fullMessage = e.toString(), - boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), - boilerplateEnd = boilerplateStart + Spec.pendingSpecExceptionMessage.length; + boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), + boilerplateEnd = + boilerplateStart + Spec.pendingSpecExceptionMessage.length; return fullMessage.substr(boilerplateEnd); }; @@ -180,7 +207,11 @@ getJasmineRequireObj().Spec = function(j$) { Spec.pendingSpecExceptionMessage = '=> marked Pending'; Spec.isPendingSpecException = function(e) { - return !!(e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1); + return !!( + e && + e.toString && + e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 + ); }; return Spec; diff --git a/src/core/Spy.js b/src/core/Spy.js index e4072f1b..753499bb 100644 --- a/src/core/Spy.js +++ b/src/core/Spy.js @@ -1,5 +1,4 @@ -getJasmineRequireObj().Spy = function (j$) { - +getJasmineRequireObj().Spy = function(j$) { var nextOrder = (function() { var order = 0; @@ -14,21 +13,21 @@ getJasmineRequireObj().Spy = function (j$) { * @name Spy */ function Spy(name, originalFn, customStrategies, getPromise) { - var numArgs = (typeof originalFn === 'function' ? originalFn.length : 0), - wrapper = makeFunc(numArgs, function () { + var numArgs = typeof originalFn === 'function' ? originalFn.length : 0, + wrapper = makeFunc(numArgs, function() { return spy.apply(this, Array.prototype.slice.call(arguments)); }), strategyDispatcher = new SpyStrategyDispatcher({ name: name, fn: originalFn, - getSpy: function () { + getSpy: function() { return wrapper; }, customStrategies: customStrategies, getPromise: getPromise }), callTracker = new j$.CallTracker(), - spy = function () { + spy = function() { /** * @name Spy.callData * @property {object} object - `this` context for the invocation. @@ -50,22 +49,54 @@ getJasmineRequireObj().Spy = function (j$) { function makeFunc(length, fn) { switch (length) { - case 1 : return function (a) { return fn.apply(this, arguments); }; - case 2 : return function (a,b) { return fn.apply(this, arguments); }; - case 3 : return function (a,b,c) { return fn.apply(this, arguments); }; - case 4 : return function (a,b,c,d) { return fn.apply(this, arguments); }; - case 5 : return function (a,b,c,d,e) { return fn.apply(this, arguments); }; - case 6 : return function (a,b,c,d,e,f) { return fn.apply(this, arguments); }; - case 7 : return function (a,b,c,d,e,f,g) { return fn.apply(this, arguments); }; - case 8 : return function (a,b,c,d,e,f,g,h) { return fn.apply(this, arguments); }; - case 9 : return function (a,b,c,d,e,f,g,h,i) { return fn.apply(this, arguments); }; - default : return function () { return fn.apply(this, arguments); }; + case 1: + return function(a) { + return fn.apply(this, arguments); + }; + case 2: + return function(a, b) { + return fn.apply(this, arguments); + }; + case 3: + return function(a, b, c) { + return fn.apply(this, arguments); + }; + case 4: + return function(a, b, c, d) { + return fn.apply(this, arguments); + }; + case 5: + return function(a, b, c, d, e) { + return fn.apply(this, arguments); + }; + case 6: + return function(a, b, c, d, e, f) { + return fn.apply(this, arguments); + }; + case 7: + return function(a, b, c, d, e, f, g) { + return fn.apply(this, arguments); + }; + case 8: + return function(a, b, c, d, e, f, g, h) { + return fn.apply(this, arguments); + }; + case 9: + return function(a, b, c, d, e, f, g, h, i) { + return fn.apply(this, arguments); + }; + default: + return function() { + return fn.apply(this, arguments); + }; } } for (var prop in originalFn) { if (prop === 'and' || prop === 'calls') { - throw new Error('Jasmine spies would overwrite the \'and\' and \'calls\' properties on the object being spied upon'); + throw new Error( + "Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon" + ); } wrapper[prop] = originalFn[prop]; @@ -112,7 +143,13 @@ getJasmineRequireObj().Spy = function (j$) { if (!strategy) { if (argsStrategies.any() && !baseStrategy.isConfigured()) { - throw new Error('Spy \'' + strategyArgs.name + '\' received a call with arguments ' + j$.pp(Array.prototype.slice.call(args)) + ' but all configured strategies specify other arguments.'); + throw new Error( + "Spy '" + + strategyArgs.name + + "' received a call with arguments " + + j$.pp(Array.prototype.slice.call(args)) + + ' but all configured strategies specify other arguments.' + ); } else { strategy = baseStrategy; } diff --git a/src/core/SpyFactory.js b/src/core/SpyFactory.js index 4df28e55..a622a8a3 100644 --- a/src/core/SpyFactory.js +++ b/src/core/SpyFactory.js @@ -1,5 +1,4 @@ getJasmineRequireObj().SpyFactory = function(j$) { - function SpyFactory(getCustomStrategies, getPromise) { var self = this; @@ -8,7 +7,8 @@ getJasmineRequireObj().SpyFactory = function(j$) { }; this.createSpyObj = function(baseName, methodNames) { - var baseNameIsCollection = j$.isObject_(baseName) || j$.isArray_(baseName); + var baseNameIsCollection = + j$.isObject_(baseName) || j$.isArray_(baseName); if (baseNameIsCollection && j$.util.isUndefined(methodNames)) { methodNames = baseName; diff --git a/src/core/SpyRegistry.js b/src/core/SpyRegistry.js index 3f4e3bc9..6e0bb33e 100644 --- a/src/core/SpyRegistry.js +++ b/src/core/SpyRegistry.js @@ -1,13 +1,19 @@ getJasmineRequireObj().SpyRegistry = function(j$) { - var spyOnMsg = j$.formatErrorMsg('', 'spyOn(, )'); - var spyOnPropertyMsg = j$.formatErrorMsg('', 'spyOnProperty(, , [accessType])'); + var spyOnPropertyMsg = j$.formatErrorMsg( + '', + 'spyOnProperty(, , [accessType])' + ); function SpyRegistry(options) { options = options || {}; var global = options.global || j$.getGlobal(); var createSpy = options.createSpy; - var currentSpies = options.currentSpies || function() { return []; }; + var currentSpies = + options.currentSpies || + function() { + return []; + }; this.allowRespy = function(allow) { this.respy = allow; @@ -17,7 +23,11 @@ getJasmineRequireObj().SpyRegistry = function(j$) { var getErrorMsg = spyOnMsg; if (j$.util.isUndefined(obj) || obj === null) { - throw new Error(getErrorMsg('could not find an object to spy upon for ' + methodName + '()')); + throw new Error( + getErrorMsg( + 'could not find an object to spy upon for ' + methodName + '()' + ) + ); } if (j$.util.isUndefined(methodName) || methodName === null) { @@ -28,25 +38,32 @@ getJasmineRequireObj().SpyRegistry = function(j$) { throw new Error(getErrorMsg(methodName + '() method does not exist')); } - if (obj[methodName] && j$.isSpy(obj[methodName]) ) { + if (obj[methodName] && j$.isSpy(obj[methodName])) { if (this.respy) { return obj[methodName]; - }else { - throw new Error(getErrorMsg(methodName + ' has already been spied upon')); + } else { + throw new Error( + getErrorMsg(methodName + ' has already been spied upon') + ); } } var descriptor = Object.getOwnPropertyDescriptor(obj, methodName); if (descriptor && !(descriptor.writable || descriptor.set)) { - throw new Error(getErrorMsg(methodName + ' is not declared writable or has no setter')); + throw new Error( + getErrorMsg(methodName + ' is not declared writable or has no setter') + ); } var originalMethod = obj[methodName], spiedMethod = createSpy(methodName, originalMethod), restoreStrategy; - if (Object.prototype.hasOwnProperty.call(obj, methodName) || (obj === global && methodName === 'onerror')) { + if ( + Object.prototype.hasOwnProperty.call(obj, methodName) || + (obj === global && methodName === 'onerror') + ) { restoreStrategy = function() { obj[methodName] = originalMethod; }; @@ -67,13 +84,19 @@ getJasmineRequireObj().SpyRegistry = function(j$) { return spiedMethod; }; - this.spyOnProperty = function (obj, propertyName, accessType) { + this.spyOnProperty = function(obj, propertyName, accessType) { var getErrorMsg = spyOnPropertyMsg; accessType = accessType || 'get'; if (j$.util.isUndefined(obj)) { - throw new Error(getErrorMsg('spyOn could not find an object to spy upon for ' + propertyName + '')); + throw new Error( + getErrorMsg( + 'spyOn could not find an object to spy upon for ' + + propertyName + + '' + ) + ); } if (j$.util.isUndefined(propertyName)) { @@ -87,18 +110,31 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } if (!descriptor.configurable) { - throw new Error(getErrorMsg(propertyName + ' is not declared configurable')); + throw new Error( + getErrorMsg(propertyName + ' is not declared configurable') + ); } - if(!descriptor[accessType]) { - throw new Error(getErrorMsg('Property ' + propertyName + ' does not have access type ' + accessType)); + if (!descriptor[accessType]) { + throw new Error( + getErrorMsg( + 'Property ' + + propertyName + + ' does not have access type ' + + accessType + ) + ); } if (j$.isSpy(descriptor[accessType])) { if (this.respy) { return descriptor[accessType]; } else { - throw new Error(getErrorMsg(propertyName + '#' + accessType + ' has already been spied upon')); + throw new Error( + getErrorMsg( + propertyName + '#' + accessType + ' has already been spied upon' + ) + ); } } @@ -129,19 +165,27 @@ getJasmineRequireObj().SpyRegistry = function(j$) { this.spyOnAllFunctions = function(obj) { if (j$.util.isUndefined(obj)) { - throw new Error('spyOnAllFunctions could not find an object to spy upon'); + throw new Error( + 'spyOnAllFunctions could not find an object to spy upon' + ); } var pointer = obj, - props = [], - prop, - descriptor; + props = [], + prop, + descriptor; while (pointer) { for (prop in pointer) { - if (Object.prototype.hasOwnProperty.call(pointer, prop) && pointer[prop] instanceof Function) { + if ( + Object.prototype.hasOwnProperty.call(pointer, prop) && + pointer[prop] instanceof Function + ) { descriptor = Object.getOwnPropertyDescriptor(pointer, prop); - if ((descriptor.writable || descriptor.set) && descriptor.configurable) { + if ( + (descriptor.writable || descriptor.set) && + descriptor.configurable + ) { props.push(prop); } } diff --git a/src/core/SpyStrategy.js b/src/core/SpyStrategy.js index 5a785d4f..81ccf2ce 100644 --- a/src/core/SpyStrategy.js +++ b/src/core/SpyStrategy.js @@ -1,5 +1,4 @@ getJasmineRequireObj().SpyStrategy = function(j$) { - /** * @interface SpyStrategy */ @@ -19,20 +18,27 @@ getJasmineRequireObj().SpyStrategy = function(j$) { this.getSpy = options.getSpy || function() {}; this.plan = this._defaultPlan = function() {}; - var k, cs = options.customStrategies || {}; + var k, + cs = options.customStrategies || {}; for (k in cs) { if (j$.util.has(cs, k) && !this[k]) { this[k] = createCustomPlan(cs[k]); } } - var getPromise = (typeof options.getPromise === 'function') ? options.getPromise : function() {}; + var getPromise = + typeof options.getPromise === 'function' + ? options.getPromise + : function() {}; var requirePromise = function(name) { var Promise = getPromise(); if (!Promise) { - throw new Error(name + ' requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`'); + throw new Error( + name + + ' requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`' + ); } return Promise; @@ -60,7 +66,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { */ this.rejectWith = function(value) { var Promise = requirePromise('rejectWith'); - var error = (value instanceof Error) ? value : new Error(value); + var error = value instanceof Error ? value : new Error(value); self.plan = function() { return Promise.reject(error); @@ -122,7 +128,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { */ SpyStrategy.prototype.returnValues = function() { var values = Array.prototype.slice.call(arguments); - this.plan = function () { + this.plan = function() { return values.shift(); }; return this.getSpy(); @@ -135,7 +141,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {Error|String} something Thing to throw */ SpyStrategy.prototype.throwError = function(something) { - var error = (something instanceof Error) ? something : new Error(something); + var error = something instanceof Error ? something : new Error(something); this.plan = function() { throw error; }; @@ -149,8 +155,10 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {Function} fn The function to invoke with the passed parameters. */ SpyStrategy.prototype.callFake = function(fn) { - if(!(j$.isFunction_(fn) || j$.isAsyncFunction_(fn))) { - throw new Error('Argument passed to callFake should be a function, got ' + fn); + if (!(j$.isFunction_(fn) || j$.isAsyncFunction_(fn))) { + throw new Error( + 'Argument passed to callFake should be a function, got ' + fn + ); } this.plan = fn; return this.getSpy(); diff --git a/src/core/StackTrace.js b/src/core/StackTrace.js index 6c6ec458..3382751d 100644 --- a/src/core/StackTrace.js +++ b/src/core/StackTrace.js @@ -1,8 +1,8 @@ getJasmineRequireObj().StackTrace = function(j$) { function StackTrace(error) { - var lines = error.stack - .split('\n') - .filter(function(line) { return line !== ''; }); + var lines = error.stack.split('\n').filter(function(line) { + return line !== ''; + }); var extractResult = extractMessage(error.message, lines); @@ -21,7 +21,12 @@ getJasmineRequireObj().StackTrace = function(j$) { // e.g. " at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)" // Note that the "function name" can include a surprisingly large set of // characters, including angle brackets and square brackets. - { re: /^\s*at ([^\)]+) \(([^\)]+)\)$/, fnIx: 1, fileLineColIx: 2, style: 'v8' }, + { + re: /^\s*at ([^\)]+) \(([^\)]+)\)$/, + fnIx: 1, + fileLineColIx: 2, + style: 'v8' + }, // NodeJS alternate form, often mixed in with the Chrome style // e.g. " at /some/path:4320:20 @@ -30,7 +35,12 @@ getJasmineRequireObj().StackTrace = function(j$) { // PhantomJS on OS X, Safari, Firefox // e.g. "run@http://localhost:8888/__jasmine__/jasmine.js:4320:27" // or "http://localhost:8888/__jasmine__/jasmine.js:4320:27" - { re: /^(([^@\s]+)@)?([^\s]+)$/, fnIx: 2, fileLineColIx: 3, style: 'webkit' } + { + re: /^(([^@\s]+)@)?([^\s]+)$/, + fnIx: 2, + fileLineColIx: 3, + style: 'webkit' + } ]; // regexes should capture the function name (if any) as group 1 @@ -41,11 +51,16 @@ getJasmineRequireObj().StackTrace = function(j$) { var convertedLine = first(framePatterns, function(pattern) { var overallMatch = line.match(pattern.re), fileLineColMatch; - if (!overallMatch) { return null; } + if (!overallMatch) { + return null; + } fileLineColMatch = overallMatch[pattern.fileLineColIx].match( - /^(.*):(\d+):\d+$/); - if (!fileLineColMatch) { return null; } + /^(.*):(\d+):\d+$/ + ); + if (!fileLineColMatch) { + return null; + } style = style || pattern.style; return { diff --git a/src/core/Suite.js b/src/core/Suite.js index bbb582a8..75104068 100644 --- a/src/core/Suite.js +++ b/src/core/Suite.js @@ -48,7 +48,11 @@ getJasmineRequireObj().Suite = function(j$) { Suite.prototype.getFullName = function() { var fullName = []; - for (var parentSuite = this; parentSuite; parentSuite = parentSuite.parentSuite) { + for ( + var parentSuite = this; + parentSuite; + parentSuite = parentSuite.parentSuite + ) { if (parentSuite.parentSuite) { fullName.unshift(parentSuite.description); } @@ -85,7 +89,7 @@ getJasmineRequireObj().Suite = function(j$) { }; function removeFns(queueableFns) { - for(var i = 0; i < queueableFns.length; i++) { + for (var i = 0; i < queueableFns.length; i++) { queueableFns[i].fn = null; } } @@ -124,7 +128,9 @@ getJasmineRequireObj().Suite = function(j$) { Suite.prototype.sharedUserContext = function() { if (!this.sharedContext) { - this.sharedContext = this.parentSuite ? this.parentSuite.clonedSharedUserContext() : new j$.UserContext(); + this.sharedContext = this.parentSuite + ? this.parentSuite.clonedSharedUserContext() + : new j$.UserContext(); } return this.sharedContext; @@ -155,11 +161,11 @@ getJasmineRequireObj().Suite = function(j$) { this.result.failedExpectations.push(failedExpectation); }; - Suite.prototype.addExpectationResult = function () { - if(isFailure(arguments)) { + Suite.prototype.addExpectationResult = function() { + if (isFailure(arguments)) { var data = arguments[1]; this.result.failedExpectations.push(this.expectationResultFactory(data)); - if(this.throwOnExpectationFailure) { + if (this.throwOnExpectationFailure) { throw new j$.errors.ExpectationFailed(); } } @@ -169,7 +175,9 @@ getJasmineRequireObj().Suite = function(j$) { if (typeof deprecation === 'string') { deprecation = { message: deprecation }; } - this.result.deprecationWarnings.push(this.expectationResultFactory(deprecation)); + this.result.deprecationWarnings.push( + this.expectationResultFactory(deprecation) + ); }; function isFailure(args) { diff --git a/src/core/Timer.js b/src/core/Timer.js index f613dd1a..35ef9f32 100644 --- a/src/core/Timer.js +++ b/src/core/Timer.js @@ -1,6 +1,8 @@ getJasmineRequireObj().Timer = function() { var defaultNow = (function(Date) { - return function() { return new Date().getTime(); }; + return function() { + return new Date().getTime(); + }; })(Date); function Timer(options) { @@ -24,6 +26,8 @@ getJasmineRequireObj().Timer = function() { getJasmineRequireObj().noopTimer = function() { return { start: function() {}, - elapsed: function() { return 0; } + elapsed: function() { + return 0; + } }; -}; \ No newline at end of file +}; diff --git a/src/core/TreeProcessor.js b/src/core/TreeProcessor.js index d17b5d55..469c1009 100644 --- a/src/core/TreeProcessor.js +++ b/src/core/TreeProcessor.js @@ -1,16 +1,24 @@ getJasmineRequireObj().TreeProcessor = function() { function TreeProcessor(attrs) { var tree = attrs.tree, - runnableIds = attrs.runnableIds, - queueRunnerFactory = attrs.queueRunnerFactory, - nodeStart = attrs.nodeStart || function() {}, - nodeComplete = attrs.nodeComplete || function() {}, - orderChildren = attrs.orderChildren || function(node) { return node.children; }, - excludeNode = attrs.excludeNode || function(node) { return false; }, - stats = { valid: true }, - processed = false, - defaultMin = Infinity, - defaultMax = 1 - Infinity; + runnableIds = attrs.runnableIds, + queueRunnerFactory = attrs.queueRunnerFactory, + nodeStart = attrs.nodeStart || function() {}, + nodeComplete = attrs.nodeComplete || function() {}, + orderChildren = + attrs.orderChildren || + function(node) { + return node.children; + }, + excludeNode = + attrs.excludeNode || + function(node) { + return false; + }, + stats = { valid: true }, + processed = false, + defaultMin = Infinity, + defaultMax = 1 - Infinity; this.processTree = function() { processNode(tree, true); @@ -59,13 +67,15 @@ getJasmineRequireObj().TreeProcessor = function() { stats[node.id] = { excluded: excluded, willExecute: !excluded && !node.markedPending, - segments: [{ - index: 0, - owner: node, - nodes: [node], - min: startingMin(executableIndex), - max: startingMax(executableIndex) - }] + segments: [ + { + index: 0, + owner: node, + nodes: [node], + min: startingMin(executableIndex), + max: startingMax(executableIndex) + } + ] }; } else { var hasExecutableChild = false; @@ -107,14 +117,29 @@ getJasmineRequireObj().TreeProcessor = function() { return executableIndex === undefined ? defaultMax : executableIndex; } - function segmentChildren(node, orderedChildren, nodeStats, executableIndex) { - var currentSegment = { index: 0, owner: node, nodes: [], min: startingMin(executableIndex), max: startingMax(executableIndex) }, - result = [currentSegment], - lastMax = defaultMax, - orderedChildSegments = orderChildSegments(orderedChildren); + function segmentChildren( + node, + orderedChildren, + nodeStats, + executableIndex + ) { + var currentSegment = { + index: 0, + owner: node, + nodes: [], + min: startingMin(executableIndex), + max: startingMax(executableIndex) + }, + result = [currentSegment], + lastMax = defaultMax, + orderedChildSegments = orderChildSegments(orderedChildren); function isSegmentBoundary(minIndex) { - return lastMax !== defaultMax && minIndex !== defaultMin && lastMax < minIndex - 1; + return ( + lastMax !== defaultMax && + minIndex !== defaultMin && + lastMax < minIndex - 1 + ); } for (var i = 0; i < orderedChildSegments.length; i++) { @@ -123,7 +148,13 @@ getJasmineRequireObj().TreeProcessor = function() { minIndex = childSegment.min; if (isSegmentBoundary(minIndex)) { - currentSegment = {index: result.length, owner: node, nodes: [], min: defaultMin, max: defaultMax}; + currentSegment = { + index: result.length, + owner: node, + nodes: [], + min: defaultMin, + max: defaultMax + }; result.push(currentSegment); } @@ -138,11 +169,11 @@ getJasmineRequireObj().TreeProcessor = function() { function orderChildSegments(children) { var specifiedOrder = [], - unspecifiedOrder = []; + unspecifiedOrder = []; for (var i = 0; i < children.length; i++) { var child = children[i], - segments = stats[child.id].segments; + segments = stats[child.id].segments; for (var j = 0; j < segments.length; j++) { var seg = segments[j]; @@ -173,7 +204,7 @@ getJasmineRequireObj().TreeProcessor = function() { }; queueRunnerFactory({ - onComplete: function () { + onComplete: function() { var args = Array.prototype.slice.call(arguments, [0]); node.cleanupBeforeAfter(); nodeComplete(node, node.getResult(), function() { @@ -182,7 +213,7 @@ getJasmineRequireObj().TreeProcessor = function() { }, queueableFns: [onStart].concat(wrapChildren(node, segmentNumber)), userContext: node.sharedUserContext(), - onException: function () { + onException: function() { node.onException.apply(node, arguments); } }); @@ -190,17 +221,21 @@ getJasmineRequireObj().TreeProcessor = function() { }; } else { return { - fn: function(done) { node.execute(done, stats[node.id].excluded); } + fn: function(done) { + node.execute(done, stats[node.id].excluded); + } }; } } function wrapChildren(node, segmentNumber) { var result = [], - segmentChildren = stats[node.id].segments[segmentNumber].nodes; + segmentChildren = stats[node.id].segments[segmentNumber].nodes; for (var i = 0; i < segmentChildren.length; i++) { - result.push(executeNode(segmentChildren[i].owner, segmentChildren[i].index)); + result.push( + executeNode(segmentChildren[i].owner, segmentChildren[i].index) + ); } if (!stats[node.id].willExecute) { diff --git a/src/core/UserContext.js b/src/core/UserContext.js index 3b82ce8e..83e253fa 100644 --- a/src/core/UserContext.js +++ b/src/core/UserContext.js @@ -1,6 +1,5 @@ getJasmineRequireObj().UserContext = function(j$) { - function UserContext() { - } + function UserContext() {} UserContext.fromExisting = function(oldContext) { var context = new UserContext(); @@ -14,5 +13,5 @@ getJasmineRequireObj().UserContext = function(j$) { return context; }; - return UserContext; + return UserContext; }; diff --git a/src/core/base.js b/src/core/base.js index 9c8be408..40faa4ce 100644 --- a/src/core/base.js +++ b/src/core/base.js @@ -40,7 +40,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @return {Env} */ j$.getEnv = function(options) { - var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options); + var env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); //jasmine. singletons in here (setTimeout blah blah). return env; }; @@ -50,7 +50,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; j$.isObject_ = function(value) { - return !j$.util.isUndefined(value) && value !== null && j$.isA_('Object', value); + return ( + !j$.util.isUndefined(value) && value !== null && j$.isA_('Object', value) + ); }; j$.isString_ = function(value) { @@ -70,7 +72,8 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; j$.isTypedArray_ = function(value) { - return j$.isA_('Float32Array', value) || + return ( + j$.isA_('Float32Array', value) || j$.isA_('Float64Array', value) || j$.isA_('Int16Array', value) || j$.isA_('Int32Array', value) || @@ -78,7 +81,8 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { j$.isA_('Uint16Array', value) || j$.isA_('Uint32Array', value) || j$.isA_('Uint8Array', value) || - j$.isA_('Uint8ClampedArray', value); + j$.isA_('Uint8ClampedArray', value) + ); }; j$.isA_ = function(typeName, value) { @@ -108,9 +112,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { j$.isDomNode = function(obj) { // Node is a function, because constructors - return typeof jasmineGlobal.Node !== 'undefined' ? - obj instanceof jasmineGlobal.Node : - obj !== null && + return typeof jasmineGlobal.Node !== 'undefined' + ? obj instanceof jasmineGlobal.Node + : obj !== null && typeof obj === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string'; @@ -118,15 +122,25 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; j$.isMap = function(obj) { - return typeof jasmineGlobal.Map !== 'undefined' && obj.constructor === jasmineGlobal.Map; + return ( + typeof jasmineGlobal.Map !== 'undefined' && + obj.constructor === jasmineGlobal.Map + ); }; j$.isSet = function(obj) { - return typeof jasmineGlobal.Set !== 'undefined' && obj.constructor === jasmineGlobal.Set; + return ( + typeof jasmineGlobal.Set !== 'undefined' && + obj.constructor === jasmineGlobal.Set + ); }; j$.isPromise = function(obj) { - return typeof jasmineGlobal.Promise !== 'undefined' && !!obj && obj.constructor === jasmineGlobal.Promise; + return ( + typeof jasmineGlobal.Promise !== 'undefined' && + !!obj && + obj.constructor === jasmineGlobal.Promise + ); }; j$.isPromiseLike = function(obj) { @@ -138,7 +152,8 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return func.name; } - var matches = func.toString().match(/^\s*function\s*(\w+)\s*\(/) || + var matches = + func.toString().match(/^\s*function\s*(\w+)\s*\(/) || func.toString().match(/^\s*\[object\s*(\w+)Constructor\]/); return matches ? matches[1] : ''; @@ -171,7 +186,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @name jasmine.truthy * @function */ - j$.truthy = function() { return new j$.Truthy(); }; + j$.truthy = function() { + return new j$.Truthy(); + }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), @@ -179,7 +196,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @name jasmine.falsy * @function */ - j$.falsy = function() { return new j$.Falsy(); }; + j$.falsy = function() { + return new j$.Falsy(); + }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), @@ -187,7 +206,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @name jasmine.empty * @function */ - j$.empty = function() { return new j$.Empty(); }; + j$.empty = function() { + return new j$.Empty(); + }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), @@ -195,7 +216,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @name jasmine.notEmpty * @function */ - j$.notEmpty = function() { return new j$.NotEmpty(); }; + j$.notEmpty = function() { + return new j$.NotEmpty(); + }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), @@ -245,7 +268,9 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { if (!putativeSpy) { return false; } - return putativeSpy.and instanceof j$.SpyStrategy && - putativeSpy.calls instanceof j$.CallTracker; + return ( + putativeSpy.and instanceof j$.SpyStrategy && + putativeSpy.calls instanceof j$.CallTracker + ); }; }; diff --git a/src/core/errors.js b/src/core/errors.js index e3683c5a..ba7a502d 100644 --- a/src/core/errors.js +++ b/src/core/errors.js @@ -7,4 +7,4 @@ getJasmineRequireObj().errors = function() { return { ExpectationFailed: ExpectationFailed }; -}; \ No newline at end of file +}; diff --git a/src/core/requireCore.js b/src/core/requireCore.js index 622bc8c0..d6b98eb5 100644 --- a/src/core/requireCore.js +++ b/src/core/requireCore.js @@ -1,8 +1,12 @@ -var getJasmineRequireObj = (function (jasmineGlobal) { - /* globals exports, global, module, window */ +// eslint-disable-next-line no-unused-vars +var getJasmineRequireObj = (function(jasmineGlobal) { var jasmineRequire; - if (typeof module !== 'undefined' && module.exports && typeof exports !== 'undefined') { + if ( + typeof module !== 'undefined' && + module.exports && + typeof exports !== 'undefined' + ) { if (typeof global !== 'undefined') { jasmineGlobal = global; } else { @@ -10,7 +14,11 @@ var getJasmineRequireObj = (function (jasmineGlobal) { } jasmineRequire = exports; } else { - if (typeof window !== 'undefined' && typeof window.toString === 'function' && window.toString() === '[object GjsGlobal]') { + if ( + typeof window !== 'undefined' && + typeof window.toString === 'function' && + window.toString() === '[object GjsGlobal]' + ) { jasmineGlobal = window; } jasmineRequire = jasmineGlobal.jasmineRequire = {}; diff --git a/src/core/requireInterface.js b/src/core/requireInterface.js index c2d6de8e..cff7403b 100644 --- a/src/core/requireInterface.js +++ b/src/core/requireInterface.js @@ -203,7 +203,7 @@ getJasmineRequireObj().interface = function(jasmine, env) { * @function * @global * @param {String|Error} [error] - Reason for the failure. - */ + */ fail: function() { return env.fail.apply(env, arguments); }, diff --git a/src/core/util.js b/src/core/util.js index f885d2cb..0c25382a 100644 --- a/src/core/util.js +++ b/src/core/util.js @@ -1,10 +1,8 @@ getJasmineRequireObj().util = function(j$) { - var util = {}; util.inherit = function(childClass, parentClass) { - var Subclass = function() { - }; + var Subclass = function() {}; Subclass.prototype = parentClass.prototype; childClass.prototype = new Subclass(); }; @@ -13,7 +11,8 @@ getJasmineRequireObj().util = function(j$) { if (!str) { return str; } - return str.replace(/&/g, '&') + return str + .replace(/&/g, '&') .replace(//g, '>'); }; @@ -58,7 +57,7 @@ getJasmineRequireObj().util = function(j$) { util.cloneArgs = function(args) { var clonedArgs = []; var argsAsArray = j$.util.argsToArray(args); - for(var i = 0; i < argsAsArray.length; i++) { + for (var i = 0; i < argsAsArray.length; i++) { var str = Object.prototype.toString.apply(argsAsArray[i]), primitives = /^\[object (Boolean|String|RegExp|Number)/; @@ -100,7 +99,7 @@ getJasmineRequireObj().util = function(j$) { return Object.prototype.hasOwnProperty.call(obj, key); }; - util.errorWithStack = function errorWithStack () { + util.errorWithStack = function errorWithStack() { // Don't throw and catch if we don't have to, because it makes it harder // for users to debug their code with exception breakpoints. var error = new Error(); @@ -132,7 +131,7 @@ getJasmineRequireObj().util = function(j$) { return result; }; - }()); + })(); return util; }; diff --git a/src/html/HtmlReporter.js b/src/html/HtmlReporter.js index 880f9558..2a89aaca 100644 --- a/src/html/HtmlReporter.js +++ b/src/html/HtmlReporter.js @@ -23,8 +23,7 @@ jasmineRequire.HtmlReporter = function(j$) { } }; - ResultsStateBuilder.prototype.specStarted = function(result) { - }; + ResultsStateBuilder.prototype.specStarted = function(result) {}; ResultsStateBuilder.prototype.specDone = function(result) { this.currentParent.addChild(result, 'spec'); @@ -42,15 +41,16 @@ jasmineRequire.HtmlReporter = function(j$) { } }; - - function HtmlReporter(options) { - var config = function() { return (options.env && options.env.configuration()) || {}; }, + var config = function() { + return (options.env && options.env.configuration()) || {}; + }, getContainer = options.getContainer, createElement = options.createElement, createTextNode = options.createTextNode, navigateWithNewParam = options.navigateWithNewParam || function() {}, - addToExistingQueryString = options.addToExistingQueryString || defaultQueryString, + addToExistingQueryString = + options.addToExistingQueryString || defaultQueryString, filterSpecs = options.filterSpecs, timer = options.timer || j$.noopTimer, htmlReporterMain, @@ -59,15 +59,25 @@ jasmineRequire.HtmlReporter = function(j$) { this.initialize = function() { clearPrior(); - htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'}, - createDom('div', {className: 'jasmine-banner'}, - createDom('a', {className: 'jasmine-title', href: 'http://jasmine.github.io/', target: '_blank'}), - createDom('span', {className: 'jasmine-version'}, j$.version) + htmlReporterMain = createDom( + 'div', + { className: 'jasmine_html-reporter' }, + createDom( + 'div', + { className: 'jasmine-banner' }, + createDom('a', { + className: 'jasmine-title', + href: 'http://jasmine.github.io/', + target: '_blank' + }), + createDom('span', { className: 'jasmine-version' }, j$.version) ), - createDom('ul', {className: 'jasmine-symbol-summary'}), - createDom('div', {className: 'jasmine-alert'}), - createDom('div', {className: 'jasmine-results'}, - createDom('div', {className: 'jasmine-failures'}) + createDom('ul', { className: 'jasmine-symbol-summary' }), + createDom('div', { className: 'jasmine-alert' }), + createDom( + 'div', + { className: 'jasmine-results' }, + createDom('div', { className: 'jasmine-failures' }) ) ); getContainer().appendChild(htmlReporterMain); @@ -79,7 +89,7 @@ jasmineRequire.HtmlReporter = function(j$) { timer.start(); }; - var summary = createDom('div', {className: 'jasmine-summary'}); + var summary = createDom('div', { className: 'jasmine-summary' }); var stateBuilder = new ResultsStateBuilder(); @@ -104,20 +114,25 @@ jasmineRequire.HtmlReporter = function(j$) { this.specDone = function(result) { stateBuilder.specDone(result); - if(noExpectations(result) && typeof console !== 'undefined' && typeof console.error !== 'undefined') { - console.error('Spec \'' + result.fullName + '\' has no expectations.'); + if ( + noExpectations(result) && + typeof console !== 'undefined' && + typeof console.error !== 'undefined' + ) { + console.error("Spec '" + result.fullName + "' has no expectations."); } if (!symbols) { symbols = find('.jasmine-symbol-summary'); } - symbols.appendChild(createDom('li', { + symbols.appendChild( + createDom('li', { className: this.displaySpecInCorrectFormat(result), id: 'spec_' + result.id, title: result.fullName - } - )); + }) + ); if (result.status === 'failed') { failures.push(failureDom(result)); @@ -127,12 +142,16 @@ jasmineRequire.HtmlReporter = function(j$) { }; this.displaySpecInCorrectFormat = function(result) { - return noExpectations(result) ? 'jasmine-empty' : this.resultStatus(result.status); + return noExpectations(result) + ? 'jasmine-empty' + : this.resultStatus(result.status); }; this.resultStatus = function(status) { - if(status === 'excluded') { - return config().hideDisabled ? 'jasmine-excluded-no-display' : 'jasmine-excluded'; + if (status === 'excluded') { + return config().hideDisabled + ? 'jasmine-excluded-no-display' + : 'jasmine-excluded'; } return 'jasmine-' + status; }; @@ -142,16 +161,33 @@ jasmineRequire.HtmlReporter = function(j$) { var alert = find('.jasmine-alert'); var order = doneResult && doneResult.order; var i; - alert.appendChild(createDom('span', {className: 'jasmine-duration'}, 'finished in ' + timer.elapsed() / 1000 + 's')); + alert.appendChild( + createDom( + 'span', + { className: 'jasmine-duration' }, + 'finished in ' + timer.elapsed() / 1000 + 's' + ) + ); banner.appendChild(optionsMenu(config())); if (stateBuilder.specsExecuted < totalSpecsDefined) { - var skippedMessage = 'Ran ' + stateBuilder.specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all'; + var skippedMessage = + 'Ran ' + + stateBuilder.specsExecuted + + ' of ' + + totalSpecsDefined + + ' specs - run all'; var skippedLink = addToExistingQueryString('spec', ''); alert.appendChild( - createDom('span', {className: 'jasmine-bar jasmine-skipped'}, - createDom('a', {href: skippedLink, title: 'Run all specs'}, skippedMessage) + createDom( + 'span', + { className: 'jasmine-bar jasmine-skipped' }, + createDom( + 'a', + { href: skippedLink, title: 'Run all specs' }, + skippedMessage + ) ) ); } @@ -161,34 +197,66 @@ jasmineRequire.HtmlReporter = function(j$) { var failed = stateBuilder.failureCount + globalFailures.length > 0; if (totalSpecsDefined > 0 || failed) { - statusBarMessage += pluralize('spec', stateBuilder.specsExecuted) + ', ' + pluralize('failure', stateBuilder.failureCount); - if (stateBuilder.pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', stateBuilder.pendingSpecCount); } + statusBarMessage += + pluralize('spec', stateBuilder.specsExecuted) + + ', ' + + pluralize('failure', stateBuilder.failureCount); + if (stateBuilder.pendingSpecCount) { + statusBarMessage += + ', ' + pluralize('pending spec', stateBuilder.pendingSpecCount); + } } if (doneResult.overallStatus === 'passed') { statusBarClassName += ' jasmine-passed '; } else if (doneResult.overallStatus === 'incomplete') { statusBarClassName += ' jasmine-incomplete '; - statusBarMessage = 'Incomplete: ' + doneResult.incompleteReason + ', ' + statusBarMessage; + statusBarMessage = + 'Incomplete: ' + + doneResult.incompleteReason + + ', ' + + statusBarMessage; } else { statusBarClassName += ' jasmine-failed '; } var seedBar; if (order && order.random) { - seedBar = createDom('span', {className: 'jasmine-seed-bar'}, + seedBar = createDom( + 'span', + { className: 'jasmine-seed-bar' }, ', randomized with seed ', - createDom('a', {title: 'randomized with seed ' + order.seed, href: seedHref(order.seed)}, order.seed) + createDom( + 'a', + { + title: 'randomized with seed ' + order.seed, + href: seedHref(order.seed) + }, + order.seed + ) ); } - alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage, seedBar)); + alert.appendChild( + createDom( + 'span', + { className: statusBarClassName }, + statusBarMessage, + seedBar + ) + ); var errorBarClassName = 'jasmine-bar jasmine-errored'; var afterAllMessagePrefix = 'AfterAll '; - for(i = 0; i < globalFailures.length; i++) { - alert.appendChild(createDom('span', {className: errorBarClassName}, globalFailureMessage(globalFailures[i]))); + for (i = 0; i < globalFailures.length; i++) { + alert.appendChild( + createDom( + 'span', + { className: errorBarClassName }, + globalFailureMessage(globalFailures[i]) + ) + ); } function globalFailureMessage(failure) { @@ -196,7 +264,9 @@ jasmineRequire.HtmlReporter = function(j$) { var prefix = 'Error during loading: ' + failure.message; if (failure.filename) { - return prefix + ' in ' + failure.filename + ' line ' + failure.lineno; + return ( + prefix + ' in ' + failure.filename + ' line ' + failure.lineno + ); } else { return prefix; } @@ -208,9 +278,15 @@ jasmineRequire.HtmlReporter = function(j$) { addDeprecationWarnings(doneResult); var warningBarClassName = 'jasmine-bar jasmine-warning'; - for(i = 0; i < deprecationWarnings.length; i++) { + for (i = 0; i < deprecationWarnings.length; i++) { var warning = deprecationWarnings[i]; - alert.appendChild(createDom('span', {className: warningBarClassName}, 'DEPRECATION: ' + warning)); + alert.appendChild( + createDom( + 'span', + { className: warningBarClassName }, + 'DEPRECATION: ' + warning + ) + ); } var results = find('.jasmine-results'); @@ -220,13 +296,29 @@ jasmineRequire.HtmlReporter = function(j$) { if (failures.length) { alert.appendChild( - createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-spec-list'}, + createDom( + 'span', + { className: 'jasmine-menu jasmine-bar jasmine-spec-list' }, createDom('span', {}, 'Spec List | '), - createDom('a', {className: 'jasmine-failures-menu', href: '#'}, 'Failures'))); + createDom( + 'a', + { className: 'jasmine-failures-menu', href: '#' }, + 'Failures' + ) + ) + ); alert.appendChild( - createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-failure-list'}, - createDom('a', {className: 'jasmine-spec-list-menu', href: '#'}, 'Spec List'), - createDom('span', {}, ' | Failures '))); + createDom( + 'span', + { className: 'jasmine-menu jasmine-bar jasmine-failure-list' }, + createDom( + 'a', + { className: 'jasmine-spec-list-menu', href: '#' }, + 'Spec List' + ), + createDom('span', {}, ' | Failures ') + ) + ); find('.jasmine-failures-menu').onclick = function() { setMenuModeTo('jasmine-failure-list'); @@ -247,17 +339,30 @@ jasmineRequire.HtmlReporter = function(j$) { return this; function failureDom(result) { - var failure = - createDom('div', {className: 'jasmine-spec-detail jasmine-failed'}, - failureDescription(result, stateBuilder.currentParent), - createDom('div', {className: 'jasmine-messages'}) - ); + var failure = createDom( + 'div', + { className: 'jasmine-spec-detail jasmine-failed' }, + failureDescription(result, stateBuilder.currentParent), + createDom('div', { className: 'jasmine-messages' }) + ); var messages = failure.childNodes[1]; for (var i = 0; i < result.failedExpectations.length; i++) { var expectation = result.failedExpectations[i]; - messages.appendChild(createDom('div', {className: 'jasmine-result-message'}, expectation.message)); - messages.appendChild(createDom('div', {className: 'jasmine-stack-trace'}, expectation.stack)); + messages.appendChild( + createDom( + 'div', + { className: 'jasmine-result-message' }, + expectation.message + ) + ); + messages.appendChild( + createDom( + 'div', + { className: 'jasmine-stack-trace' }, + expectation.stack + ) + ); } return failure; @@ -271,9 +376,20 @@ jasmineRequire.HtmlReporter = function(j$) { continue; } if (resultNode.type === 'suite') { - var suiteListNode = createDom('ul', {className: 'jasmine-suite', id: 'suite-' + resultNode.result.id}, - createDom('li', {className: 'jasmine-suite-detail jasmine-' + resultNode.result.status}, - createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description) + var suiteListNode = createDom( + 'ul', + { className: 'jasmine-suite', id: 'suite-' + resultNode.result.id }, + createDom( + 'li', + { + className: + 'jasmine-suite-detail jasmine-' + resultNode.result.status + }, + createDom( + 'a', + { href: specHref(resultNode.result) }, + resultNode.result.description + ) ) ); @@ -282,22 +398,34 @@ jasmineRequire.HtmlReporter = function(j$) { } if (resultNode.type === 'spec') { if (domParent.getAttribute('class') !== 'jasmine-specs') { - specListNode = createDom('ul', {className: 'jasmine-specs'}); + specListNode = createDom('ul', { className: 'jasmine-specs' }); domParent.appendChild(specListNode); } var specDescription = resultNode.result.description; - if(noExpectations(resultNode.result)) { + if (noExpectations(resultNode.result)) { specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; } - if(resultNode.result.status === 'pending' && resultNode.result.pendingReason !== '') { - specDescription = specDescription + ' PENDING WITH MESSAGE: ' + resultNode.result.pendingReason; + if ( + resultNode.result.status === 'pending' && + resultNode.result.pendingReason !== '' + ) { + specDescription = + specDescription + + ' PENDING WITH MESSAGE: ' + + resultNode.result.pendingReason; } specListNode.appendChild( - createDom('li', { + createDom( + 'li', + { className: 'jasmine-' + resultNode.result.status, id: 'spec-' + resultNode.result.id }, - createDom('a', {href: specHref(resultNode.result)}, specDescription) + createDom( + 'a', + { href: specHref(resultNode.result) }, + specDescription + ) ) ); } @@ -305,37 +433,69 @@ jasmineRequire.HtmlReporter = function(j$) { } function optionsMenu(config) { - var optionsMenuDom = createDom('div', { className: 'jasmine-run-options' }, + var optionsMenuDom = createDom( + 'div', + { className: 'jasmine-run-options' }, createDom('span', { className: 'jasmine-trigger' }, 'Options'), - createDom('div', { className: 'jasmine-payload' }, - createDom('div', { className: 'jasmine-stop-on-failure' }, + createDom( + 'div', + { className: 'jasmine-payload' }, + createDom( + 'div', + { className: 'jasmine-stop-on-failure' }, createDom('input', { className: 'jasmine-fail-fast', id: 'jasmine-fail-fast', type: 'checkbox' }), - createDom('label', { className: 'jasmine-label', 'for': 'jasmine-fail-fast' }, 'stop execution on spec failure')), - createDom('div', { className: 'jasmine-throw-failures' }, + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-fail-fast' }, + 'stop execution on spec failure' + ) + ), + createDom( + 'div', + { className: 'jasmine-throw-failures' }, createDom('input', { className: 'jasmine-throw', id: 'jasmine-throw-failures', type: 'checkbox' }), - createDom('label', { className: 'jasmine-label', 'for': 'jasmine-throw-failures' }, 'stop spec on expectation failure')), - createDom('div', { className: 'jasmine-random-order' }, + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-throw-failures' }, + 'stop spec on expectation failure' + ) + ), + createDom( + 'div', + { className: 'jasmine-random-order' }, createDom('input', { className: 'jasmine-random', id: 'jasmine-random-order', type: 'checkbox' }), - createDom('label', { className: 'jasmine-label', 'for': 'jasmine-random-order' }, 'run tests in random order')), - createDom('div', { className: 'jasmine-hide-disabled' }, + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-random-order' }, + 'run tests in random order' + ) + ), + createDom( + 'div', + { className: 'jasmine-hide-disabled' }, createDom('input', { className: 'jasmine-disabled', id: 'jasmine-hide-disabled', type: 'checkbox' }), - createDom('label', { className: 'jasmine-label', 'for': 'jasmine-hide-disabled' }, 'hide disabled tests')) + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-hide-disabled' }, + 'hide disabled tests' + ) + ) ) ); @@ -345,13 +505,17 @@ jasmineRequire.HtmlReporter = function(j$) { navigateWithNewParam('failFast', !config.failFast); }; - var throwCheckbox = optionsMenuDom.querySelector('#jasmine-throw-failures'); + var throwCheckbox = optionsMenuDom.querySelector( + '#jasmine-throw-failures' + ); throwCheckbox.checked = config.oneFailurePerSpec; throwCheckbox.onclick = function() { navigateWithNewParam('throwFailures', !config.oneFailurePerSpec); }; - var randomCheckbox = optionsMenuDom.querySelector('#jasmine-random-order'); + var randomCheckbox = optionsMenuDom.querySelector( + '#jasmine-random-order' + ); randomCheckbox.checked = config.random; randomCheckbox.onclick = function() { navigateWithNewParam('random', !config.random); @@ -369,7 +533,10 @@ jasmineRequire.HtmlReporter = function(j$) { optionsTrigger.onclick = function() { if (isOpen.test(optionsPayload.className)) { - optionsPayload.className = optionsPayload.className.replace(isOpen, ''); + optionsPayload.className = optionsPayload.className.replace( + isOpen, + '' + ); } else { optionsPayload.className += ' jasmine-open'; } @@ -379,14 +546,24 @@ jasmineRequire.HtmlReporter = function(j$) { } function failureDescription(result, suite) { - var wrapper = createDom('div', {className: 'jasmine-description'}, - createDom('a', {title: result.description, href: specHref(result)}, result.description) + var wrapper = createDom( + 'div', + { className: 'jasmine-description' }, + createDom( + 'a', + { title: result.description, href: specHref(result) }, + result.description + ) ); var suiteLink; while (suite && suite.parent) { wrapper.insertBefore(createTextNode(' > '), wrapper.firstChild); - suiteLink = createDom('a', {href: suiteHref(suite)}, suite.result.description); + suiteLink = createDom( + 'a', + { href: suiteHref(suite) }, + suite.result.description + ); wrapper.insertBefore(suiteLink, wrapper.firstChild); suite = suite.parent; @@ -408,7 +585,7 @@ jasmineRequire.HtmlReporter = function(j$) { function addDeprecationWarnings(result) { if (result && result.deprecationWarnings) { - for(var i = 0; i < result.deprecationWarnings.length; i++) { + for (var i = 0; i < result.deprecationWarnings.length; i++) { var warning = result.deprecationWarnings[i].message; if (!j$.util.arrayContains(warning)) { deprecationWarnings.push(warning); @@ -425,7 +602,7 @@ jasmineRequire.HtmlReporter = function(j$) { // return the reporter var oldReporter = find(''); - if(oldReporter) { + if (oldReporter) { getContainer().removeChild(oldReporter); } } @@ -457,7 +634,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function pluralize(singular, count) { - var word = (count == 1 ? singular : singular + 's'); + var word = count == 1 ? singular : singular + 's'; return '' + count + ' ' + word; } @@ -479,8 +656,10 @@ jasmineRequire.HtmlReporter = function(j$) { } function noExpectations(result) { - return (result.failedExpectations.length + result.passedExpectations.length) === 0 && - result.status === 'passed'; + return ( + result.failedExpectations.length + result.passedExpectations.length === + 0 && result.status === 'passed' + ); } function hasActiveSpec(resultNode) { diff --git a/src/html/HtmlSpecFilter.js b/src/html/HtmlSpecFilter.js index 3d0a6c23..7a18f1ec 100644 --- a/src/html/HtmlSpecFilter.js +++ b/src/html/HtmlSpecFilter.js @@ -1,6 +1,9 @@ jasmineRequire.HtmlSpecFilter = function() { function HtmlSpecFilter(options) { - var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); + var filterString = + options && + options.filterString() && + options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); var filterPattern = new RegExp(filterString); this.matches = function(specName) { diff --git a/src/html/QueryString.js b/src/html/QueryString.js index a72d92d8..c4ce950e 100644 --- a/src/html/QueryString.js +++ b/src/html/QueryString.js @@ -1,8 +1,10 @@ jasmineRequire.QueryString = function() { function QueryString(options) { - this.navigateWithNewParam = function(key, value) { - options.getWindowLocation().search = this.fullStringWithNewParam(key, value); + options.getWindowLocation().search = this.fullStringWithNewParam( + key, + value + ); }; this.fullStringWithNewParam = function(key, value) { @@ -20,7 +22,9 @@ jasmineRequire.QueryString = function() { function toQueryString(paramMap) { var qStrPairs = []; for (var prop in paramMap) { - qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop])); + qStrPairs.push( + encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]) + ); } return '?' + qStrPairs.join('&'); } @@ -44,7 +48,6 @@ jasmineRequire.QueryString = function() { return paramMap; } - } return QueryString;