From 135ff20123d91da374a4ae5ed41ebdb36535c6f6 Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Wed, 8 Jun 2022 19:07:43 -0700 Subject: [PATCH] Replaced uses of var with const/let --- lib/jasmine-core.js | 18 +- lib/jasmine-core/boot0.js | 10 +- lib/jasmine-core/boot1.js | 18 +- lib/jasmine-core/jasmine-html.js | 175 +-- lib/jasmine-core/jasmine.js | 1164 ++++++++--------- lib/jasmine-core/node_boot.js | 8 +- package.json | 3 +- spec/.eslintrc.js | 2 - spec/support/ci.js | 2 +- src/boot/boot0.js | 10 +- src/boot/boot1.js | 18 +- src/boot/node_boot.js | 8 +- src/core/CallTracker.js | 15 +- src/core/ClearStack.js | 22 +- src/core/Clock.js | 18 +- src/core/DelayedFunctionScheduler.js | 40 +- src/core/Deprecator.js | 8 +- src/core/Env.js | 193 +-- src/core/ExpectationFilterChain.js | 6 +- src/core/Expector.js | 16 +- src/core/GlobalErrors.js | 26 +- src/core/JsApiReporter.js | 10 +- src/core/MockDate.js | 6 +- src/core/Order.js | 6 +- src/core/QueueRunner.js | 120 +- src/core/ReportDispatcher.js | 20 +- src/core/Spec.js | 14 +- src/core/Spy.js | 62 +- src/core/SpyFactory.js | 27 +- src/core/SpyRegistry.js | 59 +- src/core/SpyStrategy.js | 17 +- src/core/StackTrace.js | 32 +- src/core/Suite.js | 8 +- src/core/Timer.js | 6 +- src/core/TreeProcessor.js | 82 +- src/core/UserContext.js | 4 +- .../asymmetric_equality/ArrayContaining.js | 3 +- .../ArrayWithExactContents.js | 3 +- src/core/asymmetric_equality/MapContaining.js | 2 +- .../asymmetric_equality/ObjectContaining.js | 4 +- src/core/asymmetric_equality/SetContaining.js | 2 +- src/core/base.js | 8 +- src/core/formatErrorMsg.js | 2 +- src/core/matchers/async/toBePending.js | 2 +- .../matchers/async/toBeRejectedWithError.js | 6 +- src/core/matchers/matchersUtil.js | 140 +- src/core/matchers/requireAsyncMatchers.js | 5 +- src/core/matchers/requireMatchers.js | 5 +- src/core/matchers/toBe.js | 4 +- src/core/matchers/toBeCloseTo.js | 6 +- src/core/matchers/toBeInstanceOf.js | 20 +- src/core/matchers/toBeNaN.js | 2 +- src/core/matchers/toBeNegativeInfinity.js | 2 +- src/core/matchers/toBePositiveInfinity.js | 2 +- src/core/matchers/toEqual.js | 2 +- src/core/matchers/toHaveBeenCalled.js | 4 +- src/core/matchers/toHaveBeenCalledBefore.js | 12 +- src/core/matchers/toHaveBeenCalledOnceWith.js | 8 +- src/core/matchers/toHaveBeenCalledTimes.js | 8 +- src/core/matchers/toHaveBeenCalledWith.js | 10 +- src/core/matchers/toHaveSize.js | 4 +- src/core/matchers/toHaveSpyInteractions.js | 4 +- src/core/matchers/toMatch.js | 4 +- src/core/matchers/toThrow.js | 8 +- src/core/matchers/toThrowError.js | 21 +- src/core/matchers/toThrowMatching.js | 6 +- src/core/requireCore.js | 6 +- src/core/requireInterface.js | 2 +- src/core/util.js | 30 +- src/html/HtmlReporter.js | 152 +-- src/html/HtmlSpecFilter.js | 4 +- src/html/QueryString.js | 18 +- src/html/requireHtml.js | 1 + 73 files changed, 1384 insertions(+), 1391 deletions(-) diff --git a/lib/jasmine-core.js b/lib/jasmine-core.js index 314ff9e7..718adcd5 100644 --- a/lib/jasmine-core.js +++ b/lib/jasmine-core.js @@ -37,16 +37,16 @@ module.exports.noGlobals = (function() { }; }()); -var path = require('path'), - fs = require('fs'); +const path = require('path'), + fs = require('fs'); -var rootPath = path.join(__dirname, "jasmine-core"), - bootFiles = ['boot0.js', 'boot1.js'], - legacyBootFiles = ['boot.js'], - nodeBootFiles = ['node_boot.js'], - cssFiles = [], - jsFiles = [], - jsFilesToSkip = ['jasmine.js'].concat(bootFiles, legacyBootFiles, nodeBootFiles); +const rootPath = path.join(__dirname, 'jasmine-core'), + bootFiles = ['boot0.js', 'boot1.js'], + legacyBootFiles = ['boot.js'], + nodeBootFiles = ['node_boot.js'], + cssFiles = [], + jsFiles = [], + jsFilesToSkip = ['jasmine.js'].concat(bootFiles, legacyBootFiles, nodeBootFiles); fs.readdirSync(rootPath).forEach(function(file) { if(fs.statSync(path.join(rootPath, file)).isFile()) { diff --git a/lib/jasmine-core/boot0.js b/lib/jasmine-core/boot0.js index 03186b00..c773ba8e 100644 --- a/lib/jasmine-core/boot0.js +++ b/lib/jasmine-core/boot0.js @@ -27,14 +27,14 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. source files or spec files are loaded. */ (function() { - var jasmineRequire = window.jasmineRequire || require('./jasmine.js'); + const jasmineRequire = window.jasmineRequire || require('./jasmine.js'); /** * ## Require & Instantiate * * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. */ - var jasmine = jasmineRequire.core(jasmineRequire), + const jasmine = jasmineRequire.core(jasmineRequire), global = jasmine.getGlobal(); global.jasmine = jasmine; @@ -46,19 +46,19 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /** * Create the Jasmine environment. This is used to run all specs in a project. */ - var env = jasmine.getEnv(); + const env = jasmine.getEnv(); /** * ## The Global Interface * * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. */ - var jasmineInterface = jasmineRequire.interface(jasmine, env); + const jasmineInterface = jasmineRequire.interface(jasmine, env); /** * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. */ - for (var property in jasmineInterface) { + for (const property in jasmineInterface) { global[property] = jasmineInterface[property]; } })(); diff --git a/lib/jasmine-core/boot1.js b/lib/jasmine-core/boot1.js index 7980a1bb..5fe49e41 100644 --- a/lib/jasmine-core/boot1.js +++ b/lib/jasmine-core/boot1.js @@ -34,7 +34,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function() { - var env = jasmine.getEnv(); + const env = jasmine.getEnv(); /** * ## Runner Parameters @@ -42,15 +42,15 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. */ - var queryString = new jasmine.QueryString({ + const queryString = new jasmine.QueryString({ getWindowLocation: function() { return window.location; } }); - var filterSpecs = !!queryString.getParam('spec'); + const filterSpecs = !!queryString.getParam('spec'); - var config = { + const config = { stopOnSpecFailure: queryString.getParam('stopOnSpecFailure'), stopSpecOnExpectationFailure: queryString.getParam( 'stopSpecOnExpectationFailure' @@ -58,13 +58,13 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. hideDisabled: queryString.getParam('hideDisabled') }; - var random = queryString.getParam('random'); + const random = queryString.getParam('random'); if (random !== undefined && random !== '') { config.random = random; } - var seed = queryString.getParam('seed'); + const seed = queryString.getParam('seed'); if (seed) { config.seed = seed; } @@ -73,7 +73,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ## Reporters * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). */ - var htmlReporter = new jasmine.HtmlReporter({ + const htmlReporter = new jasmine.HtmlReporter({ env: env, navigateWithNewParam: function(key, value) { return queryString.navigateWithNewParam(key, value); @@ -103,7 +103,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /** * Filter which specs will be run by matching the start of the full name against the `spec` query param. */ - var specFilter = new jasmine.HtmlSpecFilter({ + const specFilter = new jasmine.HtmlSpecFilter({ filterString: function() { return queryString.getParam('spec'); } @@ -120,7 +120,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. */ - var currentWindowOnload = window.onload; + const currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { diff --git a/lib/jasmine-core/jasmine-html.js b/lib/jasmine-core/jasmine-html.js index c4d7c8d2..2ebc6d0e 100644 --- a/lib/jasmine-core/jasmine-html.js +++ b/lib/jasmine-core/jasmine-html.js @@ -20,6 +20,7 @@ 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. */ +// eslint-disable-next-line no-var var jasmineRequire = window.jasmineRequire || require('./jasmine.js'); jasmineRequire.html = function(j$) { @@ -79,19 +80,21 @@ jasmineRequire.HtmlReporter = function(j$) { }; function HtmlReporter(options) { - 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, - filterSpecs = options.filterSpecs, - htmlReporterMain, - symbols, - deprecationWarnings = []; + function config() { + return (options.env && options.env.configuration()) || {}; + } + + const getContainer = options.getContainer; + const createElement = options.createElement; + const createTextNode = options.createTextNode; + const navigateWithNewParam = options.navigateWithNewParam || function() {}; + const addToExistingQueryString = + options.addToExistingQueryString || defaultQueryString; + const filterSpecs = options.filterSpecs; + let htmlReporterMain; + let symbols; + const deprecationWarnings = []; + const failures = []; this.initialize = function() { clearPrior(); @@ -119,14 +122,14 @@ jasmineRequire.HtmlReporter = function(j$) { getContainer().appendChild(htmlReporterMain); }; - var totalSpecsDefined; + let totalSpecsDefined; this.jasmineStarted = function(options) { totalSpecsDefined = options.totalSpecsDefined || 0; }; - var summary = createDom('div', { className: 'jasmine-summary' }); + const summary = createDom('div', { className: 'jasmine-summary' }); - var stateBuilder = new ResultsStateBuilder(); + const stateBuilder = new ResultsStateBuilder(); this.suiteStarted = function(result) { stateBuilder.suiteStarted(result); @@ -145,12 +148,11 @@ jasmineRequire.HtmlReporter = function(j$) { stateBuilder.specStarted(result); }; - var failures = []; this.specDone = function(result) { stateBuilder.specDone(result); if (noExpectations(result)) { - var noSpecMsg = "Spec '" + result.fullName + "' has no expectations."; + const noSpecMsg = "Spec '" + result.fullName + "' has no expectations."; if (result.status === 'failed') { console.error(noSpecMsg); } else { @@ -194,10 +196,10 @@ jasmineRequire.HtmlReporter = function(j$) { this.jasmineDone = function(doneResult) { stateBuilder.jasmineDone(doneResult); - var banner = find('.jasmine-banner'); - var alert = find('.jasmine-alert'); - var order = doneResult && doneResult.order; - var i; + const banner = find('.jasmine-banner'); + const alert = find('.jasmine-alert'); + const order = doneResult && doneResult.order; + alert.appendChild( createDom( 'span', @@ -209,14 +211,14 @@ jasmineRequire.HtmlReporter = function(j$) { banner.appendChild(optionsMenu(config())); if (stateBuilder.specsExecuted < totalSpecsDefined) { - var skippedMessage = + const skippedMessage = 'Ran ' + stateBuilder.specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all'; // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 - var skippedLink = + const skippedLink = (window.location.pathname || '') + addToExistingQueryString('spec', ''); alert.appendChild( @@ -231,10 +233,11 @@ jasmineRequire.HtmlReporter = function(j$) { ) ); } - var statusBarMessage = ''; - var statusBarClassName = 'jasmine-overall-result jasmine-bar '; - var globalFailures = (doneResult && doneResult.failedExpectations) || []; - var failed = stateBuilder.failureCount + globalFailures.length > 0; + let statusBarMessage = ''; + let statusBarClassName = 'jasmine-overall-result jasmine-bar '; + const globalFailures = + (doneResult && doneResult.failedExpectations) || []; + const failed = stateBuilder.failureCount + globalFailures.length > 0; if (totalSpecsDefined > 0 || failed) { statusBarMessage += @@ -260,7 +263,7 @@ jasmineRequire.HtmlReporter = function(j$) { statusBarClassName += ' jasmine-failed '; } - var seedBar; + let seedBar; if (order && order.random) { seedBar = createDom( 'span', @@ -286,10 +289,10 @@ jasmineRequire.HtmlReporter = function(j$) { ) ); - var errorBarClassName = 'jasmine-bar jasmine-errored'; - var afterAllMessagePrefix = 'AfterAll '; + const errorBarClassName = 'jasmine-bar jasmine-errored'; + const afterAllMessagePrefix = 'AfterAll '; - for (i = 0; i < globalFailures.length; i++) { + for (let i = 0; i < globalFailures.length; i++) { alert.appendChild( createDom( 'span', @@ -301,7 +304,7 @@ jasmineRequire.HtmlReporter = function(j$) { function globalFailureMessage(failure) { if (failure.globalErrorType === 'load') { - var prefix = 'Error during loading: ' + failure.message; + const prefix = 'Error during loading: ' + failure.message; if (failure.filename) { return ( @@ -319,9 +322,9 @@ jasmineRequire.HtmlReporter = function(j$) { addDeprecationWarnings(doneResult); - for (i = 0; i < deprecationWarnings.length; i++) { - var children = [], - context; + for (let i = 0; i < deprecationWarnings.length; i++) { + const children = []; + let context; switch (deprecationWarnings[i].runnableType) { case 'spec': @@ -355,7 +358,7 @@ jasmineRequire.HtmlReporter = function(j$) { ); } - var results = find('.jasmine-results'); + const results = find('.jasmine-results'); results.appendChild(summary); summaryList(stateBuilder.topResults, summary); @@ -397,8 +400,8 @@ jasmineRequire.HtmlReporter = function(j$) { setMenuModeTo('jasmine-failure-list'); - var failureNode = find('.jasmine-failures'); - for (i = 0; i < failures.length; i++) { + const failureNode = find('.jasmine-failures'); + for (let i = 0; i < failures.length; i++) { failureNode.appendChild(failures[i]); } } @@ -407,16 +410,16 @@ jasmineRequire.HtmlReporter = function(j$) { return this; function failureDom(result) { - var failure = createDom( + const failure = createDom( 'div', { className: 'jasmine-spec-detail jasmine-failed' }, failureDescription(result, stateBuilder.currentParent), createDom('div', { className: 'jasmine-messages' }) ); - var messages = failure.childNodes[1]; + const messages = failure.childNodes[1]; - for (var i = 0; i < result.failedExpectations.length; i++) { - var expectation = result.failedExpectations[i]; + for (let i = 0; i < result.failedExpectations.length; i++) { + const expectation = result.failedExpectations[i]; messages.appendChild( createDom( 'div', @@ -451,7 +454,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function debugLogTable(debugLogs) { - var tbody = createDom('tbody'); + const tbody = createDom('tbody'); debugLogs.forEach(function(entry) { tbody.appendChild( @@ -491,14 +494,14 @@ jasmineRequire.HtmlReporter = function(j$) { } function summaryList(resultsTree, domParent) { - var specListNode; - for (var i = 0; i < resultsTree.children.length; i++) { - var resultNode = resultsTree.children[i]; + let specListNode; + for (let i = 0; i < resultsTree.children.length; i++) { + const resultNode = resultsTree.children[i]; if (filterSpecs && !hasActiveSpec(resultNode)) { continue; } if (resultNode.type === 'suite') { - var suiteListNode = createDom( + const suiteListNode = createDom( 'ul', { className: 'jasmine-suite', id: 'suite-' + resultNode.result.id }, createDom( @@ -523,7 +526,7 @@ jasmineRequire.HtmlReporter = function(j$) { specListNode = createDom('ul', { className: 'jasmine-specs' }); domParent.appendChild(specListNode); } - var specDescription = resultNode.result.description; + let specDescription = resultNode.result.description; if (noExpectations(resultNode.result)) { specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; } @@ -555,7 +558,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function optionsMenu(config) { - var optionsMenuDom = createDom( + const optionsMenuDom = createDom( 'div', { className: 'jasmine-run-options' }, createDom('span', { className: 'jasmine-trigger' }, 'Options'), @@ -621,13 +624,15 @@ jasmineRequire.HtmlReporter = function(j$) { ) ); - var failFastCheckbox = optionsMenuDom.querySelector('#jasmine-fail-fast'); + const failFastCheckbox = optionsMenuDom.querySelector( + '#jasmine-fail-fast' + ); failFastCheckbox.checked = config.stopOnSpecFailure; failFastCheckbox.onclick = function() { navigateWithNewParam('stopOnSpecFailure', !config.stopOnSpecFailure); }; - var throwCheckbox = optionsMenuDom.querySelector( + const throwCheckbox = optionsMenuDom.querySelector( '#jasmine-throw-failures' ); throwCheckbox.checked = config.stopSpecOnExpectationFailure; @@ -638,7 +643,7 @@ jasmineRequire.HtmlReporter = function(j$) { ); }; - var randomCheckbox = optionsMenuDom.querySelector( + const randomCheckbox = optionsMenuDom.querySelector( '#jasmine-random-order' ); randomCheckbox.checked = config.random; @@ -646,13 +651,15 @@ jasmineRequire.HtmlReporter = function(j$) { navigateWithNewParam('random', !config.random); }; - var hideDisabled = optionsMenuDom.querySelector('#jasmine-hide-disabled'); + const hideDisabled = optionsMenuDom.querySelector( + '#jasmine-hide-disabled' + ); hideDisabled.checked = config.hideDisabled; hideDisabled.onclick = function() { navigateWithNewParam('hideDisabled', !config.hideDisabled); }; - var optionsTrigger = optionsMenuDom.querySelector('.jasmine-trigger'), + const optionsTrigger = optionsMenuDom.querySelector('.jasmine-trigger'), optionsPayload = optionsMenuDom.querySelector('.jasmine-payload'), isOpen = /\bjasmine-open\b/; @@ -671,7 +678,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function failureDescription(result, suite) { - var wrapper = createDom( + const wrapper = createDom( 'div', { className: 'jasmine-description' }, createDom( @@ -680,7 +687,7 @@ jasmineRequire.HtmlReporter = function(j$) { result.description ) ); - var suiteLink; + let suiteLink; while (suite && suite.parent) { wrapper.insertBefore(createTextNode(' > '), wrapper.firstChild); @@ -698,7 +705,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function suiteHref(suite) { - var els = []; + const els = []; while (suite && suite.parent) { els.unshift(suite.result.description); @@ -714,8 +721,8 @@ jasmineRequire.HtmlReporter = function(j$) { function addDeprecationWarnings(result, runnableType) { if (result && result.deprecationWarnings) { - for (var i = 0; i < result.deprecationWarnings.length; i++) { - var warning = result.deprecationWarnings[i].message; + for (let i = 0; i < result.deprecationWarnings.length; i++) { + const warning = result.deprecationWarnings[i].message; deprecationWarnings.push({ message: warning, stack: result.deprecationWarnings[i].stack, @@ -727,8 +734,8 @@ jasmineRequire.HtmlReporter = function(j$) { } function createExpander(stackTrace) { - var expandLink = createDom('a', { href: '#' }, 'Show stack trace'); - var root = createDom( + const expandLink = createDom('a', { href: '#' }, 'Show stack trace'); + const root = createDom( 'div', { className: 'jasmine-expander' }, expandLink, @@ -759,8 +766,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function clearPrior() { - // return the reporter - var oldReporter = find(''); + const oldReporter = find(''); if (oldReporter) { getContainer().removeChild(oldReporter); @@ -768,22 +774,21 @@ jasmineRequire.HtmlReporter = function(j$) { } function createDom(type, attrs, childrenArrayOrVarArgs) { - var el = createElement(type), - children, - i; + const el = createElement(type); + let children; if (j$.isArray_(childrenArrayOrVarArgs)) { children = childrenArrayOrVarArgs; } else { children = []; - for (i = 2; i < arguments.length; i++) { + for (let i = 2; i < arguments.length; i++) { children.push(arguments[i]); } } - for (i = 0; i < children.length; i++) { - var child = children[i]; + for (let i = 0; i < children.length; i++) { + const child = children[i]; if (typeof child === 'string') { el.appendChild(createTextNode(child)); @@ -794,7 +799,7 @@ jasmineRequire.HtmlReporter = function(j$) { } } - for (var attr in attrs) { + for (const attr in attrs) { if (attr == 'className') { el[attr] = attrs[attr]; } else { @@ -806,7 +811,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function pluralize(singular, count) { - var word = count == 1 ? singular : singular + 's'; + const word = count == 1 ? singular : singular + 's'; return '' + count + ' ' + word; } @@ -836,7 +841,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function noExpectations(result) { - var allExpectations = + const allExpectations = result.failedExpectations.length + result.passedExpectations.length; return ( @@ -851,7 +856,7 @@ jasmineRequire.HtmlReporter = function(j$) { } if (resultNode.type == 'suite') { - for (var i = 0, j = resultNode.children.length; i < j; i++) { + for (let i = 0, j = resultNode.children.length; i < j; i++) { if (hasActiveSpec(resultNode.children[i])) { return true; } @@ -865,11 +870,11 @@ jasmineRequire.HtmlReporter = function(j$) { jasmineRequire.HtmlSpecFilter = function() { function HtmlSpecFilter(options) { - var filterString = + const filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); - var filterPattern = new RegExp(filterString); + const filterPattern = new RegExp(filterString); this.matches = function(specName) { return filterPattern.test(specName); @@ -913,7 +918,7 @@ jasmineRequire.QueryString = function() { }; this.fullStringWithNewParam = function(key, value) { - var paramMap = queryStringToParamMap(); + const paramMap = queryStringToParamMap(); paramMap[key] = value; return toQueryString(paramMap); }; @@ -925,8 +930,8 @@ jasmineRequire.QueryString = function() { return this; function toQueryString(paramMap) { - var qStrPairs = []; - for (var prop in paramMap) { + const qStrPairs = []; + for (const prop in paramMap) { qStrPairs.push( encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]) ); @@ -935,15 +940,15 @@ jasmineRequire.QueryString = function() { } function queryStringToParamMap() { - var paramStr = options.getWindowLocation().search.substring(1), - params = [], - paramMap = {}; + const paramStr = options.getWindowLocation().search.substring(1); + let params = []; + const paramMap = {}; if (paramStr.length > 0) { params = paramStr.split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - var value = decodeURIComponent(p[1]); + for (let i = 0; i < params.length; i++) { + const p = params[i].split('='); + let value = decodeURIComponent(p[1]); if (value === 'true' || value === 'false') { value = JSON.parse(value); } diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index e65e0e0d..9d9b690f 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -20,9 +20,9 @@ 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. */ -// eslint-disable-next-line no-unused-vars +// eslint-disable-next-line no-unused-vars,no-var var getJasmineRequireObj = (function(jasmineGlobal) { - var jasmineRequire; + let jasmineRequire; if ( typeof module !== 'undefined' && @@ -51,7 +51,7 @@ var getJasmineRequireObj = (function(jasmineGlobal) { } getJasmineRequire().core = function(jRequire) { - var j$ = {}; + const j$ = {}; jRequire.base(j$, jasmineGlobal); j$.util = jRequire.util(j$); @@ -125,7 +125,7 @@ var getJasmineRequireObj = (function(jasmineGlobal) { })(this); getJasmineRequireObj().requireMatchers = function(jRequire, j$) { - var availableMatchers = [ + const availableMatchers = [ 'nothing', 'toBe', 'toBeCloseTo', @@ -161,8 +161,7 @@ getJasmineRequireObj().requireMatchers = function(jRequire, j$) { ], matchers = {}; - for (var i = 0; i < availableMatchers.length; i++) { - var name = availableMatchers[i]; + for (const name of availableMatchers) { matchers[name] = jRequire[name](j$); } @@ -214,7 +213,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @default 5000 * @since 1.3.0 */ - var DEFAULT_TIMEOUT_INTERVAL = 5000; + let DEFAULT_TIMEOUT_INTERVAL = 5000; Object.defineProperty(j$, 'DEFAULT_TIMEOUT_INTERVAL', { get: function() { return DEFAULT_TIMEOUT_INTERVAL; @@ -238,7 +237,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @return {Env} */ j$.getEnv = function(options) { - var env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); + const env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); //jasmine. singletons in here (setTimeout blah blah). return env; }; @@ -379,7 +378,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return func.name; } - var matches = + const matches = func.toString().match(/^\s*function\s*(\w+)\s*\(/) || func.toString().match(/^\s*\[object\s*(\w+)Constructor\]/); @@ -387,7 +386,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; j$.isPending_ = function(promise) { - var sentinel = {}; + const sentinel = {}; return Promise.race([promise, Promise.resolve(sentinel)]).then( function(result) { return result === sentinel; @@ -599,17 +598,17 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; getJasmineRequireObj().util = function(j$) { - var util = {}; + const util = {}; util.inherit = function(childClass, parentClass) { - var Subclass = function() {}; + const Subclass = function() {}; Subclass.prototype = parentClass.prototype; childClass.prototype = new Subclass(); }; util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) { + const arrayOfArgs = []; + for (let i = 0; i < args.length; i++) { arrayOfArgs.push(args[i]); } return arrayOfArgs; @@ -620,7 +619,7 @@ getJasmineRequireObj().util = function(j$) { }; util.arrayContains = function(array, search) { - var i = array.length; + let i = array.length; while (i--) { if (array[i] === search) { return true; @@ -634,8 +633,8 @@ getJasmineRequireObj().util = function(j$) { return obj.slice(); } - var cloned = {}; - for (var prop in obj) { + const cloned = {}; + for (const prop in obj) { if (obj.hasOwnProperty(prop)) { cloned[prop] = obj[prop]; } @@ -645,10 +644,10 @@ getJasmineRequireObj().util = function(j$) { }; util.cloneArgs = function(args) { - var clonedArgs = []; - var argsAsArray = j$.util.argsToArray(args); - for (var i = 0; i < argsAsArray.length; i++) { - var str = Object.prototype.toString.apply(argsAsArray[i]), + const clonedArgs = []; + const argsAsArray = j$.util.argsToArray(args); + for (let i = 0; i < argsAsArray.length; i++) { + const str = Object.prototype.toString.apply(argsAsArray[i]), primitives = /^\[object (Boolean|String|RegExp|Number)/; // All falsey values are either primitives, `null`, or `undefined. @@ -664,7 +663,7 @@ getJasmineRequireObj().util = function(j$) { }; util.getPropertyDescriptor = function(obj, methodName) { - var descriptor, + let descriptor, proto = obj; do { @@ -687,12 +686,12 @@ getJasmineRequireObj().util = function(j$) { }; function callerFile() { - var trace = new j$.StackTrace(util.errorWithStack()); + const trace = new j$.StackTrace(util.errorWithStack()); return trace.frames[2].file; } util.jasmineFile = (function() { - var result; + let result; return function() { if (!result) { @@ -713,7 +712,7 @@ getJasmineRequireObj().util = function(j$) { // exceeded. But on all currently supported JS runtimes, setTimeout calls // the callback immediately when the timeout is greater than 2147483647 // (the maximum value of a signed 32 bit integer). - var max = 2147483647; + const max = 2147483647; if (timeout > max) { throw new Error( @@ -827,16 +826,16 @@ getJasmineRequireObj().Spec = function(j$) { }; Spec.prototype.execute = function(onComplete, excluded, failSpecWithNoExp) { - var self = this; + const self = this; - var onStart = { + const onStart = { fn: function(done) { self.timer.start(); self.onStart(self, done); } }; - var complete = { + const complete = { fn: function(done) { if (self.autoCleanClosures) { self.queueableFn.fn = null; @@ -853,9 +852,9 @@ getJasmineRequireObj().Spec = function(j$) { type: 'specCleanup' }; - var fns = this.beforeAndAfterFns(); + const fns = this.beforeAndAfterFns(); - var runnerConfig = { + const runnerConfig = { isLeaf: true, queueableFns: [...fns.befores, this.queueableFn, ...fns.afters], onException: function() { @@ -1016,8 +1015,8 @@ getJasmineRequireObj().Spec = function(j$) { }); }; - var extractCustomPendingMessage = function(e) { - var fullMessage = e.toString(), + const extractCustomPendingMessage = function(e) { + const fullMessage = e.toString(), boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), boilerplateEnd = boilerplateStart + Spec.pendingSpecExceptionMessage.length; @@ -1083,7 +1082,7 @@ getJasmineRequireObj().Spec = function(j$) { getJasmineRequireObj().Order = function() { function Order(options) { this.random = 'random' in options ? options.random : true; - var seed = (this.seed = options.seed || generateSeed()); + const seed = (this.seed = options.seed || generateSeed()); this.sort = this.random ? randomOrder : naturalOrder; function naturalOrder(items) { @@ -1091,7 +1090,7 @@ getJasmineRequireObj().Order = function() { } function randomOrder(items) { - var copy = items.slice(); + const copy = items.slice(); copy.sort(function(a, b) { return jenkinsHash(seed + a.id) - jenkinsHash(seed + b.id); }); @@ -1108,7 +1107,7 @@ getJasmineRequireObj().Order = function() { // used in conjunction with a seed function jenkinsHash(key) { - var hash, i; + let hash, i; for (hash = i = 0; i < key.length; ++i) { hash += key.charCodeAt(i); hash += hash << 10; @@ -1136,14 +1135,14 @@ getJasmineRequireObj().Env = function(j$) { function Env(options) { options = options || {}; - var self = this; - var global = options.global || j$.getGlobal(); + const self = this; + const global = options.global || j$.getGlobal(); - var totalSpecsDefined = 0; + let totalSpecsDefined = 0; - var realSetTimeout = global.setTimeout; - var realClearTimeout = global.clearTimeout; - var clearStack = j$.getClearStack(global); + const realSetTimeout = global.setTimeout; + const realClearTimeout = global.clearTimeout; + const clearStack = j$.getClearStack(global); this.clock = new j$.Clock( global, function() { @@ -1152,12 +1151,17 @@ getJasmineRequireObj().Env = function(j$) { new j$.MockDate(global) ); - var runnableResources = {}; + const runnableResources = {}; - var currentSpec = null; - var currentlyExecutingSuites = []; - var currentDeclarationSuite = null; - var hasFailures = false; + let topSuite; + let currentSpec = null; + const currentlyExecutingSuites = []; + const focusedRunnables = []; + let currentDeclarationSuite = null; + let hasFailures = false; + let deprecator; + let reporter; + let spyRegistry; /** * This represents the available options to configure Jasmine. @@ -1166,7 +1170,7 @@ getJasmineRequireObj().Env = function(j$) { * @interface Configuration * @since 3.3.0 */ - var config = { + const config = { /** * Whether to randomize spec execution order * @name Configuration#random @@ -1259,24 +1263,24 @@ getJasmineRequireObj().Env = function(j$) { verboseDeprecations: false }; - var currentSuite = function() { + function currentSuite() { return currentlyExecutingSuites[currentlyExecutingSuites.length - 1]; - }; + } - var currentRunnable = function() { + function currentRunnable() { return currentSpec || currentSuite(); - }; + } - var globalErrors = null; + let globalErrors = null; - var installGlobalErrors = function() { + function installGlobalErrors() { if (globalErrors) { return; } globalErrors = new j$.GlobalErrors(); globalErrors.install(); - }; + } if (!options.suppressLoadErrors) { installGlobalErrors(); @@ -1306,7 +1310,7 @@ getJasmineRequireObj().Env = function(j$) { * @function */ this.configure = function(configuration) { - var booleanProps = [ + const booleanProps = [ 'random', 'failSpecWithNoExpectations', 'hideDisabled', @@ -1343,8 +1347,8 @@ getJasmineRequireObj().Env = function(j$) { * @returns {Configuration} */ this.configuration = function() { - var result = {}; - for (var property in config) { + const result = {}; + for (const property in config) { result[property] = config[property]; } return result; @@ -1387,10 +1391,10 @@ getJasmineRequireObj().Env = function(j$) { 'Matchers must be added in a before function or a spec' ); } - var customMatchers = + const customMatchers = runnableResources[currentRunnable().id].customMatchers; - for (var matcherName in matchersToAdd) { + for (const matcherName in matchersToAdd) { customMatchers[matcherName] = matchersToAdd[matcherName]; } }; @@ -1401,10 +1405,10 @@ getJasmineRequireObj().Env = function(j$) { 'Async Matchers must be added in a before function or a spec' ); } - var customAsyncMatchers = + const customAsyncMatchers = runnableResources[currentRunnable().id].customAsyncMatchers; - for (var matcherName in matchersToAdd) { + for (const matcherName in matchersToAdd) { customAsyncMatchers[matcherName] = matchersToAdd[matcherName]; } }; @@ -1424,23 +1428,25 @@ getJasmineRequireObj().Env = function(j$) { j$.Expectation.addCoreMatchers(j$.matchers); j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers); - var nextSpecId = 0; - var getNextSpecId = function() { + let nextSpecId = 0; + + function getNextSpecId() { return 'spec' + nextSpecId++; - }; + } - var nextSuiteId = 0; - var getNextSuiteId = function() { + let nextSuiteId = 0; + + function getNextSuiteId() { return 'suite' + nextSuiteId++; - }; + } - var makePrettyPrinter = function() { - var customObjectFormatters = + function makePrettyPrinter() { + const customObjectFormatters = runnableResources[currentRunnable().id].customObjectFormatters; return j$.makePrettyPrinter(customObjectFormatters); - }; + } - var makeMatchersUtil = function() { + function makeMatchersUtil() { const cr = currentRunnable(); if (cr) { @@ -1453,7 +1459,7 @@ getJasmineRequireObj().Env = function(j$) { } else { return new j$.MatchersUtil({ pp: j$.basicPrettyPrinter_ }); } - }; + } const expectationFactory = function(actual, spec) { return j$.Expectation.factory({ @@ -1486,7 +1492,7 @@ getJasmineRequireObj().Env = function(j$) { } function recordLateExpectation(runable, runableType, result) { - var delayedExpectationResult = {}; + const delayedExpectationResult = {}; Object.keys(result).forEach(function(k) { delayedExpectationResult[k] = result[k]; }); @@ -1556,8 +1562,8 @@ getJasmineRequireObj().Env = function(j$) { return asyncExpectationFactory(actual, suite, 'Spec'); }; - var defaultResourcesForRunnable = function(id, parentRunnableId) { - var resources = { + function defaultResourcesForRunnable(id, parentRunnableId) { + const resources = { spies: [], customEqualityTesters: [], customMatchers: {}, @@ -1588,16 +1594,16 @@ getJasmineRequireObj().Env = function(j$) { } runnableResources[id] = resources; - }; + } - var clearResourcesForRunnable = function(id) { + function clearResourcesForRunnable(id) { spyRegistry.clearSpies(); delete runnableResources[id]; - }; + } - var beforeAndAfterFns = function(targetSuite) { + function beforeAndAfterFns(targetSuite) { return function() { - var befores = [], + let befores = [], afters = [], suite = targetSuite; @@ -1613,17 +1619,17 @@ getJasmineRequireObj().Env = function(j$) { afters: afters }; }; - }; + } - var getSpecName = function(spec, suite) { - var fullName = [spec.description], + function getSpecName(spec, suite) { + const fullName = [spec.description], suiteFullName = suite.getFullName(); if (suiteFullName !== '') { fullName.unshift(suiteFullName); } return fullName.join(' '); - }; + } /** * Causes a deprecation warning to be logged to the console and reported to @@ -1648,11 +1654,11 @@ getJasmineRequireObj().Env = function(j$) { * @param {Object} [options] Optional extra options, as described above */ this.deprecated = function(deprecation, options) { - var runnable = currentRunnable() || topSuite; + const runnable = currentRunnable() || topSuite; deprecator.addDeprecationWarning(runnable, deprecation, options); }; - var queueRunnerFactory = function(options, args) { + function queueRunnerFactory(options, args) { if (options.isLeaf) { // A spec options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy; @@ -1683,9 +1689,9 @@ getJasmineRequireObj().Env = function(j$) { options.deprecated = self.deprecated; new j$.QueueRunner(options).execute(args); - }; + } - var topSuite = new j$.Suite({ + topSuite = new j$.Suite({ id: getNextSuiteId(), description: 'Jasmine__TopLevel__Suite', expectationFactory: expectationFactory, @@ -1693,7 +1699,7 @@ getJasmineRequireObj().Env = function(j$) { autoCleanClosures: config.autoCleanClosures, onLateError: recordLateError }); - var deprecator = new j$.Deprecator(topSuite); + deprecator = new j$.Deprecator(topSuite); currentDeclarationSuite = topSuite; /** @@ -1713,7 +1719,7 @@ getJasmineRequireObj().Env = function(j$) { * @interface Reporter * @see custom_reporter */ - var reporter = new j$.ReportDispatcher( + reporter = new j$.ReportDispatcher( [ /** * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. @@ -1831,12 +1837,12 @@ getJasmineRequireObj().Env = function(j$) { } } - var order = new j$.Order({ + const order = new j$.Order({ random: config.random, seed: config.seed }); - var processor = new j$.TreeProcessor({ + const processor = new j$.TreeProcessor({ tree: topSuite, runnableIds: runnablesToRun, queueRunnerFactory: queueRunnerFactory, @@ -1882,7 +1888,7 @@ getJasmineRequireObj().Env = function(j$) { ); } - var jasmineTimer = new j$.Timer(); + const jasmineTimer = new j$.Timer(); jasmineTimer.start(); return new Promise(function(resolve) { @@ -1919,7 +1925,7 @@ getJasmineRequireObj().Env = function(j$) { clearResourcesForRunnable(topSuite.id); currentlyExecutingSuites.pop(); - var overallStatus, incompleteReason; + let overallStatus, incompleteReason; if ( hasFailures || @@ -2041,9 +2047,9 @@ getJasmineRequireObj().Env = function(j$) { reporter.clearReporters(); }; - var spyFactory = new j$.SpyFactory( + const spyFactory = new j$.SpyFactory( function getCustomStrategies() { - var runnable = currentRunnable(); + const runnable = currentRunnable(); if (runnable) { return runnableResources[runnable.id].customSpyStrategies; @@ -2052,7 +2058,7 @@ getJasmineRequireObj().Env = function(j$) { return {}; }, function getDefaultStrategyFn() { - var runnable = currentRunnable(); + const runnable = currentRunnable(); if (runnable) { return runnableResources[runnable.id].defaultStrategyFn; @@ -2063,7 +2069,7 @@ getJasmineRequireObj().Env = function(j$) { makeMatchersUtil ); - var spyRegistry = new j$.SpyRegistry({ + spyRegistry = new j$.SpyRegistry({ currentSpies: function() { if (!currentRunnable()) { throw new Error( @@ -2115,24 +2121,24 @@ getJasmineRequireObj().Env = function(j$) { return spyFactory.createSpyObj(baseName, methodNames, propertyNames); }; - var ensureIsFunction = function(fn, caller) { + function ensureIsFunction(fn, caller) { if (!j$.isFunction_(fn)) { throw new Error( caller + ' expects a function argument; received ' + j$.getType_(fn) ); } - }; + } - var ensureIsFunctionOrAsync = function(fn, caller) { + function ensureIsFunctionOrAsync(fn, caller) { if (!j$.isFunction_(fn) && !j$.isAsyncFunction_(fn)) { throw new Error( caller + ' expects a function argument; received ' + j$.getType_(fn) ); } - }; + } function ensureIsNotNested(method) { - var runnable = currentRunnable(); + const runnable = currentRunnable(); if (runnable !== null && runnable !== undefined) { throw new Error( "'" + method + "' should only be used in 'describe' function" @@ -2140,8 +2146,8 @@ getJasmineRequireObj().Env = function(j$) { } } - var suiteFactory = function(description) { - var suite = new j$.Suite({ + function suiteFactory(description) { + return new j$.Suite({ id: getNextSuiteId(), description: description, parentSuite: currentDeclarationSuite, @@ -2152,14 +2158,12 @@ getJasmineRequireObj().Env = function(j$) { autoCleanClosures: config.autoCleanClosures, onLateError: recordLateError }); - - return suite; - }; + } this.describe = function(description, specDefinitions) { ensureIsNotNested('describe'); ensureIsFunction(specDefinitions, 'describe'); - var suite = suiteFactory(description); + const suite = suiteFactory(description); if (specDefinitions.length > 0) { throw new Error('describe does not expect any arguments'); } @@ -2179,18 +2183,16 @@ getJasmineRequireObj().Env = function(j$) { this.xdescribe = function(description, specDefinitions) { ensureIsNotNested('xdescribe'); ensureIsFunction(specDefinitions, 'xdescribe'); - var suite = suiteFactory(description); + const suite = suiteFactory(description); suite.exclude(); addSpecsToSuite(suite, specDefinitions); return suite.metadata; }; - var focusedRunnables = []; - this.fdescribe = function(description, specDefinitions) { ensureIsNotNested('fdescribe'); ensureIsFunction(specDefinitions, 'fdescribe'); - var suite = suiteFactory(description); + const suite = suiteFactory(description); suite.isFocused = true; focusedRunnables.push(suite.id); @@ -2201,11 +2203,11 @@ getJasmineRequireObj().Env = function(j$) { }; function addSpecsToSuite(suite, specDefinitions) { - var parentSuite = currentDeclarationSuite; + const parentSuite = currentDeclarationSuite; parentSuite.addChild(suite); currentDeclarationSuite = suite; - var declarationError = null; + let declarationError = null; try { specDefinitions(); } catch (e) { @@ -2231,9 +2233,9 @@ getJasmineRequireObj().Env = function(j$) { } function unfocusAncestor() { - var focusedAncestor = findFocusedAncestor(currentDeclarationSuite); + const focusedAncestor = findFocusedAncestor(currentDeclarationSuite); if (focusedAncestor) { - for (var i = 0; i < focusedRunnables.length; i++) { + for (let i = 0; i < focusedRunnables.length; i++) { if (focusedRunnables[i] === focusedAncestor) { focusedRunnables.splice(i, 1); break; @@ -2242,9 +2244,9 @@ getJasmineRequireObj().Env = function(j$) { } } - var specFactory = function(description, fn, suite, timeout) { + const specFactory = function(description, fn, suite, timeout) { totalSpecsDefined++; - var spec = new j$.Spec({ + const spec = new j$.Spec({ id: getNextSpecId(), beforeAndAfterFns: beforeAndAfterFns(suite), expectationFactory: expectationFactory, @@ -2310,7 +2312,12 @@ getJasmineRequireObj().Env = function(j$) { j$.util.validateTimeout(timeout); } - var spec = specFactory(description, fn, currentDeclarationSuite, timeout); + const spec = specFactory( + description, + fn, + currentDeclarationSuite, + timeout + ); if (currentDeclarationSuite.markedExcluding) { spec.exclude(); } @@ -2331,7 +2338,7 @@ getJasmineRequireObj().Env = function(j$) { if (arguments.length > 1 && typeof fn !== 'undefined') { ensureIsFunctionOrAsync(fn, 'xit'); } - var spec = this.it_.apply(this, arguments); + const spec = this.it_.apply(this, arguments); spec.exclude('Temporarily disabled with xit'); return spec.metadata; }; @@ -2343,7 +2350,12 @@ getJasmineRequireObj().Env = function(j$) { if (timeout) { j$.util.validateTimeout(timeout); } - var spec = specFactory(description, fn, currentDeclarationSuite, timeout); + const spec = specFactory( + description, + fn, + currentDeclarationSuite, + timeout + ); currentDeclarationSuite.addChild(spec); focusedRunnables.push(spec.id); unfocusAncestor(); @@ -2385,7 +2397,7 @@ getJasmineRequireObj().Env = function(j$) { }; this.debugLog = function(msg) { - var maybeSpec = currentRunnable(); + const maybeSpec = currentRunnable(); if (!maybeSpec || !maybeSpec.debugLog) { throw new Error("'debugLog' was called when there was no current spec"); @@ -2472,7 +2484,7 @@ getJasmineRequireObj().Env = function(j$) { }; this.pending = function(message) { - var fullMessage = j$.Spec.pendingSpecExceptionMessage; + let fullMessage = j$.Spec.pendingSpecExceptionMessage; if (message) { fullMessage += message; } @@ -2486,7 +2498,7 @@ getJasmineRequireObj().Env = function(j$) { ); } - var message = 'Failed'; + let message = 'Failed'; if (error) { message += ': '; if (error.message) { @@ -2531,8 +2543,8 @@ getJasmineRequireObj().JsApiReporter = function(j$) { * @hideconstructor */ function JsApiReporter(options) { - var timer = options.timer || new j$.Timer(), - status = 'loaded'; + const timer = options.timer || new j$.Timer(); + let status = 'loaded'; this.started = false; this.finished = false; @@ -2544,7 +2556,7 @@ getJasmineRequireObj().JsApiReporter = function(j$) { timer.start(); }; - var executionTime; + let executionTime; this.jasmineDone = function(runDetails) { this.finished = true; @@ -2564,7 +2576,7 @@ getJasmineRequireObj().JsApiReporter = function(j$) { return status; }; - var suites = [], + const suites = [], suites_hash = {}; this.suiteStarted = function(result) { @@ -2606,7 +2618,7 @@ getJasmineRequireObj().JsApiReporter = function(j$) { return suites_hash; }; - var specs = []; + const specs = []; this.specDone = function(result) { specs.push(result); @@ -2734,8 +2746,7 @@ getJasmineRequireObj().ArrayContaining = function(j$) { return false; } - for (var i = 0; i < this.sample.length; i++) { - var item = this.sample[i]; + for (const item of this.sample) { if (!matchersUtil.contains(other, item)) { return false; } @@ -2772,8 +2783,7 @@ getJasmineRequireObj().ArrayWithExactContents = function(j$) { return false; } - for (var i = 0; i < this.sample.length; i++) { - var item = this.sample[i]; + for (const item of this.sample) { if (!matchersUtil.contains(other, item)) { return false; } @@ -2864,7 +2874,7 @@ getJasmineRequireObj().MapContaining = function(j$) { for (const [key, value] of this.sample) { // for each key/value pair in `sample` // there should be at least one pair in `other` whose key and value both match - var hasMatch = false; + let hasMatch = false; for (const [oKey, oValue] of other) { if ( matchersUtil.equals(oKey, key) && @@ -2945,7 +2955,7 @@ getJasmineRequireObj().ObjectContaining = function(j$) { return false; } - for (var property in this.sample) { + for (const property in this.sample) { if ( !hasProperty(other, property) || !matchersUtil.equals(this.sample[property], other[property]) @@ -2965,7 +2975,7 @@ getJasmineRequireObj().ObjectContaining = function(j$) { }; } - var filteredOther = {}; + const filteredOther = {}; Object.keys(this.sample).forEach(function(k) { // eq short-circuits comparison of objects that have different key sets, // so include all keys even if undefined. @@ -3004,7 +3014,7 @@ getJasmineRequireObj().SetContaining = function(j$) { // for each item in `sample` there should be at least one matching item in `other` // (not using `matchersUtil.contains` because it compares set members by reference, // not by deep value equality) - var hasMatch = false; + let hasMatch = false; for (const oItem of other) { if (matchersUtil.equals(oItem, item)) { hasMatch = true; @@ -3179,8 +3189,8 @@ getJasmineRequireObj().CallTracker = function(j$) { * @since 2.0.0 */ function CallTracker() { - var calls = []; - var opts = {}; + let calls = []; + const opts = {}; this.track = function(context) { if (opts.cloneArgs) { @@ -3220,7 +3230,7 @@ getJasmineRequireObj().CallTracker = function(j$) { * @return {Array} */ this.argsFor = function(index) { - var call = calls[index]; + const call = calls[index]; return call ? call.args : []; }; @@ -3233,7 +3243,7 @@ getJasmineRequireObj().CallTracker = function(j$) { * @return {Object?} */ this.thisFor = function(index) { - var call = calls[index]; + const call = calls[index]; return call ? call.object : undefined; }; @@ -3256,12 +3266,7 @@ getJasmineRequireObj().CallTracker = function(j$) { * @return {Array} */ this.allArgs = function() { - var callArgs = []; - for (var i = 0; i < calls.length; i++) { - callArgs.push(calls[i].args); - } - - return callArgs; + return calls.map(c => c.args); }; /** @@ -3311,17 +3316,17 @@ getJasmineRequireObj().CallTracker = function(j$) { }; getJasmineRequireObj().clearStack = function(j$) { - var maxInlineCallCount = 10; + const maxInlineCallCount = 10; function messageChannelImpl(global, setTimeout) { - var channel = new global.MessageChannel(), - head = {}, - tail = head; + const channel = new global.MessageChannel(); + let head = {}; + let tail = head; - var taskRunning = false; + let taskRunning = false; channel.port1.onmessage = function() { head = head.next; - var task = head.task; + const task = head.task; delete head.task; if (taskRunning) { @@ -3336,7 +3341,7 @@ getJasmineRequireObj().clearStack = function(j$) { } }; - var currentCallCount = 0; + let currentCallCount = 0; return function clearStack(fn) { currentCallCount++; @@ -3351,14 +3356,14 @@ getJasmineRequireObj().clearStack = function(j$) { } function getClearStack(global) { - var currentCallCount = 0; - var realSetTimeout = global.setTimeout; - var setTimeoutImpl = function clearStack(fn) { + let currentCallCount = 0; + const realSetTimeout = global.setTimeout; + const setTimeoutImpl = function clearStack(fn) { Function.prototype.apply.apply(realSetTimeout, [global, [fn, 0]]); }; if (j$.isFunction_(global.setImmediate)) { - var realSetImmediate = global.setImmediate; + const realSetImmediate = global.setImmediate; return function(fn) { currentCallCount++; @@ -3382,7 +3387,7 @@ getJasmineRequireObj().clearStack = function(j$) { getJasmineRequireObj().Clock = function() { /* global process */ - var NODE_JS = + const NODE_JS = typeof process !== 'undefined' && process.versions && typeof process.versions.node === 'string'; @@ -3396,7 +3401,7 @@ getJasmineRequireObj().Clock = function() { * @hideconstructor */ function Clock(global, delayedFunctionSchedulerFactory, mockDate) { - var self = this, + const self = this, realTimingFunctions = { setTimeout: global.setTimeout, clearTimeout: global.clearTimeout, @@ -3408,10 +3413,10 @@ getJasmineRequireObj().Clock = function() { clearTimeout: clearTimeout, setInterval: setInterval, clearInterval: clearInterval - }, - installed = false, - delayedFunctionScheduler, - timer; + }; + let installed = false; + let delayedFunctionScheduler; + let timer; self.FakeTimeout = FakeTimeout; @@ -3533,7 +3538,7 @@ getJasmineRequireObj().Clock = function() { } function replace(dest, source) { - for (var prop in source) { + for (const prop in source) { dest[prop] = source[prop]; } } @@ -3547,7 +3552,7 @@ getJasmineRequireObj().Clock = function() { ); } - var timeout = new FakeTimeout(); + const timeout = new FakeTimeout(); delayedFunctionScheduler.scheduleFunction( fn, @@ -3574,7 +3579,7 @@ getJasmineRequireObj().Clock = function() { ); } - var timeout = new FakeTimeout(); + const timeout = new FakeTimeout(); delayedFunctionScheduler.scheduleFunction( fn, @@ -3666,16 +3671,16 @@ getJasmineRequireObj().CompleteOnFirstErrorSkipPolicy = function(j$) { getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { function DelayedFunctionScheduler() { - var self = this; - var scheduledLookup = []; - var scheduledFunctions = {}; - var currentTime = 0; - var delayedFnCount = 0; - var deletedKeys = []; + const self = this; + const scheduledLookup = []; + const scheduledFunctions = {}; + let currentTime = 0; + let delayedFnCount = 0; + let deletedKeys = []; self.tick = function(millis, tickDate) { millis = millis || 0; - var endTime = currentTime + millis; + const endTime = currentTime + millis; runScheduledFunctions(endTime, tickDate); }; @@ -3688,7 +3693,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { timeoutKey, runAtMillis ) { - var f; + let f; if (typeof funcToCall === 'string') { f = function() { // eslint-disable-next-line no-eval @@ -3702,7 +3707,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { timeoutKey = timeoutKey || ++delayedFnCount; runAtMillis = runAtMillis || currentTime + millis; - var funcToSchedule = { + const funcToSchedule = { runAtMillis: runAtMillis, funcToCall: f, recurring: recurring, @@ -3727,9 +3732,9 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { self.removeFunctionWithId = function(timeoutKey) { deletedKeys.push(timeoutKey); - for (var runAtMillis in scheduledFunctions) { - var funcs = scheduledFunctions[runAtMillis]; - var i = indexOfFirstToPass(funcs, function(func) { + for (const runAtMillis in scheduledFunctions) { + const funcs = scheduledFunctions[runAtMillis]; + const i = indexOfFirstToPass(funcs, function(func) { return func.timeoutKey === timeoutKey; }); @@ -3751,9 +3756,9 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { return self; function indexOfFirstToPass(array, testFn) { - var index = -1; + let index = -1; - for (var i = 0; i < array.length; ++i) { + for (let i = 0; i < array.length; ++i) { if (testFn(array[i])) { index = i; break; @@ -3764,8 +3769,8 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { } function deleteFromLookup(key) { - var value = Number(key); - var i = indexOfFirstToPass(scheduledLookup, function(millis) { + const value = Number(key); + const i = indexOfFirstToPass(scheduledLookup, function(millis) { return millis === value; }); @@ -3786,8 +3791,8 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { } function forEachFunction(funcsToRun, callback) { - for (var i = 0; i < funcsToRun.length; ++i) { - callback(funcsToRun[i]); + for (const f of funcsToRun) { + callback(f); } } @@ -3803,13 +3808,13 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { do { deletedKeys = []; - var newCurrentTime = scheduledLookup.shift(); + const newCurrentTime = scheduledLookup.shift(); if (newCurrentTime >= currentTime) { tickDate(newCurrentTime - currentTime); currentTime = newCurrentTime; } - var funcsToRun = scheduledFunctions[currentTime]; + const funcsToRun = scheduledFunctions[currentTime]; delete scheduledFunctions[currentTime]; @@ -3853,7 +3858,7 @@ getJasmineRequireObj().Deprecator = function(j$) { this.toSuppress_ = []; } - var verboseNote = + const verboseNote = 'Note: This message will be shown only once. Set the verboseDeprecations ' + 'config property to true to see every occurrence.'; @@ -3883,13 +3888,13 @@ getJasmineRequireObj().Deprecator = function(j$) { }; Deprecator.prototype.log_ = function(runnable, deprecation, options) { - var context; - if (j$.isError_(deprecation)) { console.error(deprecation); return; } + let context; + if (runnable === this.topSuite_ || options.ignoreRunnable) { context = ''; } else if (runnable.children) { @@ -3910,7 +3915,7 @@ getJasmineRequireObj().Deprecator = function(j$) { }; Deprecator.prototype.stackTrace_ = function() { - var formatter = new j$.ExceptionFormatter(); + const formatter = new j$.ExceptionFormatter(); return formatter.stack(j$.util.errorWithStack()).replace(/^Error\n/m, ''); }; @@ -4338,15 +4343,13 @@ getJasmineRequireObj().ExpectationFilterChain = function() { }; ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { - var result = this.callFirst_('modifyFailureMessage', arguments).result; + const result = this.callFirst_('modifyFailureMessage', arguments).result; return result || msg; }; ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { - var prevResult; - if (this.prev_) { - prevResult = this.prev_.callFirst_(fname, args); + const prevResult = this.prev_.callFirst_(fname, args); if (prevResult.found) { return prevResult; @@ -4387,20 +4390,20 @@ getJasmineRequireObj().Expector = function(j$) { this.args.unshift(this.actual); - var matcher = matcherFactory(this.matchersUtil); + const matcher = matcherFactory(this.matchersUtil); - var comparisonFunc = this.filters.selectComparisonFunc(matcher); + const comparisonFunc = this.filters.selectComparisonFunc(matcher); return comparisonFunc || matcher.compare; }; Expector.prototype.buildMessage = function(result) { - var self = this; + const self = this; if (result.pass) { return ''; } - var msg = this.filters.buildFailureMessage( + const msg = this.filters.buildFailureMessage( result, this.matcherName, this.args, @@ -4411,7 +4414,7 @@ getJasmineRequireObj().Expector = function(j$) { function defaultMessage() { if (!result.message) { - var args = self.args.slice(); + const args = self.args.slice(); args.unshift(false); args.unshift(self.matcherName); return self.matchersUtil.buildFailureMessage.apply( @@ -4427,7 +4430,7 @@ getJasmineRequireObj().Expector = function(j$) { }; Expector.prototype.compare = function(matcherName, matcherFactory, args) { - var matcherCompare = this.instantiateMatcher( + const matcherCompare = this.instantiateMatcher( matcherName, matcherFactory, args @@ -4436,13 +4439,13 @@ getJasmineRequireObj().Expector = function(j$) { }; Expector.prototype.addFilter = function(filter) { - var result = Object.create(this); + const result = Object.create(this); result.filters = this.filters.addFilter(filter); return result; }; Expector.prototype.processResult = function(result, errorForStack) { - var message = this.buildMessage(result); + const message = this.buildMessage(result); if (this.expected.length === 1) { this.expected = this.expected[0]; @@ -4464,7 +4467,7 @@ getJasmineRequireObj().Expector = function(j$) { getJasmineRequireObj().formatErrorMsg = function() { function generateErrorMsg(domain, usage) { - var usageDefinition = usage ? '\nUsage: ' + usage : ''; + const usageDefinition = usage ? '\nUsage: ' + usage : ''; return function errorMsg(msg) { return domain + ' : ' + msg + usageDefinition; @@ -4476,11 +4479,11 @@ getJasmineRequireObj().formatErrorMsg = function() { getJasmineRequireObj().GlobalErrors = function(j$) { function GlobalErrors(global) { - var handlers = []; + const handlers = []; global = global || j$.getGlobal(); - var onerror = function onerror() { - var handler = handlers[handlers.length - 1]; + const onerror = function onerror() { + const handler = handlers[handlers.length - 1]; if (handler) { handler.apply(null, Array.prototype.slice.call(arguments, 0)); @@ -4493,11 +4496,11 @@ getJasmineRequireObj().GlobalErrors = function(j$) { this.jasmineHandlers = {}; this.installOne_ = function installOne_(errorType, jasmineMessage) { function taggedOnError(error) { - var substituteMsg; - if (j$.isError_(error)) { error.jasmineMessage = jasmineMessage + ': ' + error; } else { + let substituteMsg; + if (error) { substituteMsg = jasmineMessage + ': ' + error; } else { @@ -4516,7 +4519,7 @@ getJasmineRequireObj().GlobalErrors = function(j$) { error = new Error(substituteMsg); } - var handler = handlers[handlers.length - 1]; + const handler = handlers[handlers.length - 1]; if (handler) { handler(error); @@ -4532,14 +4535,14 @@ getJasmineRequireObj().GlobalErrors = function(j$) { global.process.on(errorType, taggedOnError); this.uninstall = function uninstall() { - var errorTypes = Object.keys(this.originalHandlers); - for (var iType = 0; iType < errorTypes.length; iType++) { - var errorType = errorTypes[iType]; + const errorTypes = Object.keys(this.originalHandlers); + for (const errorType of errorTypes) { global.process.removeListener( errorType, this.jasmineHandlers[errorType] ); - for (var i = 0; i < this.originalHandlers[errorType].length; i++) { + + for (let i = 0; i < this.originalHandlers[errorType].length; i++) { global.process.on(errorType, this.originalHandlers[errorType][i]); } delete this.originalHandlers[errorType]; @@ -4557,10 +4560,12 @@ getJasmineRequireObj().GlobalErrors = function(j$) { this.installOne_('uncaughtException', 'Uncaught exception'); this.installOne_('unhandledRejection', 'Unhandled promise rejection'); } else { - var originalHandler = global.onerror; + const originalHandler = global.onerror; global.onerror = onerror; - var browserRejectionHandler = function browserRejectionHandler(event) { + const browserRejectionHandler = function browserRejectionHandler( + event + ) { if (j$.isError_(event.reason)) { event.reason.jasmineMessage = 'Unhandled promise rejection: ' + event.reason; @@ -4621,7 +4626,7 @@ getJasmineRequireObj().toBePending = function(j$) { if (!j$.isPromiseLike(actual)) { throw new Error('Expected toBePending to be called on a promise.'); } - var want = {}; + const want = {}; return Promise.race([actual, Promise.resolve(want)]).then( function(got) { return { pass: want === got }; @@ -4752,7 +4757,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) { ); } - var expected = getExpectedFromArgs(arg1, arg2, matchersUtil); + const expected = getExpectedFromArgs(arg1, arg2, matchersUtil); return actualPromise.then( function() { @@ -4781,7 +4786,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) { ); } - var actualMessage = actual.message; + const actualMessage = actual.message; if ( actualMessage === expected.message || @@ -4823,7 +4828,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) { } function getExpectedFromArgs(arg1, arg2, matchersUtil) { - var error, message; + let error, message; if (isErrorConstructor(arg1)) { error = arg1; @@ -5130,7 +5135,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { if (j$.isNumber_(haystack.length)) { // Objects that are shaped like arrays but aren't iterable - for (var i = 0; i < haystack.length; i++) { + for (let i = 0; i < haystack.length; i++) { if (this.equals(haystack[i], needle)) { return true; } @@ -5141,8 +5146,8 @@ getJasmineRequireObj().MatchersUtil = function(j$) { }; MatchersUtil.prototype.buildFailureMessage = function() { - var self = this; - var args = Array.prototype.slice.call(arguments, 0), + const self = this; + const args = Array.prototype.slice.call(arguments, 0), matcherName = args[0], isNot = args[1], actual = args[2], @@ -5151,14 +5156,14 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return ' ' + s.toLowerCase(); }); - var message = + let message = 'Expected ' + self.pp(actual) + (isNot ? ' not ' : ' ') + englishyPredicate; if (expected.length > 0) { - for (var i = 0; i < expected.length; i++) { + for (let i = 0; i < expected.length; i++) { if (i > 0) { message += ','; } @@ -5177,7 +5182,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { diffBuilder ) { if (j$.isFunction_(b.valuesForDiff_)) { - var values = b.valuesForDiff_(a, this.pp); + const values = b.valuesForDiff_(a, this.pp); this.eq_(values.other, values.self, aStack, bStack, diffBuilder); } else { diffBuilder.recordMismatch(); @@ -5191,14 +5196,15 @@ getJasmineRequireObj().MatchersUtil = function(j$) { bStack, diffBuilder ) { - var asymmetricA = j$.isAsymmetricEqualityTester_(a), - asymmetricB = j$.isAsymmetricEqualityTester_(b), - result; + const asymmetricA = j$.isAsymmetricEqualityTester_(a); + const asymmetricB = j$.isAsymmetricEqualityTester_(b); if (asymmetricA === asymmetricB) { return undefined; } + let result; + if (asymmetricA) { result = a.asymmetricMatch(b, this); if (!result) { @@ -5235,11 +5241,10 @@ getJasmineRequireObj().MatchersUtil = function(j$) { // Equality function lovingly adapted from isEqual in // [Underscore](http://underscorejs.org) MatchersUtil.prototype.eq_ = function(a, b, aStack, bStack, diffBuilder) { - var result = true, - self = this, - i; + let result = true; + const self = this; - var asymmetricResult = this.asymmetricMatch_( + const asymmetricResult = this.asymmetricMatch_( a, b, aStack, @@ -5250,8 +5255,8 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return asymmetricResult; } - for (i = 0; i < this.customTesters_.length; i++) { - var customTesterResult = this.customTesters_[i](a, b); + for (const tester of this.customTesters_) { + const customTesterResult = tester(a, b); if (!j$.util.isUndefined(customTesterResult)) { if (!customTesterResult) { diffBuilder.recordMismatch(); @@ -5285,7 +5290,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } return result; } - var className = Object.prototype.toString.call(a); + const className = Object.prototype.toString.call(a); if (className != Object.prototype.toString.call(b)) { diffBuilder.recordMismatch(); return false; @@ -5343,8 +5348,8 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - var aIsDomNode = j$.isDomNode(a); - var bIsDomNode = j$.isDomNode(b); + const aIsDomNode = j$.isDomNode(a); + const bIsDomNode = j$.isDomNode(b); if (aIsDomNode && bIsDomNode) { // At first try to use DOM3 method isEqualNode result = a.isEqualNode(b); @@ -5358,15 +5363,15 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - var aIsPromise = j$.isPromise(a); - var bIsPromise = j$.isPromise(b); + const aIsPromise = j$.isPromise(a); + const bIsPromise = j$.isPromise(b); if (aIsPromise && bIsPromise) { return a === b; } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - var length = aStack.length; + let length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. @@ -5377,12 +5382,12 @@ getJasmineRequireObj().MatchersUtil = function(j$) { // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); - var size = 0; + let size = 0; // Recursively compare objects and arrays. // Compare array lengths to determine if a deep comparison is necessary. if (className == '[object Array]') { - var aLength = a.length; - var bLength = b.length; + const aLength = a.length; + const bLength = b.length; diffBuilder.withPath('length', function() { if (aLength !== bLength) { @@ -5391,7 +5396,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } }); - for (i = 0; i < aLength || i < bLength; i++) { + for (let i = 0; i < aLength || i < bLength; i++) { diffBuilder.withPath(i, function() { if (i >= bLength) { diffBuilder.recordMismatch( @@ -5419,8 +5424,8 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - var keysA = []; - var keysB = []; + const keysA = []; + const keysB = []; a.forEach(function(valueA, keyA) { keysA.push(keyA); }); @@ -5430,18 +5435,17 @@ getJasmineRequireObj().MatchersUtil = function(j$) { // For both sets of keys, check they map to equal values in both maps. // Keep track of corresponding keys (in insertion order) in order to handle asymmetric obj keys. - var mapKeys = [keysA, keysB]; - var cmpKeys = [keysB, keysA]; - var mapIter, mapKey, mapValueA, mapValueB; - var cmpIter, cmpKey; - for (i = 0; result && i < mapKeys.length; i++) { - mapIter = mapKeys[i]; - cmpIter = cmpKeys[i]; + const mapKeys = [keysA, keysB]; + const cmpKeys = [keysB, keysA]; + for (let i = 0; result && i < mapKeys.length; i++) { + const mapIter = mapKeys[i]; + const cmpIter = cmpKeys[i]; - for (var j = 0; result && j < mapIter.length; j++) { - mapKey = mapIter[j]; - cmpKey = cmpIter[j]; - mapValueA = a.get(mapKey); + for (let j = 0; result && j < mapIter.length; j++) { + const mapKey = mapIter[j]; + const cmpKey = cmpIter[j]; + const mapValueA = a.get(mapKey); + let mapValueB; // Only use the cmpKey when one of the keys is asymmetric and the corresponding key matches, // otherwise explicitly look up the mapKey in the other Map since we want keys with unique @@ -5475,35 +5479,30 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - var valuesA = []; + const valuesA = []; a.forEach(function(valueA) { valuesA.push(valueA); }); - var valuesB = []; + const valuesB = []; b.forEach(function(valueB) { valuesB.push(valueB); }); // For both sets, check they are all contained in the other set - var setPairs = [[valuesA, valuesB], [valuesB, valuesA]]; - var stackPairs = [[aStack, bStack], [bStack, aStack]]; - var baseValues, baseValue, baseStack; - var otherValues, otherValue, otherStack; - var found; - var prevStackSize; - for (i = 0; result && i < setPairs.length; i++) { - baseValues = setPairs[i][0]; - otherValues = setPairs[i][1]; - baseStack = stackPairs[i][0]; - otherStack = stackPairs[i][1]; + const setPairs = [[valuesA, valuesB], [valuesB, valuesA]]; + const stackPairs = [[aStack, bStack], [bStack, aStack]]; + for (let i = 0; result && i < setPairs.length; i++) { + const baseValues = setPairs[i][0]; + const otherValues = setPairs[i][1]; + const baseStack = stackPairs[i][0]; + const otherStack = stackPairs[i][1]; // For each value in the base set... - for (var k = 0; result && k < baseValues.length; k++) { - baseValue = baseValues[k]; - found = false; + for (const baseValue of baseValues) { + let found = false; // ... test that it is present in the other set - for (var l = 0; !found && l < otherValues.length; l++) { - otherValue = otherValues[l]; - prevStackSize = baseStack.length; + for (let j = 0; !found && j < otherValues.length; j++) { + const otherValue = otherValues[j]; + const prevStackSize = baseStack.length; // compare by value equality found = this.eq_( baseValue, @@ -5532,7 +5531,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } else { // Objects with different constructors are not equivalent, but `Object`s // or `Array`s from different frames are. - var aCtor = a.constructor, + const aCtor = a.constructor, bCtor = b.constructor; if ( aCtor !== bCtor && @@ -5550,8 +5549,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } // Deep compare objects. - var aKeys = MatchersUtil.keys(a, className == '[object Array]'), - key; + const aKeys = MatchersUtil.keys(a, className == '[object Array]'); size = aKeys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. @@ -5562,8 +5560,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - for (i = 0; i < size; i++) { - key = aKeys[i]; + for (const key of aKeys) { // Deep compare each member if (!j$.util.has(b, key)) { diffBuilder.recordMismatch( @@ -5592,18 +5589,18 @@ getJasmineRequireObj().MatchersUtil = function(j$) { }; MatchersUtil.keys = function(obj, isArray) { - var allKeys = (function(o) { - var keys = []; - for (var key in o) { + const allKeys = (function(o) { + const keys = []; + for (const key in o) { if (j$.util.has(o, key)) { keys.push(key); } } - var symbols = Object.getOwnPropertySymbols(o); - for (var i = 0; i < symbols.length; i++) { - if (o.propertyIsEnumerable(symbols[i])) { - keys.push(symbols[i]); + const symbols = Object.getOwnPropertySymbols(o); + for (const sym of symbols) { + if (o.propertyIsEnumerable(sym)) { + keys.push(sym); } } @@ -5618,10 +5615,10 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return allKeys; } - var extraKeys = []; - for (var i = 0; i < allKeys.length; i++) { - if (typeof allKeys[i] === 'symbol' || !/^[0-9]+$/.test(allKeys[i])) { - extraKeys.push(allKeys[i]); + const extraKeys = []; + for (const k of allKeys) { + if (typeof k === 'symbol' || !/^[0-9]+$/.test(k)) { + extraKeys.push(k); } } @@ -5641,7 +5638,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } function objectKeysAreDifferentFormatter(pp, actual, expected, path) { - var missingProperties = extraKeysAndValues(expected, actual), + const missingProperties = extraKeysAndValues(expected, actual), extraProperties = extraKeysAndValues(actual, expected), missingPropertiesMessage = formatKeyValuePairs(pp, missingProperties), extraPropertiesMessage = formatKeyValuePairs(pp, extraProperties), @@ -5892,7 +5889,7 @@ getJasmineRequireObj().ObjectPath = function(j$) { }; getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) { - var availableMatchers = [ + const availableMatchers = [ 'toBePending', 'toBeResolved', 'toBeRejected', @@ -5902,8 +5899,7 @@ getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) { ], matchers = {}; - for (var i = 0; i < availableMatchers.length; i++) { - var name = availableMatchers[i]; + for (const name of availableMatchers) { matchers[name] = jRequire[name](j$); } @@ -5921,12 +5917,12 @@ getJasmineRequireObj().toBe = function(j$) { * expect(thing).toBe(realThing); */ function toBe(matchersUtil) { - var tip = + const tip = ' Tip: To check for deep equality, use .toEqual() instead of .toBe().'; return { compare: function(actual, expected) { - var result = { + const result = { pass: actual === expected }; @@ -5985,9 +5981,9 @@ getJasmineRequireObj().toBeCloseTo = function() { }; } - var pow = Math.pow(10, precision + 1); - var delta = Math.abs(expected - actual); - var maxDelta = Math.pow(10, -precision) / 2; + const pow = Math.pow(10, precision + 1); + const delta = Math.abs(expected - actual); + const maxDelta = Math.pow(10, -precision) / 2; return { pass: Math.round(delta * pow) <= maxDelta * pow @@ -6112,7 +6108,7 @@ getJasmineRequireObj().toBeGreaterThanOrEqual = function() { }; getJasmineRequireObj().toBeInstanceOf = function(j$) { - var usageError = j$.formatErrorMsg( + const usageError = j$.formatErrorMsg( '', 'expect(value).toBeInstanceOf()' ); @@ -6131,15 +6127,15 @@ getJasmineRequireObj().toBeInstanceOf = function(j$) { function toBeInstanceOf(matchersUtil) { return { compare: function(actual, expected) { - var actualType = - actual && actual.constructor - ? j$.fnNameFor(actual.constructor) - : matchersUtil.pp(actual), - expectedType = expected - ? j$.fnNameFor(expected) - : matchersUtil.pp(expected), - expectedMatcher, - pass; + const actualType = + actual && actual.constructor + ? j$.fnNameFor(actual.constructor) + : matchersUtil.pp(actual); + const expectedType = expected + ? j$.fnNameFor(expected) + : matchersUtil.pp(expected); + let expectedMatcher; + let pass; try { expectedMatcher = new j$.Any(expected); @@ -6234,7 +6230,7 @@ getJasmineRequireObj().toBeNaN = function(j$) { function toBeNaN(matchersUtil) { return { compare: function(actual) { - var result = { + const result = { pass: actual !== actual }; @@ -6266,7 +6262,7 @@ getJasmineRequireObj().toBeNegativeInfinity = function(j$) { function toBeNegativeInfinity(matchersUtil) { return { compare: function(actual) { - var result = { + const result = { pass: actual === Number.NEGATIVE_INFINITY }; @@ -6320,7 +6316,7 @@ getJasmineRequireObj().toBePositiveInfinity = function(j$) { function toBePositiveInfinity(matchersUtil) { return { compare: function(actual) { - var result = { + const result = { pass: actual === Number.POSITIVE_INFINITY }; @@ -6443,7 +6439,7 @@ getJasmineRequireObj().toEqual = function(j$) { function toEqual(matchersUtil) { return { compare: function(actual, expected) { - var result = { + const result = { pass: false }, diffBuilder = new j$.DiffBuilder({ prettyPrinter: matchersUtil.pp }); @@ -6462,7 +6458,7 @@ getJasmineRequireObj().toEqual = function(j$) { }; getJasmineRequireObj().toHaveBeenCalled = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalled()' ); @@ -6479,7 +6475,7 @@ getJasmineRequireObj().toHaveBeenCalled = function(j$) { function toHaveBeenCalled(matchersUtil) { return { compare: function(actual) { - var result = {}; + const result = {}; if (!j$.isSpy(actual)) { throw new Error( @@ -6510,7 +6506,7 @@ getJasmineRequireObj().toHaveBeenCalled = function(j$) { }; getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalledBefore()' ); @@ -6542,7 +6538,7 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { ); } - var result = { pass: false }; + const result = { pass: false }; if (!firstSpy.calls.count()) { result.message = @@ -6555,8 +6551,8 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { return result; } - var latest1stSpyCall = firstSpy.calls.mostRecent().invocationOrder; - var first2ndSpyCall = latterSpy.calls.first().invocationOrder; + const latest1stSpyCall = firstSpy.calls.mostRecent().invocationOrder; + const first2ndSpyCall = latterSpy.calls.first().invocationOrder; result.pass = latest1stSpyCall < first2ndSpyCall; @@ -6568,8 +6564,8 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { latterSpy.and.identity + ', but it was'; } else { - var first1stSpyCall = firstSpy.calls.first().invocationOrder; - var latest2ndSpyCall = latterSpy.calls.mostRecent().invocationOrder; + const first1stSpyCall = firstSpy.calls.first().invocationOrder; + const latest2ndSpyCall = latterSpy.calls.mostRecent().invocationOrder; if (first1stSpyCall < first2ndSpyCall) { result.message = @@ -6603,7 +6599,7 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { }; getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalledOnceWith(...arguments)' ); @@ -6620,7 +6616,7 @@ getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { function toHaveBeenCalledOnceWith(util) { return { compare: function() { - var args = Array.prototype.slice.call(arguments, 0), + const args = Array.prototype.slice.call(arguments, 0), actual = args[0], expectedArgs = args.slice(1); @@ -6630,7 +6626,7 @@ getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { ); } - var prettyPrintedCalls = actual.calls + const prettyPrintedCalls = actual.calls .allArgs() .map(function(argsForCall) { return ' ' + util.pp(argsForCall); @@ -6657,7 +6653,7 @@ getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { function getDiffs() { return actual.calls.allArgs().map(function(argsForCall, callIx) { - var diffBuilder = new j$.DiffBuilder(); + const diffBuilder = new j$.DiffBuilder(); util.equals(argsForCall, expectedArgs, diffBuilder); return diffBuilder.getMessage(); }); @@ -6703,7 +6699,7 @@ getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { }; getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalledTimes()' ); @@ -6728,7 +6724,7 @@ getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { ); } - var args = Array.prototype.slice.call(arguments, 0), + const args = Array.prototype.slice.call(arguments, 0), result = { pass: false }; if (!j$.isNumber_(expected)) { @@ -6740,8 +6736,8 @@ getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { } actual = args[0]; - var calls = actual.calls.count(); - var timesMessage = expected === 1 ? 'once' : expected + ' times'; + const calls = actual.calls.count(); + const timesMessage = expected === 1 ? 'once' : expected + ' times'; result.pass = calls === expected; result.message = result.pass ? 'Expected spy ' + @@ -6767,7 +6763,7 @@ getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { }; getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalledWith(...arguments)' ); @@ -6784,7 +6780,7 @@ getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { function toHaveBeenCalledWith(matchersUtil) { return { compare: function() { - var args = Array.prototype.slice.call(arguments, 0), + const args = Array.prototype.slice.call(arguments, 0), actual = args[0], expectedArgs = args.slice(1), result = { pass: false }; @@ -6825,16 +6821,16 @@ getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { }; } else { result.message = function() { - var prettyPrintedCalls = actual.calls + const prettyPrintedCalls = actual.calls .allArgs() .map(function(argsForCall) { return ' ' + matchersUtil.pp(argsForCall); }); - var diffs = actual.calls + const diffs = actual.calls .allArgs() .map(function(argsForCall, callIx) { - var diffBuilder = new j$.DiffBuilder(); + const diffBuilder = new j$.DiffBuilder(); matchersUtil.equals(argsForCall, expectedArgs, diffBuilder); return ( 'Call ' + @@ -6917,7 +6913,7 @@ getJasmineRequireObj().toHaveSize = function(j$) { function toHaveSize() { return { compare: function(actual, expected) { - var result = { + const result = { pass: false }; @@ -6942,7 +6938,7 @@ getJasmineRequireObj().toHaveSize = function(j$) { }; } - var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; function isLength(value) { return ( typeof value == 'number' && @@ -6956,7 +6952,7 @@ getJasmineRequireObj().toHaveSize = function(j$) { }; getJasmineRequireObj().toHaveSpyInteractions = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveSpyInteractions()' ); @@ -6973,7 +6969,7 @@ getJasmineRequireObj().toHaveSpyInteractions = function(j$) { function toHaveSpyInteractions(matchersUtil) { return { compare: function(actual) { - var result = {}; + const result = {}; if (!j$.isObject_(actual)) { throw new Error( @@ -7032,7 +7028,7 @@ getJasmineRequireObj().toHaveSpyInteractions = function(j$) { }; getJasmineRequireObj().toMatch = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toMatch( || )' ); @@ -7054,7 +7050,7 @@ getJasmineRequireObj().toMatch = function(j$) { throw new Error(getErrorMsg('Expected is not a String or a RegExp')); } - var regexp = new RegExp(expected); + const regexp = new RegExp(expected); return { pass: regexp.test(actual) @@ -7067,7 +7063,7 @@ getJasmineRequireObj().toMatch = function(j$) { }; getJasmineRequireObj().toThrow = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect(function() {}).toThrow()' ); @@ -7085,9 +7081,9 @@ getJasmineRequireObj().toThrow = function(j$) { function toThrow(matchersUtil) { return { compare: function(actual, expected) { - var result = { pass: false }, - threw = false, - thrown; + const result = { pass: false }; + let threw = false; + let thrown; if (typeof actual != 'function') { throw new Error(getErrorMsg('Actual is not a Function')); @@ -7148,7 +7144,7 @@ getJasmineRequireObj().toThrow = function(j$) { }; getJasmineRequireObj().toThrowError = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect(function() {}).toThrowError(, )' ); @@ -7170,13 +7166,14 @@ getJasmineRequireObj().toThrowError = function(j$) { function toThrowError(matchersUtil) { return { compare: function(actual) { - var errorMatcher = getMatcher.apply(null, arguments), - thrown; + const errorMatcher = getMatcher.apply(null, arguments); if (typeof actual != 'function') { throw new Error(getErrorMsg('Actual is not a Function')); } + let thrown; + try { actual(); return fail('Expected function to throw an Error.'); @@ -7199,7 +7196,7 @@ getJasmineRequireObj().toThrowError = function(j$) { }; function getMatcher() { - var expected, errorType; + let expected, errorType; if (arguments[2]) { errorType = arguments[1]; @@ -7255,15 +7252,15 @@ getJasmineRequireObj().toThrowError = function(j$) { } } - var errorTypeDescription = errorType + const errorTypeDescription = errorType ? j$.fnNameFor(errorType) : 'an exception'; function thrownDescription(thrown) { - var thrownName = errorType - ? j$.fnNameFor(thrown.constructor) - : 'an exception', - thrownMessage = ''; + const thrownName = errorType + ? j$.fnNameFor(thrown.constructor) + : 'an exception'; + let thrownMessage = ''; if (expected) { thrownMessage = ' with message ' + matchersUtil.pp(thrown.message); @@ -7325,7 +7322,7 @@ getJasmineRequireObj().toThrowError = function(j$) { return false; } - var Surrogate = function() {}; + const Surrogate = function() {}; Surrogate.prototype = type.prototype; return j$.isError_(new Surrogate()); } @@ -7349,7 +7346,7 @@ getJasmineRequireObj().toThrowError = function(j$) { }; getJasmineRequireObj().toThrowMatching = function(j$) { - var usageError = j$.formatErrorMsg( + const usageError = j$.formatErrorMsg( '', 'expect(function() {}).toThrowMatching()' ); @@ -7366,8 +7363,6 @@ getJasmineRequireObj().toThrowMatching = function(j$) { function toThrowMatching(matchersUtil) { return { compare: function(actual, predicate) { - var thrown; - if (typeof actual !== 'function') { throw new Error(usageError('Actual is not a Function')); } @@ -7376,6 +7371,8 @@ getJasmineRequireObj().toThrowMatching = function(j$) { throw new Error(usageError('Predicate is not a Function')); } + let thrown; + try { actual(); return fail('Expected function to throw an exception.'); @@ -7432,8 +7429,8 @@ getJasmineRequireObj().toThrowMatching = function(j$) { getJasmineRequireObj().MockDate = function(j$) { function MockDate(global) { - var self = this; - var currentTime = 0; + const self = this; + let currentTime = 0; if (!global || !global.Date) { self.install = function() {}; @@ -7442,7 +7439,7 @@ getJasmineRequireObj().MockDate = function(j$) { return self; } - var GlobalDate = global.Date; + const GlobalDate = global.Date; self.install = function(mockDate) { if (mockDate instanceof GlobalDate) { @@ -7912,14 +7909,14 @@ getJasmineRequireObj().makePrettyPrinter = function(j$) { }; getJasmineRequireObj().QueueRunner = function(j$) { - var nextid = 1; + let nextid = 1; function StopExecutionError() {} StopExecutionError.prototype = new Error(); j$.StopExecutionError = StopExecutionError; function once(fn, onTwice) { - var called = false; + let called = false; return function(arg) { if (called) { if (onTwice) { @@ -7979,7 +7976,7 @@ getJasmineRequireObj().QueueRunner = function(j$) { } QueueRunner.prototype.execute = function() { - var self = this; + const self = this; this.handleFinalError = function(message, source, lineno, colno, error) { // Older browsers would send the error as the first parameter. HTML5 // specifies the the five parameters above. The error instance should @@ -8005,57 +8002,57 @@ getJasmineRequireObj().QueueRunner = function(j$) { }; QueueRunner.prototype.attempt = function attempt(iterativeIndex) { - var self = this, - completedSynchronously = true, - handleError = function handleError(error) { - // TODO probably shouldn't next() right away here. - // That makes debugging async failures much more confusing. - onException(error); + let timeoutId; + let timedOut; + const self = this; + let completedSynchronously = true; + function handleError(error) { + // TODO probably shouldn't next() right away here. + // That makes debugging async failures much more confusing. + onException(error); + } + const cleanup = once(function cleanup() { + if (timeoutId !== void 0) { + self.clearTimeout(timeoutId); + } + self.globalErrors.popListener(handleError); + }); + const next = once( + function next(err) { + cleanup(); + + if (typeof err !== 'undefined') { + if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { + self.fail(err); + } + self.recordError_(iterativeIndex); + } + + function runNext() { + self.run(self.nextFnIx_(iterativeIndex)); + } + + if (completedSynchronously) { + self.setTimeout(runNext); + } else { + runNext(); + } }, - cleanup = once(function cleanup() { - if (timeoutId !== void 0) { - self.clearTimeout(timeoutId); + function() { + try { + if (!timedOut) { + self.onMultipleDone(); + } + } catch (error) { + // Any error we catch here is probably due to a bug in Jasmine, + // and it's not likely to end up anywhere useful if we let it + // propagate. Log it so it can at least show up when debugging. + console.error(error); } - self.globalErrors.popListener(handleError); - }), - next = once( - function next(err) { - cleanup(); - - if (typeof err !== 'undefined') { - if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { - self.fail(err); - } - self.recordError_(iterativeIndex); - } - - function runNext() { - self.run(self.nextFnIx_(iterativeIndex)); - } - - if (completedSynchronously) { - self.setTimeout(runNext); - } else { - runNext(); - } - }, - function() { - try { - if (!timedOut) { - self.onMultipleDone(); - } - } catch (error) { - // Any error we catch here is probably due to a bug in Jasmine, - // and it's not likely to end up anywhere useful if we let it - // propagate. Log it so it can at least show up when debugging. - console.error(error); - } - } - ), - timedOut = false, - queueableFn = self.queueableFns[iterativeIndex], - timeoutId, - maybeThenable; + } + ); + timedOut = false; + const queueableFn = self.queueableFns[iterativeIndex]; next.fail = function nextFail() { self.fail.apply(null, arguments); @@ -8066,10 +8063,11 @@ getJasmineRequireObj().QueueRunner = function(j$) { self.globalErrors.pushListener(handleError); if (queueableFn.timeout !== undefined) { - var timeoutInterval = queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL; + const timeoutInterval = + queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL; timeoutId = self.setTimeout(function() { timedOut = true; - var error = new Error( + const error = new Error( 'Timeout - Async function did not complete within ' + timeoutInterval + 'ms ' + @@ -8086,6 +8084,8 @@ getJasmineRequireObj().QueueRunner = function(j$) { } try { + let maybeThenable; + if (queueableFn.fn.length === 0) { maybeThenable = queueableFn.fn.call(self.userContext); @@ -8123,16 +8123,15 @@ getJasmineRequireObj().QueueRunner = function(j$) { }; QueueRunner.prototype.run = function(recursiveIndex) { - var length = this.queueableFns.length, - self = this, - iterativeIndex; + const length = this.queueableFns.length; + const self = this; for ( - iterativeIndex = recursiveIndex; + let iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex = this.nextFnIx_(iterativeIndex) ) { - var result = this.attempt(iterativeIndex); + const result = this.attempt(iterativeIndex); if (!result.completedSynchronously) { return; @@ -8203,10 +8202,9 @@ getJasmineRequireObj().QueueRunner = function(j$) { getJasmineRequireObj().ReportDispatcher = function(j$) { function ReportDispatcher(methods, queueRunnerFactory, onLateError) { - var dispatchedMethods = methods || []; + const dispatchedMethods = methods || []; - for (var i = 0; i < dispatchedMethods.length; i++) { - var method = dispatchedMethods[i]; + for (const method of dispatchedMethods) { this[method] = (function(m) { return function() { dispatch(m, arguments); @@ -8214,8 +8212,8 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { })(method); } - var reporters = []; - var fallbackReporter = null; + let reporters = []; + let fallbackReporter = null; this.addReporter = function(reporter) { reporters.push(reporter); @@ -8235,11 +8233,10 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { if (reporters.length === 0 && fallbackReporter !== null) { reporters.push(fallbackReporter); } - var onComplete = args[args.length - 1]; + const onComplete = args[args.length - 1]; args = j$.util.argsToArray(args).splice(0, args.length - 1); - var fns = []; - for (var i = 0; i < reporters.length; i++) { - var reporter = reporters[i]; + const fns = []; + for (const reporter of reporters) { addFn(fns, reporter, method, args); } @@ -8259,12 +8256,12 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { } function addFn(fns, reporter, method, args) { - var fn = reporter[method]; + const fn = reporter[method]; if (!fn) { return; } - var thisArgs = j$.util.cloneArgs(args); + const thisArgs = j$.util.cloneArgs(args); if (fn.length <= 1) { fns.push({ fn: function() { @@ -8285,7 +8282,7 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { }; getJasmineRequireObj().interface = function(jasmine, env) { - var jasmineInterface = { + const jasmineInterface = { /** * Callback passed to parts of the Jasmine base interface. * @@ -8755,8 +8752,8 @@ getJasmineRequireObj().SkipAfterBeforeAllErrorPolicy = function(j$) { }; getJasmineRequireObj().Spy = function(j$) { - var nextOrder = (function() { - var order = 0; + const nextOrder = (function() { + let order = 0; return function() { return order++; @@ -8771,9 +8768,29 @@ getJasmineRequireObj().Spy = function(j$) { * @hideconstructor */ function Spy(name, matchersUtil, optionals) { + const spy = function(context, args, invokeNew) { + /** + * @name Spy.callData + * @property {object} object - `this` context for the invocation. + * @property {number} invocationOrder - Order of the invocation. + * @property {Array} args - The arguments passed for this invocation. + * @property returnValue - The value that was returned from this invocation. + */ + const callData = { + object: context, + invocationOrder: nextOrder(), + args: Array.prototype.slice.apply(args) + }; + + callTracker.track(callData); + const returnValue = strategyDispatcher.exec(context, args, invokeNew); + callData.returnValue = returnValue; + + return returnValue; + }; const { originalFn, customStrategies, defaultStrategyFn } = optionals || {}; - var numArgs = typeof originalFn === 'function' ? originalFn.length : 0, + const numArgs = typeof originalFn === 'function' ? originalFn.length : 0, wrapper = makeFunc(numArgs, function(context, args, invokeNew) { return spy(context, args, invokeNew); }), @@ -8788,27 +8805,7 @@ getJasmineRequireObj().Spy = function(j$) { }, matchersUtil ), - callTracker = new j$.CallTracker(), - spy = function(context, args, invokeNew) { - /** - * @name Spy.callData - * @property {object} object - `this` context for the invocation. - * @property {number} invocationOrder - Order of the invocation. - * @property {Array} args - The arguments passed for this invocation. - * @property returnValue - The value that was returned from this invocation. - */ - var callData = { - object: context, - invocationOrder: nextOrder(), - args: Array.prototype.slice.apply(args) - }; - - callTracker.track(callData); - var returnValue = strategyDispatcher.exec(context, args, invokeNew); - callData.returnValue = returnValue; - - return returnValue; - }; + callTracker = new j$.CallTracker(); function makeFunc(length, fn) { switch (length) { @@ -8855,7 +8852,7 @@ getJasmineRequireObj().Spy = function(j$) { } } - for (var prop in originalFn) { + for (const 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" @@ -8900,15 +8897,15 @@ getJasmineRequireObj().Spy = function(j$) { } function SpyStrategyDispatcher(strategyArgs, matchersUtil) { - var baseStrategy = new j$.SpyStrategy(strategyArgs); - var argsStrategies = new StrategyDict(function() { + const baseStrategy = new j$.SpyStrategy(strategyArgs); + const argsStrategies = new StrategyDict(function() { return new j$.SpyStrategy(strategyArgs); }, matchersUtil); this.and = baseStrategy; this.exec = function(spy, args, invokeNew) { - var strategy = argsStrategies.get(args); + let strategy = argsStrategies.get(args); if (!strategy) { if (argsStrategies.any() && !baseStrategy.isConfigured()) { @@ -8943,7 +8940,7 @@ getJasmineRequireObj().Spy = function(j$) { }; StrategyDict.prototype.getOrCreate = function(args) { - var strategy = this.get(args); + let strategy = this.get(args); if (!strategy) { strategy = this.strategyFactory(); @@ -8957,9 +8954,7 @@ getJasmineRequireObj().Spy = function(j$) { }; StrategyDict.prototype.get = function(args) { - var i; - - for (i = 0; i < this.strategies.length; i++) { + for (let i = 0; i < this.strategies.length; i++) { if (this.matchersUtil.equals(args, this.strategies[i].args)) { return this.strategies[i].strategy; } @@ -8975,7 +8970,7 @@ getJasmineRequireObj().SpyFactory = function(j$) { getDefaultStrategyFn, getMatchersUtil ) { - var self = this; + const self = this; this.createSpy = function(name, originalFn) { return j$.Spy(name, getMatchersUtil(), { @@ -8986,7 +8981,7 @@ getJasmineRequireObj().SpyFactory = function(j$) { }; this.createSpyObj = function(baseName, methodNames, propertyNames) { - var baseNameIsCollection = + const baseNameIsCollection = j$.isObject_(baseName) || j$.isArray_(baseName); if (baseNameIsCollection) { @@ -8995,22 +8990,21 @@ getJasmineRequireObj().SpyFactory = function(j$) { baseName = 'unknown'; } - var obj = {}; - var spy, descriptor; + const obj = {}; - var methods = normalizeKeyValues(methodNames); - for (var i = 0; i < methods.length; i++) { - spy = obj[methods[i][0]] = self.createSpy( + const methods = normalizeKeyValues(methodNames); + for (let i = 0; i < methods.length; i++) { + const spy = (obj[methods[i][0]] = self.createSpy( baseName + '.' + methods[i][0] - ); + )); if (methods[i].length > 1) { spy.and.returnValue(methods[i][1]); } } - var properties = normalizeKeyValues(propertyNames); - for (var i = 0; i < properties.length; i++) { - descriptor = { + const properties = normalizeKeyValues(propertyNames); + for (let i = 0; i < properties.length; i++) { + const descriptor = { enumerable: true, get: self.createSpy(baseName + '.' + properties[i][0] + '.get'), set: self.createSpy(baseName + '.' + properties[i][0] + '.set') @@ -9031,13 +9025,13 @@ getJasmineRequireObj().SpyFactory = function(j$) { } function normalizeKeyValues(object) { - var result = []; + const result = []; if (j$.isArray_(object)) { - for (var i = 0; i < object.length; i++) { + for (let i = 0; i < object.length; i++) { result.push([object[i]]); } } else if (j$.isObject_(object)) { - for (var key in object) { + for (const key in object) { if (object.hasOwnProperty(key)) { result.push([key, object[key]]); } @@ -9050,17 +9044,20 @@ getJasmineRequireObj().SpyFactory = function(j$) { }; getJasmineRequireObj().SpyRegistry = function(j$) { - var spyOnMsg = j$.formatErrorMsg('', 'spyOn(, )'); - var spyOnPropertyMsg = j$.formatErrorMsg( + const spyOnMsg = j$.formatErrorMsg( + '', + 'spyOn(, )' + ); + const spyOnPropertyMsg = j$.formatErrorMsg( '', 'spyOnProperty(, , [accessType])' ); function SpyRegistry(options) { options = options || {}; - var global = options.global || j$.getGlobal(); - var createSpy = options.createSpy; - var currentSpies = + const global = options.global || j$.getGlobal(); + const createSpy = options.createSpy; + const currentSpies = options.currentSpies || function() { return []; @@ -9071,7 +9068,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { }; this.spyOn = function(obj, methodName) { - var getErrorMsg = spyOnMsg; + const getErrorMsg = spyOnMsg; if (j$.util.isUndefined(obj) || obj === null) { throw new Error( @@ -9099,7 +9096,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } } - var descriptor = Object.getOwnPropertyDescriptor(obj, methodName); + const descriptor = Object.getOwnPropertyDescriptor(obj, methodName); if (descriptor && !(descriptor.writable || descriptor.set)) { throw new Error( @@ -9107,9 +9104,9 @@ getJasmineRequireObj().SpyRegistry = function(j$) { ); } - var originalMethod = obj[methodName], - spiedMethod = createSpy(methodName, originalMethod), - restoreStrategy; + const originalMethod = obj[methodName]; + const spiedMethod = createSpy(methodName, originalMethod); + let restoreStrategy; if ( Object.prototype.hasOwnProperty.call(obj, methodName) || @@ -9136,7 +9133,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { }; this.spyOnProperty = function(obj, propertyName, accessType) { - var getErrorMsg = spyOnPropertyMsg; + const getErrorMsg = spyOnPropertyMsg; accessType = accessType || 'get'; @@ -9154,7 +9151,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { throw new Error(getErrorMsg('No property name supplied')); } - var descriptor = j$.util.getPropertyDescriptor(obj, propertyName); + const descriptor = j$.util.getPropertyDescriptor(obj, propertyName); if (!descriptor) { throw new Error(getErrorMsg(propertyName + ' property does not exist')); @@ -9189,9 +9186,9 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } } - var originalDescriptor = j$.util.clone(descriptor), - spy = createSpy(propertyName, descriptor[accessType]), - restoreStrategy; + const originalDescriptor = j$.util.clone(descriptor); + const spy = createSpy(propertyName, descriptor[accessType]); + let restoreStrategy; if (Object.prototype.hasOwnProperty.call(obj, propertyName)) { restoreStrategy = function() { @@ -9221,7 +9218,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { ); } - var pointer = obj, + let pointer = obj, propsToSpyOn = [], properties, propertiesToSkip = []; @@ -9241,24 +9238,24 @@ getJasmineRequireObj().SpyRegistry = function(j$) { pointer = Object.getPrototypeOf(pointer); } - for (var i = 0; i < propsToSpyOn.length; i++) { - this.spyOn(obj, propsToSpyOn[i]); + for (const prop of propsToSpyOn) { + this.spyOn(obj, prop); } return obj; }; this.clearSpies = function() { - var spies = currentSpies(); - for (var i = spies.length - 1; i >= 0; i--) { - var spyEntry = spies[i]; + const spies = currentSpies(); + for (let i = spies.length - 1; i >= 0; i--) { + const spyEntry = spies[i]; spyEntry.restoreObjectToOriginalState(); } }; } function getProps(obj, includeNonEnumerable) { - var enumerableProperties = Object.keys(obj); + const enumerableProperties = Object.keys(obj); if (!includeNonEnumerable) { return enumerableProperties; @@ -9273,10 +9270,9 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } function getSpyableFunctionProps(obj, propertiesToCheck) { - var props = [], - prop; - for (var i = 0; i < propertiesToCheck.length; i++) { - prop = propertiesToCheck[i]; + const props = []; + + for (const prop of propertiesToCheck) { if ( Object.prototype.hasOwnProperty.call(obj, prop) && isSpyableProp(obj, prop) @@ -9288,14 +9284,15 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } function isSpyableProp(obj, prop) { - var value, descriptor; + let value; try { value = obj[prop]; } catch (e) { return false; } + if (value instanceof Function) { - descriptor = Object.getOwnPropertyDescriptor(obj, prop); + const descriptor = Object.getOwnPropertyDescriptor(obj, prop); return (descriptor.writable || descriptor.set) && descriptor.configurable; } return false; @@ -9311,7 +9308,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { function SpyStrategy(options) { options = options || {}; - var self = this; + const self = this; /** * Get the identifying information for the spy. @@ -9325,9 +9322,8 @@ getJasmineRequireObj().SpyStrategy = function(j$) { this.getSpy = options.getSpy || function() {}; this.plan = this._defaultPlan = function() {}; - var k, - cs = options.customStrategies || {}; - for (k in cs) { + const cs = options.customStrategies || {}; + for (const k in cs) { if (j$.util.has(cs, k) && !this[k]) { this[k] = createCustomPlan(cs[k]); } @@ -9364,7 +9360,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { function createCustomPlan(factory) { return function() { - var plan = factory.apply(null, arguments); + const plan = factory.apply(null, arguments); if (!j$.isFunction_(plan)) { throw new Error('Spy strategy must return a function'); @@ -9382,10 +9378,10 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @function */ SpyStrategy.prototype.exec = function(context, args, invokeNew) { - var contextArgs = [context].concat( + const contextArgs = [context].concat( args ? Array.prototype.slice.call(args) : [] ); - var target = this.plan.bind.apply(this.plan, contextArgs); + const target = this.plan.bind.apply(this.plan, contextArgs); return invokeNew ? new target() : target(); }; @@ -9423,7 +9419,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {...*} values - Values to be returned on subsequent calls to the spy. */ SpyStrategy.prototype.returnValues = function() { - var values = Array.prototype.slice.call(arguments); + const values = Array.prototype.slice.call(arguments); this.plan = function() { return values.shift(); }; @@ -9438,7 +9434,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {Error|Object|String} something Thing to throw */ SpyStrategy.prototype.throwError = function(something) { - var error = j$.isString_(something) ? new Error(something) : something; + const error = j$.isString_(something) ? new Error(something) : something; this.plan = function() { throw error; }; @@ -9488,23 +9484,23 @@ getJasmineRequireObj().SpyStrategy = function(j$) { getJasmineRequireObj().StackTrace = function(j$) { function StackTrace(error) { - var lines = error.stack.split('\n').filter(function(line) { + let lines = error.stack.split('\n').filter(function(line) { return line !== ''; }); - var extractResult = extractMessage(error.message, lines); + const extractResult = extractMessage(error.message, lines); if (extractResult) { this.message = extractResult.message; lines = extractResult.remainder; } - var parseResult = tryParseFrames(lines); + const parseResult = tryParseFrames(lines); this.frames = parseResult.frames; this.style = parseResult.style; } - var framePatterns = [ + const framePatterns = [ // Node, Chrome, Edge // 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 @@ -9534,16 +9530,15 @@ getJasmineRequireObj().StackTrace = function(j$) { // regexes should capture the function name (if any) as group 1 // and the file, line, and column as group 2. function tryParseFrames(lines) { - var style = null; - var frames = lines.map(function(line) { - var convertedLine = first(framePatterns, function(pattern) { - var overallMatch = line.match(pattern.re), - fileLineColMatch; + let style = null; + const frames = lines.map(function(line) { + const convertedLine = first(framePatterns, function(pattern) { + const overallMatch = line.match(pattern.re); if (!overallMatch) { return null; } - fileLineColMatch = overallMatch[pattern.fileLineColIx].match( + const fileLineColMatch = overallMatch[pattern.fileLineColIx].match( /^(.*):(\d+):\d+$/ ); if (!fileLineColMatch) { @@ -9569,10 +9564,8 @@ getJasmineRequireObj().StackTrace = function(j$) { } function first(items, fn) { - var i, result; - - for (i = 0; i < items.length; i++) { - result = fn(items[i]); + for (const item of items) { + const result = fn(item); if (result) { return result; @@ -9581,7 +9574,7 @@ getJasmineRequireObj().StackTrace = function(j$) { } function extractMessage(message, stackLines) { - var len = messagePrefixLength(message, stackLines); + const len = messagePrefixLength(message, stackLines); if (len > 0) { return { @@ -9596,10 +9589,9 @@ getJasmineRequireObj().StackTrace = function(j$) { return 0; } - var messageLines = message.split('\n'); - var i; + const messageLines = message.split('\n'); - for (i = 1; i < messageLines.length; i++) { + for (let i = 1; i < messageLines.length; i++) { if (messageLines[i] !== stackLines[i]) { return 0; } @@ -9648,9 +9640,9 @@ getJasmineRequireObj().Suite = function(j$) { }; Suite.prototype.getFullName = function() { - var fullName = []; + const fullName = []; for ( - var parentSuite = this; + let parentSuite = this; parentSuite; parentSuite = parentSuite.parentSuite ) { @@ -9702,8 +9694,8 @@ getJasmineRequireObj().Suite = function(j$) { }; function removeFns(queueableFns) { - for (var i = 0; i < queueableFns.length; i++) { - queueableFns[i].fn = null; + for (const qf of queueableFns) { + qf.fn = null; } } @@ -9932,7 +9924,7 @@ getJasmineRequireObj().Suite = function(j$) { }; getJasmineRequireObj().Timer = function() { - var defaultNow = (function(Date) { + const defaultNow = (function(Date) { return function() { return new Date().getTime(); }; @@ -9941,8 +9933,8 @@ getJasmineRequireObj().Timer = function() { function Timer(options) { options = options || {}; - var now = options.now || defaultNow, - startTime; + const now = options.now || defaultNow; + let startTime; this.start = function() { startTime = now(); @@ -9958,26 +9950,26 @@ getJasmineRequireObj().Timer = function() { getJasmineRequireObj().TreeProcessor = function() { function TreeProcessor(attrs) { - var tree = attrs.tree, - runnableIds = attrs.runnableIds, - queueRunnerFactory = attrs.queueRunnerFactory, - nodeStart = attrs.nodeStart || function() {}, - nodeComplete = attrs.nodeComplete || function() {}, - failSpecWithNoExpectations = !!attrs.failSpecWithNoExpectations, - 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; + const tree = attrs.tree; + const runnableIds = attrs.runnableIds; + const queueRunnerFactory = attrs.queueRunnerFactory; + const nodeStart = attrs.nodeStart || function() {}; + const nodeComplete = attrs.nodeComplete || function() {}; + const failSpecWithNoExpectations = !!attrs.failSpecWithNoExpectations; + const orderChildren = + attrs.orderChildren || + function(node) { + return node.children; + }; + const excludeNode = + attrs.excludeNode || + function(node) { + return false; + }; + let stats = { valid: true }; + let processed = false; + const defaultMin = Infinity; + const defaultMax = 1 - Infinity; this.processTree = function() { processNode(tree, true); @@ -9994,7 +9986,7 @@ getJasmineRequireObj().TreeProcessor = function() { throw 'invalid order'; } - var childFns = wrapChildren(tree, 0); + const childFns = wrapChildren(tree, 0); queueRunnerFactory({ queueableFns: childFns, @@ -10010,7 +10002,7 @@ getJasmineRequireObj().TreeProcessor = function() { }; function runnableIndex(id) { - for (var i = 0; i < runnableIds.length; i++) { + for (let i = 0; i < runnableIds.length; i++) { if (runnableIds[i] === id) { return i; } @@ -10018,14 +10010,14 @@ getJasmineRequireObj().TreeProcessor = function() { } function processNode(node, parentExcluded) { - var executableIndex = runnableIndex(node.id); + const executableIndex = runnableIndex(node.id); if (executableIndex !== undefined) { parentExcluded = false; } if (!node.children) { - var excluded = parentExcluded || excludeNode(node); + const excluded = parentExcluded || excludeNode(node); stats[node.id] = { excluded: excluded, willExecute: !excluded && !node.markedPending, @@ -10040,12 +10032,12 @@ getJasmineRequireObj().TreeProcessor = function() { ] }; } else { - var hasExecutableChild = false; + let hasExecutableChild = false; - var orderedChildren = orderChildren(node); + const orderedChildren = orderChildren(node); - for (var i = 0; i < orderedChildren.length; i++) { - var child = orderedChildren[i]; + for (let i = 0; i < orderedChildren.length; i++) { + const child = orderedChildren[i]; processNode(child, parentExcluded); @@ -10053,7 +10045,7 @@ getJasmineRequireObj().TreeProcessor = function() { return; } - var childStats = stats[child.id]; + const childStats = stats[child.id]; hasExecutableChild = hasExecutableChild || childStats.willExecute; } @@ -10085,7 +10077,7 @@ getJasmineRequireObj().TreeProcessor = function() { nodeStats, executableIndex ) { - var currentSegment = { + let currentSegment = { index: 0, owner: node, nodes: [], @@ -10104,8 +10096,8 @@ getJasmineRequireObj().TreeProcessor = function() { ); } - for (var i = 0; i < orderedChildSegments.length; i++) { - var childSegment = orderedChildSegments[i], + for (let i = 0; i < orderedChildSegments.length; i++) { + const childSegment = orderedChildSegments[i], maxIndex = childSegment.max, minIndex = childSegment.min; @@ -10130,15 +10122,15 @@ getJasmineRequireObj().TreeProcessor = function() { } function orderChildSegments(children) { - var specifiedOrder = [], + const specifiedOrder = [], unspecifiedOrder = []; - for (var i = 0; i < children.length; i++) { - var child = children[i], + for (let i = 0; i < children.length; i++) { + const child = children[i], segments = stats[child.id].segments; - for (var j = 0; j < segments.length; j++) { - var seg = segments[j]; + for (let j = 0; j < segments.length; j++) { + const seg = segments[j]; if (seg.min === defaultMin) { unspecifiedOrder.push(seg); @@ -10159,7 +10151,7 @@ getJasmineRequireObj().TreeProcessor = function() { if (node.children) { return { fn: function(done) { - var onStart = { + const onStart = { fn: function(next) { nodeStart(node, next); } @@ -10167,7 +10159,7 @@ getJasmineRequireObj().TreeProcessor = function() { queueRunnerFactory({ onComplete: function() { - var args = Array.prototype.slice.call(arguments, [0]); + const args = Array.prototype.slice.call(arguments, [0]); node.cleanupBeforeAfter(); nodeComplete(node, node.getResult(), function() { done.apply(undefined, args); @@ -10198,10 +10190,10 @@ getJasmineRequireObj().TreeProcessor = function() { } function wrapChildren(node, segmentNumber) { - var result = [], + const result = [], segmentChildren = stats[node.id].segments[segmentNumber].nodes; - for (var i = 0; i < segmentChildren.length; i++) { + for (let i = 0; i < segmentChildren.length; i++) { result.push( executeNode(segmentChildren[i].owner, segmentChildren[i].index) ); @@ -10222,9 +10214,9 @@ getJasmineRequireObj().UserContext = function(j$) { function UserContext() {} UserContext.fromExisting = function(oldContext) { - var context = new UserContext(); + const context = new UserContext(); - for (var prop in oldContext) { + for (const prop in oldContext) { if (oldContext.hasOwnProperty(prop)) { context[prop] = oldContext[prop]; } diff --git a/lib/jasmine-core/node_boot.js b/lib/jasmine-core/node_boot.js index 40bffff3..c10ca360 100644 --- a/lib/jasmine-core/node_boot.js +++ b/lib/jasmine-core/node_boot.js @@ -21,16 +21,16 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module.exports = function(jasmineRequire) { - var jasmine = jasmineRequire.core(jasmineRequire); + const jasmine = jasmineRequire.core(jasmineRequire); - var env = jasmine.getEnv({ suppressLoadErrors: true }); + const env = jasmine.getEnv({ suppressLoadErrors: true }); - var jasmineInterface = jasmineRequire.interface(jasmine, env); + const jasmineInterface = jasmineRequire.interface(jasmine, env); extend(global, jasmineInterface); function extend(destination, source) { - for (var property in source) destination[property] = source[property]; + for (const property in source) destination[property] = source[property]; return destination; } diff --git a/package.json b/package.json index 6d59fc8d..fdfb6c5b 100644 --- a/package.json +++ b/package.json @@ -96,7 +96,8 @@ "always" ], "space-before-blocks": "error", - "no-eval": "error" + "no-eval": "error", + "no-var": "error" } }, "browserslist": [ diff --git a/spec/.eslintrc.js b/spec/.eslintrc.js index b97d34d3..bafb67ca 100644 --- a/spec/.eslintrc.js +++ b/spec/.eslintrc.js @@ -14,8 +14,6 @@ module.exports = { // TODO: consider doing this in src files as well as specs 'no-unused-vars': ['error', { args: 'after-used' }], - 'no-var': 'error', - // Since linting is done at the end of the process and doesn't stop us // from running tests, it makes sense to fail if debugger statements // or console references are present. diff --git a/spec/support/ci.js b/spec/support/ci.js index 576fc6b3..6757446d 100644 --- a/spec/support/ci.js +++ b/spec/support/ci.js @@ -3,7 +3,7 @@ const path = require('path'), jasmineBrowser = require('jasmine-browser-runner'), jasmineCore = require('../../lib/jasmine-core'); -var config = require(path.resolve('spec/support/jasmine-browser.js')); +const config = require(path.resolve('spec/support/jasmine-browser.js')); config.clearReporters = true; config.jasmineCore = jasmineCore; diff --git a/src/boot/boot0.js b/src/boot/boot0.js index 80500089..976e623f 100644 --- a/src/boot/boot0.js +++ b/src/boot/boot0.js @@ -5,14 +5,14 @@ source files or spec files are loaded. */ (function() { - var jasmineRequire = window.jasmineRequire || require('./jasmine.js'); + const jasmineRequire = window.jasmineRequire || require('./jasmine.js'); /** * ## Require & Instantiate * * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. */ - var jasmine = jasmineRequire.core(jasmineRequire), + const jasmine = jasmineRequire.core(jasmineRequire), global = jasmine.getGlobal(); global.jasmine = jasmine; @@ -24,19 +24,19 @@ /** * Create the Jasmine environment. This is used to run all specs in a project. */ - var env = jasmine.getEnv(); + const env = jasmine.getEnv(); /** * ## The Global Interface * * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. */ - var jasmineInterface = jasmineRequire.interface(jasmine, env); + const jasmineInterface = jasmineRequire.interface(jasmine, env); /** * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. */ - for (var property in jasmineInterface) { + for (const property in jasmineInterface) { global[property] = jasmineInterface[property]; } })(); diff --git a/src/boot/boot1.js b/src/boot/boot1.js index 20ec9562..55d7e800 100644 --- a/src/boot/boot1.js +++ b/src/boot/boot1.js @@ -12,7 +12,7 @@ */ (function() { - var env = jasmine.getEnv(); + const env = jasmine.getEnv(); /** * ## Runner Parameters @@ -20,15 +20,15 @@ * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. */ - var queryString = new jasmine.QueryString({ + const queryString = new jasmine.QueryString({ getWindowLocation: function() { return window.location; } }); - var filterSpecs = !!queryString.getParam('spec'); + const filterSpecs = !!queryString.getParam('spec'); - var config = { + const config = { stopOnSpecFailure: queryString.getParam('stopOnSpecFailure'), stopSpecOnExpectationFailure: queryString.getParam( 'stopSpecOnExpectationFailure' @@ -36,13 +36,13 @@ hideDisabled: queryString.getParam('hideDisabled') }; - var random = queryString.getParam('random'); + const random = queryString.getParam('random'); if (random !== undefined && random !== '') { config.random = random; } - var seed = queryString.getParam('seed'); + const seed = queryString.getParam('seed'); if (seed) { config.seed = seed; } @@ -51,7 +51,7 @@ * ## Reporters * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). */ - var htmlReporter = new jasmine.HtmlReporter({ + const htmlReporter = new jasmine.HtmlReporter({ env: env, navigateWithNewParam: function(key, value) { return queryString.navigateWithNewParam(key, value); @@ -81,7 +81,7 @@ /** * Filter which specs will be run by matching the start of the full name against the `spec` query param. */ - var specFilter = new jasmine.HtmlSpecFilter({ + const specFilter = new jasmine.HtmlSpecFilter({ filterString: function() { return queryString.getParam('spec'); } @@ -98,7 +98,7 @@ * * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. */ - var currentWindowOnload = window.onload; + const currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { diff --git a/src/boot/node_boot.js b/src/boot/node_boot.js index af588102..53e86559 100644 --- a/src/boot/node_boot.js +++ b/src/boot/node_boot.js @@ -1,14 +1,14 @@ module.exports = function(jasmineRequire) { - var jasmine = jasmineRequire.core(jasmineRequire); + const jasmine = jasmineRequire.core(jasmineRequire); - var env = jasmine.getEnv({ suppressLoadErrors: true }); + const env = jasmine.getEnv({ suppressLoadErrors: true }); - var jasmineInterface = jasmineRequire.interface(jasmine, env); + const jasmineInterface = jasmineRequire.interface(jasmine, env); extend(global, jasmineInterface); function extend(destination, source) { - for (var property in source) destination[property] = source[property]; + for (const property in source) destination[property] = source[property]; return destination; } diff --git a/src/core/CallTracker.js b/src/core/CallTracker.js index fa9ebeaa..872e5cf8 100644 --- a/src/core/CallTracker.js +++ b/src/core/CallTracker.js @@ -4,8 +4,8 @@ getJasmineRequireObj().CallTracker = function(j$) { * @since 2.0.0 */ function CallTracker() { - var calls = []; - var opts = {}; + let calls = []; + const opts = {}; this.track = function(context) { if (opts.cloneArgs) { @@ -45,7 +45,7 @@ getJasmineRequireObj().CallTracker = function(j$) { * @return {Array} */ this.argsFor = function(index) { - var call = calls[index]; + const call = calls[index]; return call ? call.args : []; }; @@ -58,7 +58,7 @@ getJasmineRequireObj().CallTracker = function(j$) { * @return {Object?} */ this.thisFor = function(index) { - var call = calls[index]; + const call = calls[index]; return call ? call.object : undefined; }; @@ -81,12 +81,7 @@ getJasmineRequireObj().CallTracker = function(j$) { * @return {Array} */ this.allArgs = function() { - var callArgs = []; - for (var i = 0; i < calls.length; i++) { - callArgs.push(calls[i].args); - } - - return callArgs; + return calls.map(c => c.args); }; /** diff --git a/src/core/ClearStack.js b/src/core/ClearStack.js index b80de2b8..3d864244 100644 --- a/src/core/ClearStack.js +++ b/src/core/ClearStack.js @@ -1,15 +1,15 @@ getJasmineRequireObj().clearStack = function(j$) { - var maxInlineCallCount = 10; + const maxInlineCallCount = 10; function messageChannelImpl(global, setTimeout) { - var channel = new global.MessageChannel(), - head = {}, - tail = head; + const channel = new global.MessageChannel(); + let head = {}; + let tail = head; - var taskRunning = false; + let taskRunning = false; channel.port1.onmessage = function() { head = head.next; - var task = head.task; + const task = head.task; delete head.task; if (taskRunning) { @@ -24,7 +24,7 @@ getJasmineRequireObj().clearStack = function(j$) { } }; - var currentCallCount = 0; + let currentCallCount = 0; return function clearStack(fn) { currentCallCount++; @@ -39,14 +39,14 @@ getJasmineRequireObj().clearStack = function(j$) { } function getClearStack(global) { - var currentCallCount = 0; - var realSetTimeout = global.setTimeout; - var setTimeoutImpl = function clearStack(fn) { + let currentCallCount = 0; + const realSetTimeout = global.setTimeout; + const setTimeoutImpl = function clearStack(fn) { Function.prototype.apply.apply(realSetTimeout, [global, [fn, 0]]); }; if (j$.isFunction_(global.setImmediate)) { - var realSetImmediate = global.setImmediate; + const realSetImmediate = global.setImmediate; return function(fn) { currentCallCount++; diff --git a/src/core/Clock.js b/src/core/Clock.js index 1bb593e1..08a476a8 100644 --- a/src/core/Clock.js +++ b/src/core/Clock.js @@ -1,6 +1,6 @@ getJasmineRequireObj().Clock = function() { /* global process */ - var NODE_JS = + const NODE_JS = typeof process !== 'undefined' && process.versions && typeof process.versions.node === 'string'; @@ -14,7 +14,7 @@ getJasmineRequireObj().Clock = function() { * @hideconstructor */ function Clock(global, delayedFunctionSchedulerFactory, mockDate) { - var self = this, + const self = this, realTimingFunctions = { setTimeout: global.setTimeout, clearTimeout: global.clearTimeout, @@ -26,10 +26,10 @@ getJasmineRequireObj().Clock = function() { clearTimeout: clearTimeout, setInterval: setInterval, clearInterval: clearInterval - }, - installed = false, - delayedFunctionScheduler, - timer; + }; + let installed = false; + let delayedFunctionScheduler; + let timer; self.FakeTimeout = FakeTimeout; @@ -151,7 +151,7 @@ getJasmineRequireObj().Clock = function() { } function replace(dest, source) { - for (var prop in source) { + for (const prop in source) { dest[prop] = source[prop]; } } @@ -165,7 +165,7 @@ getJasmineRequireObj().Clock = function() { ); } - var timeout = new FakeTimeout(); + const timeout = new FakeTimeout(); delayedFunctionScheduler.scheduleFunction( fn, @@ -192,7 +192,7 @@ getJasmineRequireObj().Clock = function() { ); } - var timeout = new FakeTimeout(); + const timeout = new FakeTimeout(); delayedFunctionScheduler.scheduleFunction( fn, diff --git a/src/core/DelayedFunctionScheduler.js b/src/core/DelayedFunctionScheduler.js index 68bddc78..4e7ceac9 100644 --- a/src/core/DelayedFunctionScheduler.js +++ b/src/core/DelayedFunctionScheduler.js @@ -1,15 +1,15 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { function DelayedFunctionScheduler() { - var self = this; - var scheduledLookup = []; - var scheduledFunctions = {}; - var currentTime = 0; - var delayedFnCount = 0; - var deletedKeys = []; + const self = this; + const scheduledLookup = []; + const scheduledFunctions = {}; + let currentTime = 0; + let delayedFnCount = 0; + let deletedKeys = []; self.tick = function(millis, tickDate) { millis = millis || 0; - var endTime = currentTime + millis; + const endTime = currentTime + millis; runScheduledFunctions(endTime, tickDate); }; @@ -22,7 +22,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { timeoutKey, runAtMillis ) { - var f; + let f; if (typeof funcToCall === 'string') { f = function() { // eslint-disable-next-line no-eval @@ -36,7 +36,7 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { timeoutKey = timeoutKey || ++delayedFnCount; runAtMillis = runAtMillis || currentTime + millis; - var funcToSchedule = { + const funcToSchedule = { runAtMillis: runAtMillis, funcToCall: f, recurring: recurring, @@ -61,9 +61,9 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { self.removeFunctionWithId = function(timeoutKey) { deletedKeys.push(timeoutKey); - for (var runAtMillis in scheduledFunctions) { - var funcs = scheduledFunctions[runAtMillis]; - var i = indexOfFirstToPass(funcs, function(func) { + for (const runAtMillis in scheduledFunctions) { + const funcs = scheduledFunctions[runAtMillis]; + const i = indexOfFirstToPass(funcs, function(func) { return func.timeoutKey === timeoutKey; }); @@ -85,9 +85,9 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { return self; function indexOfFirstToPass(array, testFn) { - var index = -1; + let index = -1; - for (var i = 0; i < array.length; ++i) { + for (let i = 0; i < array.length; ++i) { if (testFn(array[i])) { index = i; break; @@ -98,8 +98,8 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { } function deleteFromLookup(key) { - var value = Number(key); - var i = indexOfFirstToPass(scheduledLookup, function(millis) { + const value = Number(key); + const i = indexOfFirstToPass(scheduledLookup, function(millis) { return millis === value; }); @@ -120,8 +120,8 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { } function forEachFunction(funcsToRun, callback) { - for (var i = 0; i < funcsToRun.length; ++i) { - callback(funcsToRun[i]); + for (const f of funcsToRun) { + callback(f); } } @@ -137,13 +137,13 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { do { deletedKeys = []; - var newCurrentTime = scheduledLookup.shift(); + const newCurrentTime = scheduledLookup.shift(); if (newCurrentTime >= currentTime) { tickDate(newCurrentTime - currentTime); currentTime = newCurrentTime; } - var funcsToRun = scheduledFunctions[currentTime]; + const funcsToRun = scheduledFunctions[currentTime]; delete scheduledFunctions[currentTime]; diff --git a/src/core/Deprecator.js b/src/core/Deprecator.js index 00dcf15a..65fc6e38 100644 --- a/src/core/Deprecator.js +++ b/src/core/Deprecator.js @@ -5,7 +5,7 @@ getJasmineRequireObj().Deprecator = function(j$) { this.toSuppress_ = []; } - var verboseNote = + const verboseNote = 'Note: This message will be shown only once. Set the verboseDeprecations ' + 'config property to true to see every occurrence.'; @@ -35,13 +35,13 @@ getJasmineRequireObj().Deprecator = function(j$) { }; Deprecator.prototype.log_ = function(runnable, deprecation, options) { - var context; - if (j$.isError_(deprecation)) { console.error(deprecation); return; } + let context; + if (runnable === this.topSuite_ || options.ignoreRunnable) { context = ''; } else if (runnable.children) { @@ -62,7 +62,7 @@ getJasmineRequireObj().Deprecator = function(j$) { }; Deprecator.prototype.stackTrace_ = function() { - var formatter = new j$.ExceptionFormatter(); + const formatter = new j$.ExceptionFormatter(); return formatter.stack(j$.util.errorWithStack()).replace(/^Error\n/m, ''); }; diff --git a/src/core/Env.js b/src/core/Env.js index a674a9a7..3b8c2961 100644 --- a/src/core/Env.js +++ b/src/core/Env.js @@ -10,14 +10,14 @@ getJasmineRequireObj().Env = function(j$) { function Env(options) { options = options || {}; - var self = this; - var global = options.global || j$.getGlobal(); + const self = this; + const global = options.global || j$.getGlobal(); - var totalSpecsDefined = 0; + let totalSpecsDefined = 0; - var realSetTimeout = global.setTimeout; - var realClearTimeout = global.clearTimeout; - var clearStack = j$.getClearStack(global); + const realSetTimeout = global.setTimeout; + const realClearTimeout = global.clearTimeout; + const clearStack = j$.getClearStack(global); this.clock = new j$.Clock( global, function() { @@ -26,12 +26,17 @@ getJasmineRequireObj().Env = function(j$) { new j$.MockDate(global) ); - var runnableResources = {}; + const runnableResources = {}; - var currentSpec = null; - var currentlyExecutingSuites = []; - var currentDeclarationSuite = null; - var hasFailures = false; + let topSuite; + let currentSpec = null; + const currentlyExecutingSuites = []; + const focusedRunnables = []; + let currentDeclarationSuite = null; + let hasFailures = false; + let deprecator; + let reporter; + let spyRegistry; /** * This represents the available options to configure Jasmine. @@ -40,7 +45,7 @@ getJasmineRequireObj().Env = function(j$) { * @interface Configuration * @since 3.3.0 */ - var config = { + const config = { /** * Whether to randomize spec execution order * @name Configuration#random @@ -133,24 +138,24 @@ getJasmineRequireObj().Env = function(j$) { verboseDeprecations: false }; - var currentSuite = function() { + function currentSuite() { return currentlyExecutingSuites[currentlyExecutingSuites.length - 1]; - }; + } - var currentRunnable = function() { + function currentRunnable() { return currentSpec || currentSuite(); - }; + } - var globalErrors = null; + let globalErrors = null; - var installGlobalErrors = function() { + function installGlobalErrors() { if (globalErrors) { return; } globalErrors = new j$.GlobalErrors(); globalErrors.install(); - }; + } if (!options.suppressLoadErrors) { installGlobalErrors(); @@ -180,7 +185,7 @@ getJasmineRequireObj().Env = function(j$) { * @function */ this.configure = function(configuration) { - var booleanProps = [ + const booleanProps = [ 'random', 'failSpecWithNoExpectations', 'hideDisabled', @@ -217,8 +222,8 @@ getJasmineRequireObj().Env = function(j$) { * @returns {Configuration} */ this.configuration = function() { - var result = {}; - for (var property in config) { + const result = {}; + for (const property in config) { result[property] = config[property]; } return result; @@ -261,10 +266,10 @@ getJasmineRequireObj().Env = function(j$) { 'Matchers must be added in a before function or a spec' ); } - var customMatchers = + const customMatchers = runnableResources[currentRunnable().id].customMatchers; - for (var matcherName in matchersToAdd) { + for (const matcherName in matchersToAdd) { customMatchers[matcherName] = matchersToAdd[matcherName]; } }; @@ -275,10 +280,10 @@ getJasmineRequireObj().Env = function(j$) { 'Async Matchers must be added in a before function or a spec' ); } - var customAsyncMatchers = + const customAsyncMatchers = runnableResources[currentRunnable().id].customAsyncMatchers; - for (var matcherName in matchersToAdd) { + for (const matcherName in matchersToAdd) { customAsyncMatchers[matcherName] = matchersToAdd[matcherName]; } }; @@ -298,23 +303,25 @@ getJasmineRequireObj().Env = function(j$) { j$.Expectation.addCoreMatchers(j$.matchers); j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers); - var nextSpecId = 0; - var getNextSpecId = function() { + let nextSpecId = 0; + + function getNextSpecId() { return 'spec' + nextSpecId++; - }; + } - var nextSuiteId = 0; - var getNextSuiteId = function() { + let nextSuiteId = 0; + + function getNextSuiteId() { return 'suite' + nextSuiteId++; - }; + } - var makePrettyPrinter = function() { - var customObjectFormatters = + function makePrettyPrinter() { + const customObjectFormatters = runnableResources[currentRunnable().id].customObjectFormatters; return j$.makePrettyPrinter(customObjectFormatters); - }; + } - var makeMatchersUtil = function() { + function makeMatchersUtil() { const cr = currentRunnable(); if (cr) { @@ -327,7 +334,7 @@ getJasmineRequireObj().Env = function(j$) { } else { return new j$.MatchersUtil({ pp: j$.basicPrettyPrinter_ }); } - }; + } const expectationFactory = function(actual, spec) { return j$.Expectation.factory({ @@ -360,7 +367,7 @@ getJasmineRequireObj().Env = function(j$) { } function recordLateExpectation(runable, runableType, result) { - var delayedExpectationResult = {}; + const delayedExpectationResult = {}; Object.keys(result).forEach(function(k) { delayedExpectationResult[k] = result[k]; }); @@ -430,8 +437,8 @@ getJasmineRequireObj().Env = function(j$) { return asyncExpectationFactory(actual, suite, 'Spec'); }; - var defaultResourcesForRunnable = function(id, parentRunnableId) { - var resources = { + function defaultResourcesForRunnable(id, parentRunnableId) { + const resources = { spies: [], customEqualityTesters: [], customMatchers: {}, @@ -462,16 +469,16 @@ getJasmineRequireObj().Env = function(j$) { } runnableResources[id] = resources; - }; + } - var clearResourcesForRunnable = function(id) { + function clearResourcesForRunnable(id) { spyRegistry.clearSpies(); delete runnableResources[id]; - }; + } - var beforeAndAfterFns = function(targetSuite) { + function beforeAndAfterFns(targetSuite) { return function() { - var befores = [], + let befores = [], afters = [], suite = targetSuite; @@ -487,17 +494,17 @@ getJasmineRequireObj().Env = function(j$) { afters: afters }; }; - }; + } - var getSpecName = function(spec, suite) { - var fullName = [spec.description], + function getSpecName(spec, suite) { + const fullName = [spec.description], suiteFullName = suite.getFullName(); if (suiteFullName !== '') { fullName.unshift(suiteFullName); } return fullName.join(' '); - }; + } /** * Causes a deprecation warning to be logged to the console and reported to @@ -522,11 +529,11 @@ getJasmineRequireObj().Env = function(j$) { * @param {Object} [options] Optional extra options, as described above */ this.deprecated = function(deprecation, options) { - var runnable = currentRunnable() || topSuite; + const runnable = currentRunnable() || topSuite; deprecator.addDeprecationWarning(runnable, deprecation, options); }; - var queueRunnerFactory = function(options, args) { + function queueRunnerFactory(options, args) { if (options.isLeaf) { // A spec options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy; @@ -557,9 +564,9 @@ getJasmineRequireObj().Env = function(j$) { options.deprecated = self.deprecated; new j$.QueueRunner(options).execute(args); - }; + } - var topSuite = new j$.Suite({ + topSuite = new j$.Suite({ id: getNextSuiteId(), description: 'Jasmine__TopLevel__Suite', expectationFactory: expectationFactory, @@ -567,7 +574,7 @@ getJasmineRequireObj().Env = function(j$) { autoCleanClosures: config.autoCleanClosures, onLateError: recordLateError }); - var deprecator = new j$.Deprecator(topSuite); + deprecator = new j$.Deprecator(topSuite); currentDeclarationSuite = topSuite; /** @@ -587,7 +594,7 @@ getJasmineRequireObj().Env = function(j$) { * @interface Reporter * @see custom_reporter */ - var reporter = new j$.ReportDispatcher( + reporter = new j$.ReportDispatcher( [ /** * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. @@ -705,12 +712,12 @@ getJasmineRequireObj().Env = function(j$) { } } - var order = new j$.Order({ + const order = new j$.Order({ random: config.random, seed: config.seed }); - var processor = new j$.TreeProcessor({ + const processor = new j$.TreeProcessor({ tree: topSuite, runnableIds: runnablesToRun, queueRunnerFactory: queueRunnerFactory, @@ -756,7 +763,7 @@ getJasmineRequireObj().Env = function(j$) { ); } - var jasmineTimer = new j$.Timer(); + const jasmineTimer = new j$.Timer(); jasmineTimer.start(); return new Promise(function(resolve) { @@ -793,7 +800,7 @@ getJasmineRequireObj().Env = function(j$) { clearResourcesForRunnable(topSuite.id); currentlyExecutingSuites.pop(); - var overallStatus, incompleteReason; + let overallStatus, incompleteReason; if ( hasFailures || @@ -915,9 +922,9 @@ getJasmineRequireObj().Env = function(j$) { reporter.clearReporters(); }; - var spyFactory = new j$.SpyFactory( + const spyFactory = new j$.SpyFactory( function getCustomStrategies() { - var runnable = currentRunnable(); + const runnable = currentRunnable(); if (runnable) { return runnableResources[runnable.id].customSpyStrategies; @@ -926,7 +933,7 @@ getJasmineRequireObj().Env = function(j$) { return {}; }, function getDefaultStrategyFn() { - var runnable = currentRunnable(); + const runnable = currentRunnable(); if (runnable) { return runnableResources[runnable.id].defaultStrategyFn; @@ -937,7 +944,7 @@ getJasmineRequireObj().Env = function(j$) { makeMatchersUtil ); - var spyRegistry = new j$.SpyRegistry({ + spyRegistry = new j$.SpyRegistry({ currentSpies: function() { if (!currentRunnable()) { throw new Error( @@ -989,24 +996,24 @@ getJasmineRequireObj().Env = function(j$) { return spyFactory.createSpyObj(baseName, methodNames, propertyNames); }; - var ensureIsFunction = function(fn, caller) { + function ensureIsFunction(fn, caller) { if (!j$.isFunction_(fn)) { throw new Error( caller + ' expects a function argument; received ' + j$.getType_(fn) ); } - }; + } - var ensureIsFunctionOrAsync = function(fn, caller) { + function ensureIsFunctionOrAsync(fn, caller) { if (!j$.isFunction_(fn) && !j$.isAsyncFunction_(fn)) { throw new Error( caller + ' expects a function argument; received ' + j$.getType_(fn) ); } - }; + } function ensureIsNotNested(method) { - var runnable = currentRunnable(); + const runnable = currentRunnable(); if (runnable !== null && runnable !== undefined) { throw new Error( "'" + method + "' should only be used in 'describe' function" @@ -1014,8 +1021,8 @@ getJasmineRequireObj().Env = function(j$) { } } - var suiteFactory = function(description) { - var suite = new j$.Suite({ + function suiteFactory(description) { + return new j$.Suite({ id: getNextSuiteId(), description: description, parentSuite: currentDeclarationSuite, @@ -1026,14 +1033,12 @@ getJasmineRequireObj().Env = function(j$) { autoCleanClosures: config.autoCleanClosures, onLateError: recordLateError }); - - return suite; - }; + } this.describe = function(description, specDefinitions) { ensureIsNotNested('describe'); ensureIsFunction(specDefinitions, 'describe'); - var suite = suiteFactory(description); + const suite = suiteFactory(description); if (specDefinitions.length > 0) { throw new Error('describe does not expect any arguments'); } @@ -1053,18 +1058,16 @@ getJasmineRequireObj().Env = function(j$) { this.xdescribe = function(description, specDefinitions) { ensureIsNotNested('xdescribe'); ensureIsFunction(specDefinitions, 'xdescribe'); - var suite = suiteFactory(description); + const suite = suiteFactory(description); suite.exclude(); addSpecsToSuite(suite, specDefinitions); return suite.metadata; }; - var focusedRunnables = []; - this.fdescribe = function(description, specDefinitions) { ensureIsNotNested('fdescribe'); ensureIsFunction(specDefinitions, 'fdescribe'); - var suite = suiteFactory(description); + const suite = suiteFactory(description); suite.isFocused = true; focusedRunnables.push(suite.id); @@ -1075,11 +1078,11 @@ getJasmineRequireObj().Env = function(j$) { }; function addSpecsToSuite(suite, specDefinitions) { - var parentSuite = currentDeclarationSuite; + const parentSuite = currentDeclarationSuite; parentSuite.addChild(suite); currentDeclarationSuite = suite; - var declarationError = null; + let declarationError = null; try { specDefinitions(); } catch (e) { @@ -1105,9 +1108,9 @@ getJasmineRequireObj().Env = function(j$) { } function unfocusAncestor() { - var focusedAncestor = findFocusedAncestor(currentDeclarationSuite); + const focusedAncestor = findFocusedAncestor(currentDeclarationSuite); if (focusedAncestor) { - for (var i = 0; i < focusedRunnables.length; i++) { + for (let i = 0; i < focusedRunnables.length; i++) { if (focusedRunnables[i] === focusedAncestor) { focusedRunnables.splice(i, 1); break; @@ -1116,9 +1119,9 @@ getJasmineRequireObj().Env = function(j$) { } } - var specFactory = function(description, fn, suite, timeout) { + const specFactory = function(description, fn, suite, timeout) { totalSpecsDefined++; - var spec = new j$.Spec({ + const spec = new j$.Spec({ id: getNextSpecId(), beforeAndAfterFns: beforeAndAfterFns(suite), expectationFactory: expectationFactory, @@ -1184,7 +1187,12 @@ getJasmineRequireObj().Env = function(j$) { j$.util.validateTimeout(timeout); } - var spec = specFactory(description, fn, currentDeclarationSuite, timeout); + const spec = specFactory( + description, + fn, + currentDeclarationSuite, + timeout + ); if (currentDeclarationSuite.markedExcluding) { spec.exclude(); } @@ -1205,7 +1213,7 @@ getJasmineRequireObj().Env = function(j$) { if (arguments.length > 1 && typeof fn !== 'undefined') { ensureIsFunctionOrAsync(fn, 'xit'); } - var spec = this.it_.apply(this, arguments); + const spec = this.it_.apply(this, arguments); spec.exclude('Temporarily disabled with xit'); return spec.metadata; }; @@ -1217,7 +1225,12 @@ getJasmineRequireObj().Env = function(j$) { if (timeout) { j$.util.validateTimeout(timeout); } - var spec = specFactory(description, fn, currentDeclarationSuite, timeout); + const spec = specFactory( + description, + fn, + currentDeclarationSuite, + timeout + ); currentDeclarationSuite.addChild(spec); focusedRunnables.push(spec.id); unfocusAncestor(); @@ -1259,7 +1272,7 @@ getJasmineRequireObj().Env = function(j$) { }; this.debugLog = function(msg) { - var maybeSpec = currentRunnable(); + const maybeSpec = currentRunnable(); if (!maybeSpec || !maybeSpec.debugLog) { throw new Error("'debugLog' was called when there was no current spec"); @@ -1346,7 +1359,7 @@ getJasmineRequireObj().Env = function(j$) { }; this.pending = function(message) { - var fullMessage = j$.Spec.pendingSpecExceptionMessage; + let fullMessage = j$.Spec.pendingSpecExceptionMessage; if (message) { fullMessage += message; } @@ -1360,7 +1373,7 @@ getJasmineRequireObj().Env = function(j$) { ); } - var message = 'Failed'; + let message = 'Failed'; if (error) { message += ': '; if (error.message) { diff --git a/src/core/ExpectationFilterChain.js b/src/core/ExpectationFilterChain.js index d7f020b8..490d7d99 100644 --- a/src/core/ExpectationFilterChain.js +++ b/src/core/ExpectationFilterChain.js @@ -22,15 +22,13 @@ getJasmineRequireObj().ExpectationFilterChain = function() { }; ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { - var result = this.callFirst_('modifyFailureMessage', arguments).result; + const result = this.callFirst_('modifyFailureMessage', arguments).result; return result || msg; }; ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { - var prevResult; - if (this.prev_) { - prevResult = this.prev_.callFirst_(fname, args); + const prevResult = this.prev_.callFirst_(fname, args); if (prevResult.found) { return prevResult; diff --git a/src/core/Expector.js b/src/core/Expector.js index df4878da..41db72f3 100644 --- a/src/core/Expector.js +++ b/src/core/Expector.js @@ -19,20 +19,20 @@ getJasmineRequireObj().Expector = function(j$) { this.args.unshift(this.actual); - var matcher = matcherFactory(this.matchersUtil); + const matcher = matcherFactory(this.matchersUtil); - var comparisonFunc = this.filters.selectComparisonFunc(matcher); + const comparisonFunc = this.filters.selectComparisonFunc(matcher); return comparisonFunc || matcher.compare; }; Expector.prototype.buildMessage = function(result) { - var self = this; + const self = this; if (result.pass) { return ''; } - var msg = this.filters.buildFailureMessage( + const msg = this.filters.buildFailureMessage( result, this.matcherName, this.args, @@ -43,7 +43,7 @@ getJasmineRequireObj().Expector = function(j$) { function defaultMessage() { if (!result.message) { - var args = self.args.slice(); + const args = self.args.slice(); args.unshift(false); args.unshift(self.matcherName); return self.matchersUtil.buildFailureMessage.apply( @@ -59,7 +59,7 @@ getJasmineRequireObj().Expector = function(j$) { }; Expector.prototype.compare = function(matcherName, matcherFactory, args) { - var matcherCompare = this.instantiateMatcher( + const matcherCompare = this.instantiateMatcher( matcherName, matcherFactory, args @@ -68,13 +68,13 @@ getJasmineRequireObj().Expector = function(j$) { }; Expector.prototype.addFilter = function(filter) { - var result = Object.create(this); + const result = Object.create(this); result.filters = this.filters.addFilter(filter); return result; }; Expector.prototype.processResult = function(result, errorForStack) { - var message = this.buildMessage(result); + const message = this.buildMessage(result); if (this.expected.length === 1) { this.expected = this.expected[0]; diff --git a/src/core/GlobalErrors.js b/src/core/GlobalErrors.js index d96e26c8..af2cf9ac 100644 --- a/src/core/GlobalErrors.js +++ b/src/core/GlobalErrors.js @@ -1,10 +1,10 @@ getJasmineRequireObj().GlobalErrors = function(j$) { function GlobalErrors(global) { - var handlers = []; + const handlers = []; global = global || j$.getGlobal(); - var onerror = function onerror() { - var handler = handlers[handlers.length - 1]; + const onerror = function onerror() { + const handler = handlers[handlers.length - 1]; if (handler) { handler.apply(null, Array.prototype.slice.call(arguments, 0)); @@ -17,11 +17,11 @@ getJasmineRequireObj().GlobalErrors = function(j$) { this.jasmineHandlers = {}; this.installOne_ = function installOne_(errorType, jasmineMessage) { function taggedOnError(error) { - var substituteMsg; - if (j$.isError_(error)) { error.jasmineMessage = jasmineMessage + ': ' + error; } else { + let substituteMsg; + if (error) { substituteMsg = jasmineMessage + ': ' + error; } else { @@ -40,7 +40,7 @@ getJasmineRequireObj().GlobalErrors = function(j$) { error = new Error(substituteMsg); } - var handler = handlers[handlers.length - 1]; + const handler = handlers[handlers.length - 1]; if (handler) { handler(error); @@ -56,14 +56,14 @@ getJasmineRequireObj().GlobalErrors = function(j$) { global.process.on(errorType, taggedOnError); this.uninstall = function uninstall() { - var errorTypes = Object.keys(this.originalHandlers); - for (var iType = 0; iType < errorTypes.length; iType++) { - var errorType = errorTypes[iType]; + const errorTypes = Object.keys(this.originalHandlers); + for (const errorType of errorTypes) { global.process.removeListener( errorType, this.jasmineHandlers[errorType] ); - for (var i = 0; i < this.originalHandlers[errorType].length; i++) { + + for (let i = 0; i < this.originalHandlers[errorType].length; i++) { global.process.on(errorType, this.originalHandlers[errorType][i]); } delete this.originalHandlers[errorType]; @@ -81,10 +81,12 @@ getJasmineRequireObj().GlobalErrors = function(j$) { this.installOne_('uncaughtException', 'Uncaught exception'); this.installOne_('unhandledRejection', 'Unhandled promise rejection'); } else { - var originalHandler = global.onerror; + const originalHandler = global.onerror; global.onerror = onerror; - var browserRejectionHandler = function browserRejectionHandler(event) { + const browserRejectionHandler = function browserRejectionHandler( + event + ) { if (j$.isError_(event.reason)) { event.reason.jasmineMessage = 'Unhandled promise rejection: ' + event.reason; diff --git a/src/core/JsApiReporter.js b/src/core/JsApiReporter.js index a498f388..8ee3ecc5 100644 --- a/src/core/JsApiReporter.js +++ b/src/core/JsApiReporter.js @@ -6,8 +6,8 @@ getJasmineRequireObj().JsApiReporter = function(j$) { * @hideconstructor */ function JsApiReporter(options) { - var timer = options.timer || new j$.Timer(), - status = 'loaded'; + const timer = options.timer || new j$.Timer(); + let status = 'loaded'; this.started = false; this.finished = false; @@ -19,7 +19,7 @@ getJasmineRequireObj().JsApiReporter = function(j$) { timer.start(); }; - var executionTime; + let executionTime; this.jasmineDone = function(runDetails) { this.finished = true; @@ -39,7 +39,7 @@ getJasmineRequireObj().JsApiReporter = function(j$) { return status; }; - var suites = [], + const suites = [], suites_hash = {}; this.suiteStarted = function(result) { @@ -81,7 +81,7 @@ getJasmineRequireObj().JsApiReporter = function(j$) { return suites_hash; }; - var specs = []; + const specs = []; this.specDone = function(result) { specs.push(result); diff --git a/src/core/MockDate.js b/src/core/MockDate.js index feefe458..01b7ad00 100644 --- a/src/core/MockDate.js +++ b/src/core/MockDate.js @@ -1,7 +1,7 @@ getJasmineRequireObj().MockDate = function(j$) { function MockDate(global) { - var self = this; - var currentTime = 0; + const self = this; + let currentTime = 0; if (!global || !global.Date) { self.install = function() {}; @@ -10,7 +10,7 @@ getJasmineRequireObj().MockDate = function(j$) { return self; } - var GlobalDate = global.Date; + const GlobalDate = global.Date; self.install = function(mockDate) { if (mockDate instanceof GlobalDate) { diff --git a/src/core/Order.js b/src/core/Order.js index 9839da2a..3b9c27b5 100644 --- a/src/core/Order.js +++ b/src/core/Order.js @@ -1,7 +1,7 @@ getJasmineRequireObj().Order = function() { function Order(options) { this.random = 'random' in options ? options.random : true; - var seed = (this.seed = options.seed || generateSeed()); + const seed = (this.seed = options.seed || generateSeed()); this.sort = this.random ? randomOrder : naturalOrder; function naturalOrder(items) { @@ -9,7 +9,7 @@ getJasmineRequireObj().Order = function() { } function randomOrder(items) { - var copy = items.slice(); + const copy = items.slice(); copy.sort(function(a, b) { return jenkinsHash(seed + a.id) - jenkinsHash(seed + b.id); }); @@ -26,7 +26,7 @@ getJasmineRequireObj().Order = function() { // used in conjunction with a seed function jenkinsHash(key) { - var hash, i; + let hash, i; for (hash = i = 0; i < key.length; ++i) { hash += key.charCodeAt(i); hash += hash << 10; diff --git a/src/core/QueueRunner.js b/src/core/QueueRunner.js index 4467552e..2e061bbc 100644 --- a/src/core/QueueRunner.js +++ b/src/core/QueueRunner.js @@ -1,12 +1,12 @@ getJasmineRequireObj().QueueRunner = function(j$) { - var nextid = 1; + let nextid = 1; function StopExecutionError() {} StopExecutionError.prototype = new Error(); j$.StopExecutionError = StopExecutionError; function once(fn, onTwice) { - var called = false; + let called = false; return function(arg) { if (called) { if (onTwice) { @@ -66,7 +66,7 @@ getJasmineRequireObj().QueueRunner = function(j$) { } QueueRunner.prototype.execute = function() { - var self = this; + const self = this; this.handleFinalError = function(message, source, lineno, colno, error) { // Older browsers would send the error as the first parameter. HTML5 // specifies the the five parameters above. The error instance should @@ -92,57 +92,57 @@ getJasmineRequireObj().QueueRunner = function(j$) { }; QueueRunner.prototype.attempt = function attempt(iterativeIndex) { - var self = this, - completedSynchronously = true, - handleError = function handleError(error) { - // TODO probably shouldn't next() right away here. - // That makes debugging async failures much more confusing. - onException(error); + let timeoutId; + let timedOut; + const self = this; + let completedSynchronously = true; + function handleError(error) { + // TODO probably shouldn't next() right away here. + // That makes debugging async failures much more confusing. + onException(error); + } + const cleanup = once(function cleanup() { + if (timeoutId !== void 0) { + self.clearTimeout(timeoutId); + } + self.globalErrors.popListener(handleError); + }); + const next = once( + function next(err) { + cleanup(); + + if (typeof err !== 'undefined') { + if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { + self.fail(err); + } + self.recordError_(iterativeIndex); + } + + function runNext() { + self.run(self.nextFnIx_(iterativeIndex)); + } + + if (completedSynchronously) { + self.setTimeout(runNext); + } else { + runNext(); + } }, - cleanup = once(function cleanup() { - if (timeoutId !== void 0) { - self.clearTimeout(timeoutId); + function() { + try { + if (!timedOut) { + self.onMultipleDone(); + } + } catch (error) { + // Any error we catch here is probably due to a bug in Jasmine, + // and it's not likely to end up anywhere useful if we let it + // propagate. Log it so it can at least show up when debugging. + console.error(error); } - self.globalErrors.popListener(handleError); - }), - next = once( - function next(err) { - cleanup(); - - if (typeof err !== 'undefined') { - if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { - self.fail(err); - } - self.recordError_(iterativeIndex); - } - - function runNext() { - self.run(self.nextFnIx_(iterativeIndex)); - } - - if (completedSynchronously) { - self.setTimeout(runNext); - } else { - runNext(); - } - }, - function() { - try { - if (!timedOut) { - self.onMultipleDone(); - } - } catch (error) { - // Any error we catch here is probably due to a bug in Jasmine, - // and it's not likely to end up anywhere useful if we let it - // propagate. Log it so it can at least show up when debugging. - console.error(error); - } - } - ), - timedOut = false, - queueableFn = self.queueableFns[iterativeIndex], - timeoutId, - maybeThenable; + } + ); + timedOut = false; + const queueableFn = self.queueableFns[iterativeIndex]; next.fail = function nextFail() { self.fail.apply(null, arguments); @@ -153,10 +153,11 @@ getJasmineRequireObj().QueueRunner = function(j$) { self.globalErrors.pushListener(handleError); if (queueableFn.timeout !== undefined) { - var timeoutInterval = queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL; + const timeoutInterval = + queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL; timeoutId = self.setTimeout(function() { timedOut = true; - var error = new Error( + const error = new Error( 'Timeout - Async function did not complete within ' + timeoutInterval + 'ms ' + @@ -173,6 +174,8 @@ getJasmineRequireObj().QueueRunner = function(j$) { } try { + let maybeThenable; + if (queueableFn.fn.length === 0) { maybeThenable = queueableFn.fn.call(self.userContext); @@ -210,16 +213,15 @@ getJasmineRequireObj().QueueRunner = function(j$) { }; QueueRunner.prototype.run = function(recursiveIndex) { - var length = this.queueableFns.length, - self = this, - iterativeIndex; + const length = this.queueableFns.length; + const self = this; for ( - iterativeIndex = recursiveIndex; + let iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex = this.nextFnIx_(iterativeIndex) ) { - var result = this.attempt(iterativeIndex); + const result = this.attempt(iterativeIndex); if (!result.completedSynchronously) { return; diff --git a/src/core/ReportDispatcher.js b/src/core/ReportDispatcher.js index c2f957dc..ebd1fa1f 100644 --- a/src/core/ReportDispatcher.js +++ b/src/core/ReportDispatcher.js @@ -1,9 +1,8 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { function ReportDispatcher(methods, queueRunnerFactory, onLateError) { - var dispatchedMethods = methods || []; + const dispatchedMethods = methods || []; - for (var i = 0; i < dispatchedMethods.length; i++) { - var method = dispatchedMethods[i]; + for (const method of dispatchedMethods) { this[method] = (function(m) { return function() { dispatch(m, arguments); @@ -11,8 +10,8 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { })(method); } - var reporters = []; - var fallbackReporter = null; + let reporters = []; + let fallbackReporter = null; this.addReporter = function(reporter) { reporters.push(reporter); @@ -32,11 +31,10 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { if (reporters.length === 0 && fallbackReporter !== null) { reporters.push(fallbackReporter); } - var onComplete = args[args.length - 1]; + const onComplete = args[args.length - 1]; args = j$.util.argsToArray(args).splice(0, args.length - 1); - var fns = []; - for (var i = 0; i < reporters.length; i++) { - var reporter = reporters[i]; + const fns = []; + for (const reporter of reporters) { addFn(fns, reporter, method, args); } @@ -56,12 +54,12 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { } function addFn(fns, reporter, method, args) { - var fn = reporter[method]; + const fn = reporter[method]; if (!fn) { return; } - var thisArgs = j$.util.cloneArgs(args); + const thisArgs = j$.util.cloneArgs(args); if (fn.length <= 1) { fns.push({ fn: function() { diff --git a/src/core/Spec.js b/src/core/Spec.js index 6e767fbf..71f82258 100644 --- a/src/core/Spec.js +++ b/src/core/Spec.js @@ -100,16 +100,16 @@ getJasmineRequireObj().Spec = function(j$) { }; Spec.prototype.execute = function(onComplete, excluded, failSpecWithNoExp) { - var self = this; + const self = this; - var onStart = { + const onStart = { fn: function(done) { self.timer.start(); self.onStart(self, done); } }; - var complete = { + const complete = { fn: function(done) { if (self.autoCleanClosures) { self.queueableFn.fn = null; @@ -126,9 +126,9 @@ getJasmineRequireObj().Spec = function(j$) { type: 'specCleanup' }; - var fns = this.beforeAndAfterFns(); + const fns = this.beforeAndAfterFns(); - var runnerConfig = { + const runnerConfig = { isLeaf: true, queueableFns: [...fns.befores, this.queueableFn, ...fns.afters], onException: function() { @@ -289,8 +289,8 @@ getJasmineRequireObj().Spec = function(j$) { }); }; - var extractCustomPendingMessage = function(e) { - var fullMessage = e.toString(), + const extractCustomPendingMessage = function(e) { + const fullMessage = e.toString(), boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), boilerplateEnd = boilerplateStart + Spec.pendingSpecExceptionMessage.length; diff --git a/src/core/Spy.js b/src/core/Spy.js index 26d4b6b4..8701c52b 100644 --- a/src/core/Spy.js +++ b/src/core/Spy.js @@ -1,6 +1,6 @@ getJasmineRequireObj().Spy = function(j$) { - var nextOrder = (function() { - var order = 0; + const nextOrder = (function() { + let order = 0; return function() { return order++; @@ -15,9 +15,29 @@ getJasmineRequireObj().Spy = function(j$) { * @hideconstructor */ function Spy(name, matchersUtil, optionals) { + const spy = function(context, args, invokeNew) { + /** + * @name Spy.callData + * @property {object} object - `this` context for the invocation. + * @property {number} invocationOrder - Order of the invocation. + * @property {Array} args - The arguments passed for this invocation. + * @property returnValue - The value that was returned from this invocation. + */ + const callData = { + object: context, + invocationOrder: nextOrder(), + args: Array.prototype.slice.apply(args) + }; + + callTracker.track(callData); + const returnValue = strategyDispatcher.exec(context, args, invokeNew); + callData.returnValue = returnValue; + + return returnValue; + }; const { originalFn, customStrategies, defaultStrategyFn } = optionals || {}; - var numArgs = typeof originalFn === 'function' ? originalFn.length : 0, + const numArgs = typeof originalFn === 'function' ? originalFn.length : 0, wrapper = makeFunc(numArgs, function(context, args, invokeNew) { return spy(context, args, invokeNew); }), @@ -32,27 +52,7 @@ getJasmineRequireObj().Spy = function(j$) { }, matchersUtil ), - callTracker = new j$.CallTracker(), - spy = function(context, args, invokeNew) { - /** - * @name Spy.callData - * @property {object} object - `this` context for the invocation. - * @property {number} invocationOrder - Order of the invocation. - * @property {Array} args - The arguments passed for this invocation. - * @property returnValue - The value that was returned from this invocation. - */ - var callData = { - object: context, - invocationOrder: nextOrder(), - args: Array.prototype.slice.apply(args) - }; - - callTracker.track(callData); - var returnValue = strategyDispatcher.exec(context, args, invokeNew); - callData.returnValue = returnValue; - - return returnValue; - }; + callTracker = new j$.CallTracker(); function makeFunc(length, fn) { switch (length) { @@ -99,7 +99,7 @@ getJasmineRequireObj().Spy = function(j$) { } } - for (var prop in originalFn) { + for (const 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" @@ -144,15 +144,15 @@ getJasmineRequireObj().Spy = function(j$) { } function SpyStrategyDispatcher(strategyArgs, matchersUtil) { - var baseStrategy = new j$.SpyStrategy(strategyArgs); - var argsStrategies = new StrategyDict(function() { + const baseStrategy = new j$.SpyStrategy(strategyArgs); + const argsStrategies = new StrategyDict(function() { return new j$.SpyStrategy(strategyArgs); }, matchersUtil); this.and = baseStrategy; this.exec = function(spy, args, invokeNew) { - var strategy = argsStrategies.get(args); + let strategy = argsStrategies.get(args); if (!strategy) { if (argsStrategies.any() && !baseStrategy.isConfigured()) { @@ -187,7 +187,7 @@ getJasmineRequireObj().Spy = function(j$) { }; StrategyDict.prototype.getOrCreate = function(args) { - var strategy = this.get(args); + let strategy = this.get(args); if (!strategy) { strategy = this.strategyFactory(); @@ -201,9 +201,7 @@ getJasmineRequireObj().Spy = function(j$) { }; StrategyDict.prototype.get = function(args) { - var i; - - for (i = 0; i < this.strategies.length; i++) { + for (let i = 0; i < this.strategies.length; i++) { if (this.matchersUtil.equals(args, this.strategies[i].args)) { return this.strategies[i].strategy; } diff --git a/src/core/SpyFactory.js b/src/core/SpyFactory.js index 03bd6035..e44c1408 100644 --- a/src/core/SpyFactory.js +++ b/src/core/SpyFactory.js @@ -4,7 +4,7 @@ getJasmineRequireObj().SpyFactory = function(j$) { getDefaultStrategyFn, getMatchersUtil ) { - var self = this; + const self = this; this.createSpy = function(name, originalFn) { return j$.Spy(name, getMatchersUtil(), { @@ -15,7 +15,7 @@ getJasmineRequireObj().SpyFactory = function(j$) { }; this.createSpyObj = function(baseName, methodNames, propertyNames) { - var baseNameIsCollection = + const baseNameIsCollection = j$.isObject_(baseName) || j$.isArray_(baseName); if (baseNameIsCollection) { @@ -24,22 +24,21 @@ getJasmineRequireObj().SpyFactory = function(j$) { baseName = 'unknown'; } - var obj = {}; - var spy, descriptor; + const obj = {}; - var methods = normalizeKeyValues(methodNames); - for (var i = 0; i < methods.length; i++) { - spy = obj[methods[i][0]] = self.createSpy( + const methods = normalizeKeyValues(methodNames); + for (let i = 0; i < methods.length; i++) { + const spy = (obj[methods[i][0]] = self.createSpy( baseName + '.' + methods[i][0] - ); + )); if (methods[i].length > 1) { spy.and.returnValue(methods[i][1]); } } - var properties = normalizeKeyValues(propertyNames); - for (var i = 0; i < properties.length; i++) { - descriptor = { + const properties = normalizeKeyValues(propertyNames); + for (let i = 0; i < properties.length; i++) { + const descriptor = { enumerable: true, get: self.createSpy(baseName + '.' + properties[i][0] + '.get'), set: self.createSpy(baseName + '.' + properties[i][0] + '.set') @@ -60,13 +59,13 @@ getJasmineRequireObj().SpyFactory = function(j$) { } function normalizeKeyValues(object) { - var result = []; + const result = []; if (j$.isArray_(object)) { - for (var i = 0; i < object.length; i++) { + for (let i = 0; i < object.length; i++) { result.push([object[i]]); } } else if (j$.isObject_(object)) { - for (var key in object) { + for (const key in object) { if (object.hasOwnProperty(key)) { result.push([key, object[key]]); } diff --git a/src/core/SpyRegistry.js b/src/core/SpyRegistry.js index 140bd990..ff8da7e5 100644 --- a/src/core/SpyRegistry.js +++ b/src/core/SpyRegistry.js @@ -1,15 +1,18 @@ getJasmineRequireObj().SpyRegistry = function(j$) { - var spyOnMsg = j$.formatErrorMsg('', 'spyOn(, )'); - var spyOnPropertyMsg = j$.formatErrorMsg( + const spyOnMsg = j$.formatErrorMsg( + '', + 'spyOn(, )' + ); + const spyOnPropertyMsg = j$.formatErrorMsg( '', 'spyOnProperty(, , [accessType])' ); function SpyRegistry(options) { options = options || {}; - var global = options.global || j$.getGlobal(); - var createSpy = options.createSpy; - var currentSpies = + const global = options.global || j$.getGlobal(); + const createSpy = options.createSpy; + const currentSpies = options.currentSpies || function() { return []; @@ -20,7 +23,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { }; this.spyOn = function(obj, methodName) { - var getErrorMsg = spyOnMsg; + const getErrorMsg = spyOnMsg; if (j$.util.isUndefined(obj) || obj === null) { throw new Error( @@ -48,7 +51,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } } - var descriptor = Object.getOwnPropertyDescriptor(obj, methodName); + const descriptor = Object.getOwnPropertyDescriptor(obj, methodName); if (descriptor && !(descriptor.writable || descriptor.set)) { throw new Error( @@ -56,9 +59,9 @@ getJasmineRequireObj().SpyRegistry = function(j$) { ); } - var originalMethod = obj[methodName], - spiedMethod = createSpy(methodName, originalMethod), - restoreStrategy; + const originalMethod = obj[methodName]; + const spiedMethod = createSpy(methodName, originalMethod); + let restoreStrategy; if ( Object.prototype.hasOwnProperty.call(obj, methodName) || @@ -85,7 +88,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { }; this.spyOnProperty = function(obj, propertyName, accessType) { - var getErrorMsg = spyOnPropertyMsg; + const getErrorMsg = spyOnPropertyMsg; accessType = accessType || 'get'; @@ -103,7 +106,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { throw new Error(getErrorMsg('No property name supplied')); } - var descriptor = j$.util.getPropertyDescriptor(obj, propertyName); + const descriptor = j$.util.getPropertyDescriptor(obj, propertyName); if (!descriptor) { throw new Error(getErrorMsg(propertyName + ' property does not exist')); @@ -138,9 +141,9 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } } - var originalDescriptor = j$.util.clone(descriptor), - spy = createSpy(propertyName, descriptor[accessType]), - restoreStrategy; + const originalDescriptor = j$.util.clone(descriptor); + const spy = createSpy(propertyName, descriptor[accessType]); + let restoreStrategy; if (Object.prototype.hasOwnProperty.call(obj, propertyName)) { restoreStrategy = function() { @@ -170,7 +173,7 @@ getJasmineRequireObj().SpyRegistry = function(j$) { ); } - var pointer = obj, + let pointer = obj, propsToSpyOn = [], properties, propertiesToSkip = []; @@ -190,24 +193,24 @@ getJasmineRequireObj().SpyRegistry = function(j$) { pointer = Object.getPrototypeOf(pointer); } - for (var i = 0; i < propsToSpyOn.length; i++) { - this.spyOn(obj, propsToSpyOn[i]); + for (const prop of propsToSpyOn) { + this.spyOn(obj, prop); } return obj; }; this.clearSpies = function() { - var spies = currentSpies(); - for (var i = spies.length - 1; i >= 0; i--) { - var spyEntry = spies[i]; + const spies = currentSpies(); + for (let i = spies.length - 1; i >= 0; i--) { + const spyEntry = spies[i]; spyEntry.restoreObjectToOriginalState(); } }; } function getProps(obj, includeNonEnumerable) { - var enumerableProperties = Object.keys(obj); + const enumerableProperties = Object.keys(obj); if (!includeNonEnumerable) { return enumerableProperties; @@ -222,10 +225,9 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } function getSpyableFunctionProps(obj, propertiesToCheck) { - var props = [], - prop; - for (var i = 0; i < propertiesToCheck.length; i++) { - prop = propertiesToCheck[i]; + const props = []; + + for (const prop of propertiesToCheck) { if ( Object.prototype.hasOwnProperty.call(obj, prop) && isSpyableProp(obj, prop) @@ -237,14 +239,15 @@ getJasmineRequireObj().SpyRegistry = function(j$) { } function isSpyableProp(obj, prop) { - var value, descriptor; + let value; try { value = obj[prop]; } catch (e) { return false; } + if (value instanceof Function) { - descriptor = Object.getOwnPropertyDescriptor(obj, prop); + const descriptor = Object.getOwnPropertyDescriptor(obj, prop); return (descriptor.writable || descriptor.set) && descriptor.configurable; } return false; diff --git a/src/core/SpyStrategy.js b/src/core/SpyStrategy.js index c4334611..f93f330c 100644 --- a/src/core/SpyStrategy.js +++ b/src/core/SpyStrategy.js @@ -5,7 +5,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { function SpyStrategy(options) { options = options || {}; - var self = this; + const self = this; /** * Get the identifying information for the spy. @@ -19,9 +19,8 @@ getJasmineRequireObj().SpyStrategy = function(j$) { this.getSpy = options.getSpy || function() {}; this.plan = this._defaultPlan = function() {}; - var k, - cs = options.customStrategies || {}; - for (k in cs) { + const cs = options.customStrategies || {}; + for (const k in cs) { if (j$.util.has(cs, k) && !this[k]) { this[k] = createCustomPlan(cs[k]); } @@ -58,7 +57,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { function createCustomPlan(factory) { return function() { - var plan = factory.apply(null, arguments); + const plan = factory.apply(null, arguments); if (!j$.isFunction_(plan)) { throw new Error('Spy strategy must return a function'); @@ -76,10 +75,10 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @function */ SpyStrategy.prototype.exec = function(context, args, invokeNew) { - var contextArgs = [context].concat( + const contextArgs = [context].concat( args ? Array.prototype.slice.call(args) : [] ); - var target = this.plan.bind.apply(this.plan, contextArgs); + const target = this.plan.bind.apply(this.plan, contextArgs); return invokeNew ? new target() : target(); }; @@ -117,7 +116,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {...*} values - Values to be returned on subsequent calls to the spy. */ SpyStrategy.prototype.returnValues = function() { - var values = Array.prototype.slice.call(arguments); + const values = Array.prototype.slice.call(arguments); this.plan = function() { return values.shift(); }; @@ -132,7 +131,7 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {Error|Object|String} something Thing to throw */ SpyStrategy.prototype.throwError = function(something) { - var error = j$.isString_(something) ? new Error(something) : something; + const error = j$.isString_(something) ? new Error(something) : something; this.plan = function() { throw error; }; diff --git a/src/core/StackTrace.js b/src/core/StackTrace.js index 32d9d1f2..2f930beb 100644 --- a/src/core/StackTrace.js +++ b/src/core/StackTrace.js @@ -1,22 +1,22 @@ getJasmineRequireObj().StackTrace = function(j$) { function StackTrace(error) { - var lines = error.stack.split('\n').filter(function(line) { + let lines = error.stack.split('\n').filter(function(line) { return line !== ''; }); - var extractResult = extractMessage(error.message, lines); + const extractResult = extractMessage(error.message, lines); if (extractResult) { this.message = extractResult.message; lines = extractResult.remainder; } - var parseResult = tryParseFrames(lines); + const parseResult = tryParseFrames(lines); this.frames = parseResult.frames; this.style = parseResult.style; } - var framePatterns = [ + const framePatterns = [ // Node, Chrome, Edge // 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 @@ -46,16 +46,15 @@ getJasmineRequireObj().StackTrace = function(j$) { // regexes should capture the function name (if any) as group 1 // and the file, line, and column as group 2. function tryParseFrames(lines) { - var style = null; - var frames = lines.map(function(line) { - var convertedLine = first(framePatterns, function(pattern) { - var overallMatch = line.match(pattern.re), - fileLineColMatch; + let style = null; + const frames = lines.map(function(line) { + const convertedLine = first(framePatterns, function(pattern) { + const overallMatch = line.match(pattern.re); if (!overallMatch) { return null; } - fileLineColMatch = overallMatch[pattern.fileLineColIx].match( + const fileLineColMatch = overallMatch[pattern.fileLineColIx].match( /^(.*):(\d+):\d+$/ ); if (!fileLineColMatch) { @@ -81,10 +80,8 @@ getJasmineRequireObj().StackTrace = function(j$) { } function first(items, fn) { - var i, result; - - for (i = 0; i < items.length; i++) { - result = fn(items[i]); + for (const item of items) { + const result = fn(item); if (result) { return result; @@ -93,7 +90,7 @@ getJasmineRequireObj().StackTrace = function(j$) { } function extractMessage(message, stackLines) { - var len = messagePrefixLength(message, stackLines); + const len = messagePrefixLength(message, stackLines); if (len > 0) { return { @@ -108,10 +105,9 @@ getJasmineRequireObj().StackTrace = function(j$) { return 0; } - var messageLines = message.split('\n'); - var i; + const messageLines = message.split('\n'); - for (i = 1; i < messageLines.length; i++) { + for (let i = 1; i < messageLines.length; i++) { if (messageLines[i] !== stackLines[i]) { return 0; } diff --git a/src/core/Suite.js b/src/core/Suite.js index 84d7e770..9ff02d03 100644 --- a/src/core/Suite.js +++ b/src/core/Suite.js @@ -35,9 +35,9 @@ getJasmineRequireObj().Suite = function(j$) { }; Suite.prototype.getFullName = function() { - var fullName = []; + const fullName = []; for ( - var parentSuite = this; + let parentSuite = this; parentSuite; parentSuite = parentSuite.parentSuite ) { @@ -89,8 +89,8 @@ getJasmineRequireObj().Suite = function(j$) { }; function removeFns(queueableFns) { - for (var i = 0; i < queueableFns.length; i++) { - queueableFns[i].fn = null; + for (const qf of queueableFns) { + qf.fn = null; } } diff --git a/src/core/Timer.js b/src/core/Timer.js index ebe6983d..8a7bf7ea 100644 --- a/src/core/Timer.js +++ b/src/core/Timer.js @@ -1,5 +1,5 @@ getJasmineRequireObj().Timer = function() { - var defaultNow = (function(Date) { + const defaultNow = (function(Date) { return function() { return new Date().getTime(); }; @@ -8,8 +8,8 @@ getJasmineRequireObj().Timer = function() { function Timer(options) { options = options || {}; - var now = options.now || defaultNow, - startTime; + const now = options.now || defaultNow; + let startTime; this.start = function() { startTime = now(); diff --git a/src/core/TreeProcessor.js b/src/core/TreeProcessor.js index b81ce357..99cd781f 100644 --- a/src/core/TreeProcessor.js +++ b/src/core/TreeProcessor.js @@ -1,25 +1,25 @@ getJasmineRequireObj().TreeProcessor = function() { function TreeProcessor(attrs) { - var tree = attrs.tree, - runnableIds = attrs.runnableIds, - queueRunnerFactory = attrs.queueRunnerFactory, - nodeStart = attrs.nodeStart || function() {}, - nodeComplete = attrs.nodeComplete || function() {}, - failSpecWithNoExpectations = !!attrs.failSpecWithNoExpectations, - 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; + const tree = attrs.tree; + const runnableIds = attrs.runnableIds; + const queueRunnerFactory = attrs.queueRunnerFactory; + const nodeStart = attrs.nodeStart || function() {}; + const nodeComplete = attrs.nodeComplete || function() {}; + const failSpecWithNoExpectations = !!attrs.failSpecWithNoExpectations; + const orderChildren = + attrs.orderChildren || + function(node) { + return node.children; + }; + const excludeNode = + attrs.excludeNode || + function(node) { + return false; + }; + let stats = { valid: true }; + let processed = false; + const defaultMin = Infinity; + const defaultMax = 1 - Infinity; this.processTree = function() { processNode(tree, true); @@ -36,7 +36,7 @@ getJasmineRequireObj().TreeProcessor = function() { throw 'invalid order'; } - var childFns = wrapChildren(tree, 0); + const childFns = wrapChildren(tree, 0); queueRunnerFactory({ queueableFns: childFns, @@ -52,7 +52,7 @@ getJasmineRequireObj().TreeProcessor = function() { }; function runnableIndex(id) { - for (var i = 0; i < runnableIds.length; i++) { + for (let i = 0; i < runnableIds.length; i++) { if (runnableIds[i] === id) { return i; } @@ -60,14 +60,14 @@ getJasmineRequireObj().TreeProcessor = function() { } function processNode(node, parentExcluded) { - var executableIndex = runnableIndex(node.id); + const executableIndex = runnableIndex(node.id); if (executableIndex !== undefined) { parentExcluded = false; } if (!node.children) { - var excluded = parentExcluded || excludeNode(node); + const excluded = parentExcluded || excludeNode(node); stats[node.id] = { excluded: excluded, willExecute: !excluded && !node.markedPending, @@ -82,12 +82,12 @@ getJasmineRequireObj().TreeProcessor = function() { ] }; } else { - var hasExecutableChild = false; + let hasExecutableChild = false; - var orderedChildren = orderChildren(node); + const orderedChildren = orderChildren(node); - for (var i = 0; i < orderedChildren.length; i++) { - var child = orderedChildren[i]; + for (let i = 0; i < orderedChildren.length; i++) { + const child = orderedChildren[i]; processNode(child, parentExcluded); @@ -95,7 +95,7 @@ getJasmineRequireObj().TreeProcessor = function() { return; } - var childStats = stats[child.id]; + const childStats = stats[child.id]; hasExecutableChild = hasExecutableChild || childStats.willExecute; } @@ -127,7 +127,7 @@ getJasmineRequireObj().TreeProcessor = function() { nodeStats, executableIndex ) { - var currentSegment = { + let currentSegment = { index: 0, owner: node, nodes: [], @@ -146,8 +146,8 @@ getJasmineRequireObj().TreeProcessor = function() { ); } - for (var i = 0; i < orderedChildSegments.length; i++) { - var childSegment = orderedChildSegments[i], + for (let i = 0; i < orderedChildSegments.length; i++) { + const childSegment = orderedChildSegments[i], maxIndex = childSegment.max, minIndex = childSegment.min; @@ -172,15 +172,15 @@ getJasmineRequireObj().TreeProcessor = function() { } function orderChildSegments(children) { - var specifiedOrder = [], + const specifiedOrder = [], unspecifiedOrder = []; - for (var i = 0; i < children.length; i++) { - var child = children[i], + for (let i = 0; i < children.length; i++) { + const child = children[i], segments = stats[child.id].segments; - for (var j = 0; j < segments.length; j++) { - var seg = segments[j]; + for (let j = 0; j < segments.length; j++) { + const seg = segments[j]; if (seg.min === defaultMin) { unspecifiedOrder.push(seg); @@ -201,7 +201,7 @@ getJasmineRequireObj().TreeProcessor = function() { if (node.children) { return { fn: function(done) { - var onStart = { + const onStart = { fn: function(next) { nodeStart(node, next); } @@ -209,7 +209,7 @@ getJasmineRequireObj().TreeProcessor = function() { queueRunnerFactory({ onComplete: function() { - var args = Array.prototype.slice.call(arguments, [0]); + const args = Array.prototype.slice.call(arguments, [0]); node.cleanupBeforeAfter(); nodeComplete(node, node.getResult(), function() { done.apply(undefined, args); @@ -240,10 +240,10 @@ getJasmineRequireObj().TreeProcessor = function() { } function wrapChildren(node, segmentNumber) { - var result = [], + const result = [], segmentChildren = stats[node.id].segments[segmentNumber].nodes; - for (var i = 0; i < segmentChildren.length; i++) { + for (let i = 0; i < segmentChildren.length; i++) { result.push( executeNode(segmentChildren[i].owner, segmentChildren[i].index) ); diff --git a/src/core/UserContext.js b/src/core/UserContext.js index 83e253fa..d9b60b0a 100644 --- a/src/core/UserContext.js +++ b/src/core/UserContext.js @@ -2,9 +2,9 @@ getJasmineRequireObj().UserContext = function(j$) { function UserContext() {} UserContext.fromExisting = function(oldContext) { - var context = new UserContext(); + const context = new UserContext(); - for (var prop in oldContext) { + for (const prop in oldContext) { if (oldContext.hasOwnProperty(prop)) { context[prop] = oldContext[prop]; } diff --git a/src/core/asymmetric_equality/ArrayContaining.js b/src/core/asymmetric_equality/ArrayContaining.js index 6f8765aa..3eddacde 100644 --- a/src/core/asymmetric_equality/ArrayContaining.js +++ b/src/core/asymmetric_equality/ArrayContaining.js @@ -19,8 +19,7 @@ getJasmineRequireObj().ArrayContaining = function(j$) { return false; } - for (var i = 0; i < this.sample.length; i++) { - var item = this.sample[i]; + for (const item of this.sample) { if (!matchersUtil.contains(other, item)) { return false; } diff --git a/src/core/asymmetric_equality/ArrayWithExactContents.js b/src/core/asymmetric_equality/ArrayWithExactContents.js index fe3043b0..ad241c1d 100644 --- a/src/core/asymmetric_equality/ArrayWithExactContents.js +++ b/src/core/asymmetric_equality/ArrayWithExactContents.js @@ -19,8 +19,7 @@ getJasmineRequireObj().ArrayWithExactContents = function(j$) { return false; } - for (var i = 0; i < this.sample.length; i++) { - var item = this.sample[i]; + for (const item of this.sample) { if (!matchersUtil.contains(other, item)) { return false; } diff --git a/src/core/asymmetric_equality/MapContaining.js b/src/core/asymmetric_equality/MapContaining.js index 9e0ee422..ef65dbe8 100644 --- a/src/core/asymmetric_equality/MapContaining.js +++ b/src/core/asymmetric_equality/MapContaining.js @@ -16,7 +16,7 @@ getJasmineRequireObj().MapContaining = function(j$) { for (const [key, value] of this.sample) { // for each key/value pair in `sample` // there should be at least one pair in `other` whose key and value both match - var hasMatch = false; + let hasMatch = false; for (const [oKey, oValue] of other) { if ( matchersUtil.equals(oKey, key) && diff --git a/src/core/asymmetric_equality/ObjectContaining.js b/src/core/asymmetric_equality/ObjectContaining.js index 249716c7..04a86694 100644 --- a/src/core/asymmetric_equality/ObjectContaining.js +++ b/src/core/asymmetric_equality/ObjectContaining.js @@ -27,7 +27,7 @@ getJasmineRequireObj().ObjectContaining = function(j$) { return false; } - for (var property in this.sample) { + for (const property in this.sample) { if ( !hasProperty(other, property) || !matchersUtil.equals(this.sample[property], other[property]) @@ -47,7 +47,7 @@ getJasmineRequireObj().ObjectContaining = function(j$) { }; } - var filteredOther = {}; + const filteredOther = {}; Object.keys(this.sample).forEach(function(k) { // eq short-circuits comparison of objects that have different key sets, // so include all keys even if undefined. diff --git a/src/core/asymmetric_equality/SetContaining.js b/src/core/asymmetric_equality/SetContaining.js index 46c0e88c..483c9477 100644 --- a/src/core/asymmetric_equality/SetContaining.js +++ b/src/core/asymmetric_equality/SetContaining.js @@ -17,7 +17,7 @@ getJasmineRequireObj().SetContaining = function(j$) { // for each item in `sample` there should be at least one matching item in `other` // (not using `matchersUtil.contains` because it compares set members by reference, // not by deep value equality) - var hasMatch = false; + let hasMatch = false; for (const oItem of other) { if (matchersUtil.equals(oItem, item)) { hasMatch = true; diff --git a/src/core/base.js b/src/core/base.js index b04499a2..3e69f75f 100644 --- a/src/core/base.js +++ b/src/core/base.js @@ -43,7 +43,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @default 5000 * @since 1.3.0 */ - var DEFAULT_TIMEOUT_INTERVAL = 5000; + let DEFAULT_TIMEOUT_INTERVAL = 5000; Object.defineProperty(j$, 'DEFAULT_TIMEOUT_INTERVAL', { get: function() { return DEFAULT_TIMEOUT_INTERVAL; @@ -67,7 +67,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { * @return {Env} */ j$.getEnv = function(options) { - var env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); + const env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); //jasmine. singletons in here (setTimeout blah blah). return env; }; @@ -208,7 +208,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return func.name; } - var matches = + const matches = func.toString().match(/^\s*function\s*(\w+)\s*\(/) || func.toString().match(/^\s*\[object\s*(\w+)Constructor\]/); @@ -216,7 +216,7 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { }; j$.isPending_ = function(promise) { - var sentinel = {}; + const sentinel = {}; return Promise.race([promise, Promise.resolve(sentinel)]).then( function(result) { return result === sentinel; diff --git a/src/core/formatErrorMsg.js b/src/core/formatErrorMsg.js index cedd656c..8e7f1f03 100644 --- a/src/core/formatErrorMsg.js +++ b/src/core/formatErrorMsg.js @@ -1,6 +1,6 @@ getJasmineRequireObj().formatErrorMsg = function() { function generateErrorMsg(domain, usage) { - var usageDefinition = usage ? '\nUsage: ' + usage : ''; + const usageDefinition = usage ? '\nUsage: ' + usage : ''; return function errorMsg(msg) { return domain + ' : ' + msg + usageDefinition; diff --git a/src/core/matchers/async/toBePending.js b/src/core/matchers/async/toBePending.js index d6703d7b..815bb74f 100644 --- a/src/core/matchers/async/toBePending.js +++ b/src/core/matchers/async/toBePending.js @@ -14,7 +14,7 @@ getJasmineRequireObj().toBePending = function(j$) { if (!j$.isPromiseLike(actual)) { throw new Error('Expected toBePending to be called on a promise.'); } - var want = {}; + const want = {}; return Promise.race([actual, Promise.resolve(want)]).then( function(got) { return { pass: want === got }; diff --git a/src/core/matchers/async/toBeRejectedWithError.js b/src/core/matchers/async/toBeRejectedWithError.js index 5b2aed52..4a843d2f 100644 --- a/src/core/matchers/async/toBeRejectedWithError.js +++ b/src/core/matchers/async/toBeRejectedWithError.js @@ -23,7 +23,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) { ); } - var expected = getExpectedFromArgs(arg1, arg2, matchersUtil); + const expected = getExpectedFromArgs(arg1, arg2, matchersUtil); return actualPromise.then( function() { @@ -52,7 +52,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) { ); } - var actualMessage = actual.message; + const actualMessage = actual.message; if ( actualMessage === expected.message || @@ -94,7 +94,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) { } function getExpectedFromArgs(arg1, arg2, matchersUtil) { - var error, message; + let error, message; if (isErrorConstructor(arg1)) { error = arg1; diff --git a/src/core/matchers/matchersUtil.js b/src/core/matchers/matchersUtil.js index 2cfde95e..5d552170 100644 --- a/src/core/matchers/matchersUtil.js +++ b/src/core/matchers/matchersUtil.js @@ -63,7 +63,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { if (j$.isNumber_(haystack.length)) { // Objects that are shaped like arrays but aren't iterable - for (var i = 0; i < haystack.length; i++) { + for (let i = 0; i < haystack.length; i++) { if (this.equals(haystack[i], needle)) { return true; } @@ -74,8 +74,8 @@ getJasmineRequireObj().MatchersUtil = function(j$) { }; MatchersUtil.prototype.buildFailureMessage = function() { - var self = this; - var args = Array.prototype.slice.call(arguments, 0), + const self = this; + const args = Array.prototype.slice.call(arguments, 0), matcherName = args[0], isNot = args[1], actual = args[2], @@ -84,14 +84,14 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return ' ' + s.toLowerCase(); }); - var message = + let message = 'Expected ' + self.pp(actual) + (isNot ? ' not ' : ' ') + englishyPredicate; if (expected.length > 0) { - for (var i = 0; i < expected.length; i++) { + for (let i = 0; i < expected.length; i++) { if (i > 0) { message += ','; } @@ -110,7 +110,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { diffBuilder ) { if (j$.isFunction_(b.valuesForDiff_)) { - var values = b.valuesForDiff_(a, this.pp); + const values = b.valuesForDiff_(a, this.pp); this.eq_(values.other, values.self, aStack, bStack, diffBuilder); } else { diffBuilder.recordMismatch(); @@ -124,14 +124,15 @@ getJasmineRequireObj().MatchersUtil = function(j$) { bStack, diffBuilder ) { - var asymmetricA = j$.isAsymmetricEqualityTester_(a), - asymmetricB = j$.isAsymmetricEqualityTester_(b), - result; + const asymmetricA = j$.isAsymmetricEqualityTester_(a); + const asymmetricB = j$.isAsymmetricEqualityTester_(b); if (asymmetricA === asymmetricB) { return undefined; } + let result; + if (asymmetricA) { result = a.asymmetricMatch(b, this); if (!result) { @@ -168,11 +169,10 @@ getJasmineRequireObj().MatchersUtil = function(j$) { // Equality function lovingly adapted from isEqual in // [Underscore](http://underscorejs.org) MatchersUtil.prototype.eq_ = function(a, b, aStack, bStack, diffBuilder) { - var result = true, - self = this, - i; + let result = true; + const self = this; - var asymmetricResult = this.asymmetricMatch_( + const asymmetricResult = this.asymmetricMatch_( a, b, aStack, @@ -183,8 +183,8 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return asymmetricResult; } - for (i = 0; i < this.customTesters_.length; i++) { - var customTesterResult = this.customTesters_[i](a, b); + for (const tester of this.customTesters_) { + const customTesterResult = tester(a, b); if (!j$.util.isUndefined(customTesterResult)) { if (!customTesterResult) { diffBuilder.recordMismatch(); @@ -218,7 +218,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } return result; } - var className = Object.prototype.toString.call(a); + const className = Object.prototype.toString.call(a); if (className != Object.prototype.toString.call(b)) { diffBuilder.recordMismatch(); return false; @@ -276,8 +276,8 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - var aIsDomNode = j$.isDomNode(a); - var bIsDomNode = j$.isDomNode(b); + const aIsDomNode = j$.isDomNode(a); + const bIsDomNode = j$.isDomNode(b); if (aIsDomNode && bIsDomNode) { // At first try to use DOM3 method isEqualNode result = a.isEqualNode(b); @@ -291,15 +291,15 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - var aIsPromise = j$.isPromise(a); - var bIsPromise = j$.isPromise(b); + const aIsPromise = j$.isPromise(a); + const bIsPromise = j$.isPromise(b); if (aIsPromise && bIsPromise) { return a === b; } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - var length = aStack.length; + let length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. @@ -310,12 +310,12 @@ getJasmineRequireObj().MatchersUtil = function(j$) { // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); - var size = 0; + let size = 0; // Recursively compare objects and arrays. // Compare array lengths to determine if a deep comparison is necessary. if (className == '[object Array]') { - var aLength = a.length; - var bLength = b.length; + const aLength = a.length; + const bLength = b.length; diffBuilder.withPath('length', function() { if (aLength !== bLength) { @@ -324,7 +324,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } }); - for (i = 0; i < aLength || i < bLength; i++) { + for (let i = 0; i < aLength || i < bLength; i++) { diffBuilder.withPath(i, function() { if (i >= bLength) { diffBuilder.recordMismatch( @@ -352,8 +352,8 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - var keysA = []; - var keysB = []; + const keysA = []; + const keysB = []; a.forEach(function(valueA, keyA) { keysA.push(keyA); }); @@ -363,18 +363,17 @@ getJasmineRequireObj().MatchersUtil = function(j$) { // For both sets of keys, check they map to equal values in both maps. // Keep track of corresponding keys (in insertion order) in order to handle asymmetric obj keys. - var mapKeys = [keysA, keysB]; - var cmpKeys = [keysB, keysA]; - var mapIter, mapKey, mapValueA, mapValueB; - var cmpIter, cmpKey; - for (i = 0; result && i < mapKeys.length; i++) { - mapIter = mapKeys[i]; - cmpIter = cmpKeys[i]; + const mapKeys = [keysA, keysB]; + const cmpKeys = [keysB, keysA]; + for (let i = 0; result && i < mapKeys.length; i++) { + const mapIter = mapKeys[i]; + const cmpIter = cmpKeys[i]; - for (var j = 0; result && j < mapIter.length; j++) { - mapKey = mapIter[j]; - cmpKey = cmpIter[j]; - mapValueA = a.get(mapKey); + for (let j = 0; result && j < mapIter.length; j++) { + const mapKey = mapIter[j]; + const cmpKey = cmpIter[j]; + const mapValueA = a.get(mapKey); + let mapValueB; // Only use the cmpKey when one of the keys is asymmetric and the corresponding key matches, // otherwise explicitly look up the mapKey in the other Map since we want keys with unique @@ -408,35 +407,30 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - var valuesA = []; + const valuesA = []; a.forEach(function(valueA) { valuesA.push(valueA); }); - var valuesB = []; + const valuesB = []; b.forEach(function(valueB) { valuesB.push(valueB); }); // For both sets, check they are all contained in the other set - var setPairs = [[valuesA, valuesB], [valuesB, valuesA]]; - var stackPairs = [[aStack, bStack], [bStack, aStack]]; - var baseValues, baseValue, baseStack; - var otherValues, otherValue, otherStack; - var found; - var prevStackSize; - for (i = 0; result && i < setPairs.length; i++) { - baseValues = setPairs[i][0]; - otherValues = setPairs[i][1]; - baseStack = stackPairs[i][0]; - otherStack = stackPairs[i][1]; + const setPairs = [[valuesA, valuesB], [valuesB, valuesA]]; + const stackPairs = [[aStack, bStack], [bStack, aStack]]; + for (let i = 0; result && i < setPairs.length; i++) { + const baseValues = setPairs[i][0]; + const otherValues = setPairs[i][1]; + const baseStack = stackPairs[i][0]; + const otherStack = stackPairs[i][1]; // For each value in the base set... - for (var k = 0; result && k < baseValues.length; k++) { - baseValue = baseValues[k]; - found = false; + for (const baseValue of baseValues) { + let found = false; // ... test that it is present in the other set - for (var l = 0; !found && l < otherValues.length; l++) { - otherValue = otherValues[l]; - prevStackSize = baseStack.length; + for (let j = 0; !found && j < otherValues.length; j++) { + const otherValue = otherValues[j]; + const prevStackSize = baseStack.length; // compare by value equality found = this.eq_( baseValue, @@ -465,7 +459,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } else { // Objects with different constructors are not equivalent, but `Object`s // or `Array`s from different frames are. - var aCtor = a.constructor, + const aCtor = a.constructor, bCtor = b.constructor; if ( aCtor !== bCtor && @@ -483,8 +477,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } // Deep compare objects. - var aKeys = MatchersUtil.keys(a, className == '[object Array]'), - key; + const aKeys = MatchersUtil.keys(a, className == '[object Array]'); size = aKeys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. @@ -495,8 +488,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return false; } - for (i = 0; i < size; i++) { - key = aKeys[i]; + for (const key of aKeys) { // Deep compare each member if (!j$.util.has(b, key)) { diffBuilder.recordMismatch( @@ -525,18 +517,18 @@ getJasmineRequireObj().MatchersUtil = function(j$) { }; MatchersUtil.keys = function(obj, isArray) { - var allKeys = (function(o) { - var keys = []; - for (var key in o) { + const allKeys = (function(o) { + const keys = []; + for (const key in o) { if (j$.util.has(o, key)) { keys.push(key); } } - var symbols = Object.getOwnPropertySymbols(o); - for (var i = 0; i < symbols.length; i++) { - if (o.propertyIsEnumerable(symbols[i])) { - keys.push(symbols[i]); + const symbols = Object.getOwnPropertySymbols(o); + for (const sym of symbols) { + if (o.propertyIsEnumerable(sym)) { + keys.push(sym); } } @@ -551,10 +543,10 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return allKeys; } - var extraKeys = []; - for (var i = 0; i < allKeys.length; i++) { - if (typeof allKeys[i] === 'symbol' || !/^[0-9]+$/.test(allKeys[i])) { - extraKeys.push(allKeys[i]); + const extraKeys = []; + for (const k of allKeys) { + if (typeof k === 'symbol' || !/^[0-9]+$/.test(k)) { + extraKeys.push(k); } } @@ -574,7 +566,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } function objectKeysAreDifferentFormatter(pp, actual, expected, path) { - var missingProperties = extraKeysAndValues(expected, actual), + const missingProperties = extraKeysAndValues(expected, actual), extraProperties = extraKeysAndValues(actual, expected), missingPropertiesMessage = formatKeyValuePairs(pp, missingProperties), extraPropertiesMessage = formatKeyValuePairs(pp, extraProperties), diff --git a/src/core/matchers/requireAsyncMatchers.js b/src/core/matchers/requireAsyncMatchers.js index abe9b8ef..cb8cf5b2 100644 --- a/src/core/matchers/requireAsyncMatchers.js +++ b/src/core/matchers/requireAsyncMatchers.js @@ -1,5 +1,5 @@ getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) { - var availableMatchers = [ + const availableMatchers = [ 'toBePending', 'toBeResolved', 'toBeRejected', @@ -9,8 +9,7 @@ getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) { ], matchers = {}; - for (var i = 0; i < availableMatchers.length; i++) { - var name = availableMatchers[i]; + for (const name of availableMatchers) { matchers[name] = jRequire[name](j$); } diff --git a/src/core/matchers/requireMatchers.js b/src/core/matchers/requireMatchers.js index 3c9d6983..b15435c4 100755 --- a/src/core/matchers/requireMatchers.js +++ b/src/core/matchers/requireMatchers.js @@ -1,5 +1,5 @@ getJasmineRequireObj().requireMatchers = function(jRequire, j$) { - var availableMatchers = [ + const availableMatchers = [ 'nothing', 'toBe', 'toBeCloseTo', @@ -35,8 +35,7 @@ getJasmineRequireObj().requireMatchers = function(jRequire, j$) { ], matchers = {}; - for (var i = 0; i < availableMatchers.length; i++) { - var name = availableMatchers[i]; + for (const name of availableMatchers) { matchers[name] = jRequire[name](j$); } diff --git a/src/core/matchers/toBe.js b/src/core/matchers/toBe.js index 81177c28..8b795380 100644 --- a/src/core/matchers/toBe.js +++ b/src/core/matchers/toBe.js @@ -9,12 +9,12 @@ getJasmineRequireObj().toBe = function(j$) { * expect(thing).toBe(realThing); */ function toBe(matchersUtil) { - var tip = + const tip = ' Tip: To check for deep equality, use .toEqual() instead of .toBe().'; return { compare: function(actual, expected) { - var result = { + const result = { pass: actual === expected }; diff --git a/src/core/matchers/toBeCloseTo.js b/src/core/matchers/toBeCloseTo.js index a4345ad0..edab5522 100644 --- a/src/core/matchers/toBeCloseTo.js +++ b/src/core/matchers/toBeCloseTo.js @@ -35,9 +35,9 @@ getJasmineRequireObj().toBeCloseTo = function() { }; } - var pow = Math.pow(10, precision + 1); - var delta = Math.abs(expected - actual); - var maxDelta = Math.pow(10, -precision) / 2; + const pow = Math.pow(10, precision + 1); + const delta = Math.abs(expected - actual); + const maxDelta = Math.pow(10, -precision) / 2; return { pass: Math.round(delta * pow) <= maxDelta * pow diff --git a/src/core/matchers/toBeInstanceOf.js b/src/core/matchers/toBeInstanceOf.js index 2241402e..5e0156ee 100644 --- a/src/core/matchers/toBeInstanceOf.js +++ b/src/core/matchers/toBeInstanceOf.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toBeInstanceOf = function(j$) { - var usageError = j$.formatErrorMsg( + const usageError = j$.formatErrorMsg( '', 'expect(value).toBeInstanceOf()' ); @@ -18,15 +18,15 @@ getJasmineRequireObj().toBeInstanceOf = function(j$) { function toBeInstanceOf(matchersUtil) { return { compare: function(actual, expected) { - var actualType = - actual && actual.constructor - ? j$.fnNameFor(actual.constructor) - : matchersUtil.pp(actual), - expectedType = expected - ? j$.fnNameFor(expected) - : matchersUtil.pp(expected), - expectedMatcher, - pass; + const actualType = + actual && actual.constructor + ? j$.fnNameFor(actual.constructor) + : matchersUtil.pp(actual); + const expectedType = expected + ? j$.fnNameFor(expected) + : matchersUtil.pp(expected); + let expectedMatcher; + let pass; try { expectedMatcher = new j$.Any(expected); diff --git a/src/core/matchers/toBeNaN.js b/src/core/matchers/toBeNaN.js index b26ef5fc..b17a5b5e 100644 --- a/src/core/matchers/toBeNaN.js +++ b/src/core/matchers/toBeNaN.js @@ -10,7 +10,7 @@ getJasmineRequireObj().toBeNaN = function(j$) { function toBeNaN(matchersUtil) { return { compare: function(actual) { - var result = { + const result = { pass: actual !== actual }; diff --git a/src/core/matchers/toBeNegativeInfinity.js b/src/core/matchers/toBeNegativeInfinity.js index 2518a9c8..36caee9a 100644 --- a/src/core/matchers/toBeNegativeInfinity.js +++ b/src/core/matchers/toBeNegativeInfinity.js @@ -10,7 +10,7 @@ getJasmineRequireObj().toBeNegativeInfinity = function(j$) { function toBeNegativeInfinity(matchersUtil) { return { compare: function(actual) { - var result = { + const result = { pass: actual === Number.NEGATIVE_INFINITY }; diff --git a/src/core/matchers/toBePositiveInfinity.js b/src/core/matchers/toBePositiveInfinity.js index 17523c97..d4541a37 100644 --- a/src/core/matchers/toBePositiveInfinity.js +++ b/src/core/matchers/toBePositiveInfinity.js @@ -10,7 +10,7 @@ getJasmineRequireObj().toBePositiveInfinity = function(j$) { function toBePositiveInfinity(matchersUtil) { return { compare: function(actual) { - var result = { + const result = { pass: actual === Number.POSITIVE_INFINITY }; diff --git a/src/core/matchers/toEqual.js b/src/core/matchers/toEqual.js index 9946d9ae..04a67bda 100644 --- a/src/core/matchers/toEqual.js +++ b/src/core/matchers/toEqual.js @@ -11,7 +11,7 @@ getJasmineRequireObj().toEqual = function(j$) { function toEqual(matchersUtil) { return { compare: function(actual, expected) { - var result = { + const result = { pass: false }, diffBuilder = new j$.DiffBuilder({ prettyPrinter: matchersUtil.pp }); diff --git a/src/core/matchers/toHaveBeenCalled.js b/src/core/matchers/toHaveBeenCalled.js index ef1ea60c..f4fd131a 100644 --- a/src/core/matchers/toHaveBeenCalled.js +++ b/src/core/matchers/toHaveBeenCalled.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toHaveBeenCalled = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalled()' ); @@ -16,7 +16,7 @@ getJasmineRequireObj().toHaveBeenCalled = function(j$) { function toHaveBeenCalled(matchersUtil) { return { compare: function(actual) { - var result = {}; + const result = {}; if (!j$.isSpy(actual)) { throw new Error( diff --git a/src/core/matchers/toHaveBeenCalledBefore.js b/src/core/matchers/toHaveBeenCalledBefore.js index ad1de7c0..3f352d21 100644 --- a/src/core/matchers/toHaveBeenCalledBefore.js +++ b/src/core/matchers/toHaveBeenCalledBefore.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalledBefore()' ); @@ -31,7 +31,7 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { ); } - var result = { pass: false }; + const result = { pass: false }; if (!firstSpy.calls.count()) { result.message = @@ -44,8 +44,8 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { return result; } - var latest1stSpyCall = firstSpy.calls.mostRecent().invocationOrder; - var first2ndSpyCall = latterSpy.calls.first().invocationOrder; + const latest1stSpyCall = firstSpy.calls.mostRecent().invocationOrder; + const first2ndSpyCall = latterSpy.calls.first().invocationOrder; result.pass = latest1stSpyCall < first2ndSpyCall; @@ -57,8 +57,8 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { latterSpy.and.identity + ', but it was'; } else { - var first1stSpyCall = firstSpy.calls.first().invocationOrder; - var latest2ndSpyCall = latterSpy.calls.mostRecent().invocationOrder; + const first1stSpyCall = firstSpy.calls.first().invocationOrder; + const latest2ndSpyCall = latterSpy.calls.mostRecent().invocationOrder; if (first1stSpyCall < first2ndSpyCall) { result.message = diff --git a/src/core/matchers/toHaveBeenCalledOnceWith.js b/src/core/matchers/toHaveBeenCalledOnceWith.js index d3d6b4ef..1d36f615 100644 --- a/src/core/matchers/toHaveBeenCalledOnceWith.js +++ b/src/core/matchers/toHaveBeenCalledOnceWith.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalledOnceWith(...arguments)' ); @@ -16,7 +16,7 @@ getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { function toHaveBeenCalledOnceWith(util) { return { compare: function() { - var args = Array.prototype.slice.call(arguments, 0), + const args = Array.prototype.slice.call(arguments, 0), actual = args[0], expectedArgs = args.slice(1); @@ -26,7 +26,7 @@ getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { ); } - var prettyPrintedCalls = actual.calls + const prettyPrintedCalls = actual.calls .allArgs() .map(function(argsForCall) { return ' ' + util.pp(argsForCall); @@ -53,7 +53,7 @@ getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { function getDiffs() { return actual.calls.allArgs().map(function(argsForCall, callIx) { - var diffBuilder = new j$.DiffBuilder(); + const diffBuilder = new j$.DiffBuilder(); util.equals(argsForCall, expectedArgs, diffBuilder); return diffBuilder.getMessage(); }); diff --git a/src/core/matchers/toHaveBeenCalledTimes.js b/src/core/matchers/toHaveBeenCalledTimes.js index f3bcac3f..78054af8 100644 --- a/src/core/matchers/toHaveBeenCalledTimes.js +++ b/src/core/matchers/toHaveBeenCalledTimes.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalledTimes()' ); @@ -24,7 +24,7 @@ getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { ); } - var args = Array.prototype.slice.call(arguments, 0), + const args = Array.prototype.slice.call(arguments, 0), result = { pass: false }; if (!j$.isNumber_(expected)) { @@ -36,8 +36,8 @@ getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { } actual = args[0]; - var calls = actual.calls.count(); - var timesMessage = expected === 1 ? 'once' : expected + ' times'; + const calls = actual.calls.count(); + const timesMessage = expected === 1 ? 'once' : expected + ' times'; result.pass = calls === expected; result.message = result.pass ? 'Expected spy ' + diff --git a/src/core/matchers/toHaveBeenCalledWith.js b/src/core/matchers/toHaveBeenCalledWith.js index 0a646b89..2fa26d3c 100644 --- a/src/core/matchers/toHaveBeenCalledWith.js +++ b/src/core/matchers/toHaveBeenCalledWith.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveBeenCalledWith(...arguments)' ); @@ -16,7 +16,7 @@ getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { function toHaveBeenCalledWith(matchersUtil) { return { compare: function() { - var args = Array.prototype.slice.call(arguments, 0), + const args = Array.prototype.slice.call(arguments, 0), actual = args[0], expectedArgs = args.slice(1), result = { pass: false }; @@ -57,16 +57,16 @@ getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { }; } else { result.message = function() { - var prettyPrintedCalls = actual.calls + const prettyPrintedCalls = actual.calls .allArgs() .map(function(argsForCall) { return ' ' + matchersUtil.pp(argsForCall); }); - var diffs = actual.calls + const diffs = actual.calls .allArgs() .map(function(argsForCall, callIx) { - var diffBuilder = new j$.DiffBuilder(); + const diffBuilder = new j$.DiffBuilder(); matchersUtil.equals(argsForCall, expectedArgs, diffBuilder); return ( 'Call ' + diff --git a/src/core/matchers/toHaveSize.js b/src/core/matchers/toHaveSize.js index 87b75af7..05234cca 100644 --- a/src/core/matchers/toHaveSize.js +++ b/src/core/matchers/toHaveSize.js @@ -12,7 +12,7 @@ getJasmineRequireObj().toHaveSize = function(j$) { function toHaveSize() { return { compare: function(actual, expected) { - var result = { + const result = { pass: false }; @@ -37,7 +37,7 @@ getJasmineRequireObj().toHaveSize = function(j$) { }; } - var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; function isLength(value) { return ( typeof value == 'number' && diff --git a/src/core/matchers/toHaveSpyInteractions.js b/src/core/matchers/toHaveSpyInteractions.js index da8a4d0e..0436a098 100755 --- a/src/core/matchers/toHaveSpyInteractions.js +++ b/src/core/matchers/toHaveSpyInteractions.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toHaveSpyInteractions = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toHaveSpyInteractions()' ); @@ -16,7 +16,7 @@ getJasmineRequireObj().toHaveSpyInteractions = function(j$) { function toHaveSpyInteractions(matchersUtil) { return { compare: function(actual) { - var result = {}; + const result = {}; if (!j$.isObject_(actual)) { throw new Error( diff --git a/src/core/matchers/toMatch.js b/src/core/matchers/toMatch.js index bb3ca3a9..571304c9 100644 --- a/src/core/matchers/toMatch.js +++ b/src/core/matchers/toMatch.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toMatch = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect().toMatch( || )' ); @@ -21,7 +21,7 @@ getJasmineRequireObj().toMatch = function(j$) { throw new Error(getErrorMsg('Expected is not a String or a RegExp')); } - var regexp = new RegExp(expected); + const regexp = new RegExp(expected); return { pass: regexp.test(actual) diff --git a/src/core/matchers/toThrow.js b/src/core/matchers/toThrow.js index b1db2b4c..9f8e2240 100644 --- a/src/core/matchers/toThrow.js +++ b/src/core/matchers/toThrow.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toThrow = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect(function() {}).toThrow()' ); @@ -17,9 +17,9 @@ getJasmineRequireObj().toThrow = function(j$) { function toThrow(matchersUtil) { return { compare: function(actual, expected) { - var result = { pass: false }, - threw = false, - thrown; + const result = { pass: false }; + let threw = false; + let thrown; if (typeof actual != 'function') { throw new Error(getErrorMsg('Actual is not a Function')); diff --git a/src/core/matchers/toThrowError.js b/src/core/matchers/toThrowError.js index 38513603..4ddd78b3 100644 --- a/src/core/matchers/toThrowError.js +++ b/src/core/matchers/toThrowError.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toThrowError = function(j$) { - var getErrorMsg = j$.formatErrorMsg( + const getErrorMsg = j$.formatErrorMsg( '', 'expect(function() {}).toThrowError(, )' ); @@ -21,13 +21,14 @@ getJasmineRequireObj().toThrowError = function(j$) { function toThrowError(matchersUtil) { return { compare: function(actual) { - var errorMatcher = getMatcher.apply(null, arguments), - thrown; + const errorMatcher = getMatcher.apply(null, arguments); if (typeof actual != 'function') { throw new Error(getErrorMsg('Actual is not a Function')); } + let thrown; + try { actual(); return fail('Expected function to throw an Error.'); @@ -50,7 +51,7 @@ getJasmineRequireObj().toThrowError = function(j$) { }; function getMatcher() { - var expected, errorType; + let expected, errorType; if (arguments[2]) { errorType = arguments[1]; @@ -106,15 +107,15 @@ getJasmineRequireObj().toThrowError = function(j$) { } } - var errorTypeDescription = errorType + const errorTypeDescription = errorType ? j$.fnNameFor(errorType) : 'an exception'; function thrownDescription(thrown) { - var thrownName = errorType - ? j$.fnNameFor(thrown.constructor) - : 'an exception', - thrownMessage = ''; + const thrownName = errorType + ? j$.fnNameFor(thrown.constructor) + : 'an exception'; + let thrownMessage = ''; if (expected) { thrownMessage = ' with message ' + matchersUtil.pp(thrown.message); @@ -176,7 +177,7 @@ getJasmineRequireObj().toThrowError = function(j$) { return false; } - var Surrogate = function() {}; + const Surrogate = function() {}; Surrogate.prototype = type.prototype; return j$.isError_(new Surrogate()); } diff --git a/src/core/matchers/toThrowMatching.js b/src/core/matchers/toThrowMatching.js index e594b1f5..4e9ea406 100644 --- a/src/core/matchers/toThrowMatching.js +++ b/src/core/matchers/toThrowMatching.js @@ -1,5 +1,5 @@ getJasmineRequireObj().toThrowMatching = function(j$) { - var usageError = j$.formatErrorMsg( + const usageError = j$.formatErrorMsg( '', 'expect(function() {}).toThrowMatching()' ); @@ -16,8 +16,6 @@ getJasmineRequireObj().toThrowMatching = function(j$) { function toThrowMatching(matchersUtil) { return { compare: function(actual, predicate) { - var thrown; - if (typeof actual !== 'function') { throw new Error(usageError('Actual is not a Function')); } @@ -26,6 +24,8 @@ getJasmineRequireObj().toThrowMatching = function(j$) { throw new Error(usageError('Predicate is not a Function')); } + let thrown; + try { actual(); return fail('Expected function to throw an exception.'); diff --git a/src/core/requireCore.js b/src/core/requireCore.js index 2568134f..da49dc83 100644 --- a/src/core/requireCore.js +++ b/src/core/requireCore.js @@ -1,6 +1,6 @@ -// eslint-disable-next-line no-unused-vars +// eslint-disable-next-line no-unused-vars,no-var var getJasmineRequireObj = (function(jasmineGlobal) { - var jasmineRequire; + let jasmineRequire; if ( typeof module !== 'undefined' && @@ -29,7 +29,7 @@ var getJasmineRequireObj = (function(jasmineGlobal) { } getJasmineRequire().core = function(jRequire) { - var j$ = {}; + const j$ = {}; jRequire.base(j$, jasmineGlobal); j$.util = jRequire.util(j$); diff --git a/src/core/requireInterface.js b/src/core/requireInterface.js index 71f7d276..1c7d4d00 100644 --- a/src/core/requireInterface.js +++ b/src/core/requireInterface.js @@ -1,5 +1,5 @@ getJasmineRequireObj().interface = function(jasmine, env) { - var jasmineInterface = { + const jasmineInterface = { /** * Callback passed to parts of the Jasmine base interface. * diff --git a/src/core/util.js b/src/core/util.js index cd4170d4..5810275b 100644 --- a/src/core/util.js +++ b/src/core/util.js @@ -1,15 +1,15 @@ getJasmineRequireObj().util = function(j$) { - var util = {}; + const util = {}; util.inherit = function(childClass, parentClass) { - var Subclass = function() {}; + const Subclass = function() {}; Subclass.prototype = parentClass.prototype; childClass.prototype = new Subclass(); }; util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) { + const arrayOfArgs = []; + for (let i = 0; i < args.length; i++) { arrayOfArgs.push(args[i]); } return arrayOfArgs; @@ -20,7 +20,7 @@ getJasmineRequireObj().util = function(j$) { }; util.arrayContains = function(array, search) { - var i = array.length; + let i = array.length; while (i--) { if (array[i] === search) { return true; @@ -34,8 +34,8 @@ getJasmineRequireObj().util = function(j$) { return obj.slice(); } - var cloned = {}; - for (var prop in obj) { + const cloned = {}; + for (const prop in obj) { if (obj.hasOwnProperty(prop)) { cloned[prop] = obj[prop]; } @@ -45,10 +45,10 @@ getJasmineRequireObj().util = function(j$) { }; util.cloneArgs = function(args) { - var clonedArgs = []; - var argsAsArray = j$.util.argsToArray(args); - for (var i = 0; i < argsAsArray.length; i++) { - var str = Object.prototype.toString.apply(argsAsArray[i]), + const clonedArgs = []; + const argsAsArray = j$.util.argsToArray(args); + for (let i = 0; i < argsAsArray.length; i++) { + const str = Object.prototype.toString.apply(argsAsArray[i]), primitives = /^\[object (Boolean|String|RegExp|Number)/; // All falsey values are either primitives, `null`, or `undefined. @@ -64,7 +64,7 @@ getJasmineRequireObj().util = function(j$) { }; util.getPropertyDescriptor = function(obj, methodName) { - var descriptor, + let descriptor, proto = obj; do { @@ -87,12 +87,12 @@ getJasmineRequireObj().util = function(j$) { }; function callerFile() { - var trace = new j$.StackTrace(util.errorWithStack()); + const trace = new j$.StackTrace(util.errorWithStack()); return trace.frames[2].file; } util.jasmineFile = (function() { - var result; + let result; return function() { if (!result) { @@ -113,7 +113,7 @@ getJasmineRequireObj().util = function(j$) { // exceeded. But on all currently supported JS runtimes, setTimeout calls // the callback immediately when the timeout is greater than 2147483647 // (the maximum value of a signed 32 bit integer). - var max = 2147483647; + const max = 2147483647; if (timeout > max) { throw new Error( diff --git a/src/html/HtmlReporter.js b/src/html/HtmlReporter.js index 7f69cb57..d1b99cd7 100644 --- a/src/html/HtmlReporter.js +++ b/src/html/HtmlReporter.js @@ -48,19 +48,21 @@ jasmineRequire.HtmlReporter = function(j$) { }; function HtmlReporter(options) { - 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, - filterSpecs = options.filterSpecs, - htmlReporterMain, - symbols, - deprecationWarnings = []; + function config() { + return (options.env && options.env.configuration()) || {}; + } + + const getContainer = options.getContainer; + const createElement = options.createElement; + const createTextNode = options.createTextNode; + const navigateWithNewParam = options.navigateWithNewParam || function() {}; + const addToExistingQueryString = + options.addToExistingQueryString || defaultQueryString; + const filterSpecs = options.filterSpecs; + let htmlReporterMain; + let symbols; + const deprecationWarnings = []; + const failures = []; this.initialize = function() { clearPrior(); @@ -88,14 +90,14 @@ jasmineRequire.HtmlReporter = function(j$) { getContainer().appendChild(htmlReporterMain); }; - var totalSpecsDefined; + let totalSpecsDefined; this.jasmineStarted = function(options) { totalSpecsDefined = options.totalSpecsDefined || 0; }; - var summary = createDom('div', { className: 'jasmine-summary' }); + const summary = createDom('div', { className: 'jasmine-summary' }); - var stateBuilder = new ResultsStateBuilder(); + const stateBuilder = new ResultsStateBuilder(); this.suiteStarted = function(result) { stateBuilder.suiteStarted(result); @@ -114,12 +116,11 @@ jasmineRequire.HtmlReporter = function(j$) { stateBuilder.specStarted(result); }; - var failures = []; this.specDone = function(result) { stateBuilder.specDone(result); if (noExpectations(result)) { - var noSpecMsg = "Spec '" + result.fullName + "' has no expectations."; + const noSpecMsg = "Spec '" + result.fullName + "' has no expectations."; if (result.status === 'failed') { console.error(noSpecMsg); } else { @@ -163,10 +164,10 @@ jasmineRequire.HtmlReporter = function(j$) { this.jasmineDone = function(doneResult) { stateBuilder.jasmineDone(doneResult); - var banner = find('.jasmine-banner'); - var alert = find('.jasmine-alert'); - var order = doneResult && doneResult.order; - var i; + const banner = find('.jasmine-banner'); + const alert = find('.jasmine-alert'); + const order = doneResult && doneResult.order; + alert.appendChild( createDom( 'span', @@ -178,14 +179,14 @@ jasmineRequire.HtmlReporter = function(j$) { banner.appendChild(optionsMenu(config())); if (stateBuilder.specsExecuted < totalSpecsDefined) { - var skippedMessage = + const skippedMessage = 'Ran ' + stateBuilder.specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all'; // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 - var skippedLink = + const skippedLink = (window.location.pathname || '') + addToExistingQueryString('spec', ''); alert.appendChild( @@ -200,10 +201,11 @@ jasmineRequire.HtmlReporter = function(j$) { ) ); } - var statusBarMessage = ''; - var statusBarClassName = 'jasmine-overall-result jasmine-bar '; - var globalFailures = (doneResult && doneResult.failedExpectations) || []; - var failed = stateBuilder.failureCount + globalFailures.length > 0; + let statusBarMessage = ''; + let statusBarClassName = 'jasmine-overall-result jasmine-bar '; + const globalFailures = + (doneResult && doneResult.failedExpectations) || []; + const failed = stateBuilder.failureCount + globalFailures.length > 0; if (totalSpecsDefined > 0 || failed) { statusBarMessage += @@ -229,7 +231,7 @@ jasmineRequire.HtmlReporter = function(j$) { statusBarClassName += ' jasmine-failed '; } - var seedBar; + let seedBar; if (order && order.random) { seedBar = createDom( 'span', @@ -255,10 +257,10 @@ jasmineRequire.HtmlReporter = function(j$) { ) ); - var errorBarClassName = 'jasmine-bar jasmine-errored'; - var afterAllMessagePrefix = 'AfterAll '; + const errorBarClassName = 'jasmine-bar jasmine-errored'; + const afterAllMessagePrefix = 'AfterAll '; - for (i = 0; i < globalFailures.length; i++) { + for (let i = 0; i < globalFailures.length; i++) { alert.appendChild( createDom( 'span', @@ -270,7 +272,7 @@ jasmineRequire.HtmlReporter = function(j$) { function globalFailureMessage(failure) { if (failure.globalErrorType === 'load') { - var prefix = 'Error during loading: ' + failure.message; + const prefix = 'Error during loading: ' + failure.message; if (failure.filename) { return ( @@ -288,9 +290,9 @@ jasmineRequire.HtmlReporter = function(j$) { addDeprecationWarnings(doneResult); - for (i = 0; i < deprecationWarnings.length; i++) { - var children = [], - context; + for (let i = 0; i < deprecationWarnings.length; i++) { + const children = []; + let context; switch (deprecationWarnings[i].runnableType) { case 'spec': @@ -324,7 +326,7 @@ jasmineRequire.HtmlReporter = function(j$) { ); } - var results = find('.jasmine-results'); + const results = find('.jasmine-results'); results.appendChild(summary); summaryList(stateBuilder.topResults, summary); @@ -366,8 +368,8 @@ jasmineRequire.HtmlReporter = function(j$) { setMenuModeTo('jasmine-failure-list'); - var failureNode = find('.jasmine-failures'); - for (i = 0; i < failures.length; i++) { + const failureNode = find('.jasmine-failures'); + for (let i = 0; i < failures.length; i++) { failureNode.appendChild(failures[i]); } } @@ -376,16 +378,16 @@ jasmineRequire.HtmlReporter = function(j$) { return this; function failureDom(result) { - var failure = createDom( + const failure = createDom( 'div', { className: 'jasmine-spec-detail jasmine-failed' }, failureDescription(result, stateBuilder.currentParent), createDom('div', { className: 'jasmine-messages' }) ); - var messages = failure.childNodes[1]; + const messages = failure.childNodes[1]; - for (var i = 0; i < result.failedExpectations.length; i++) { - var expectation = result.failedExpectations[i]; + for (let i = 0; i < result.failedExpectations.length; i++) { + const expectation = result.failedExpectations[i]; messages.appendChild( createDom( 'div', @@ -420,7 +422,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function debugLogTable(debugLogs) { - var tbody = createDom('tbody'); + const tbody = createDom('tbody'); debugLogs.forEach(function(entry) { tbody.appendChild( @@ -460,14 +462,14 @@ jasmineRequire.HtmlReporter = function(j$) { } function summaryList(resultsTree, domParent) { - var specListNode; - for (var i = 0; i < resultsTree.children.length; i++) { - var resultNode = resultsTree.children[i]; + let specListNode; + for (let i = 0; i < resultsTree.children.length; i++) { + const resultNode = resultsTree.children[i]; if (filterSpecs && !hasActiveSpec(resultNode)) { continue; } if (resultNode.type === 'suite') { - var suiteListNode = createDom( + const suiteListNode = createDom( 'ul', { className: 'jasmine-suite', id: 'suite-' + resultNode.result.id }, createDom( @@ -492,7 +494,7 @@ jasmineRequire.HtmlReporter = function(j$) { specListNode = createDom('ul', { className: 'jasmine-specs' }); domParent.appendChild(specListNode); } - var specDescription = resultNode.result.description; + let specDescription = resultNode.result.description; if (noExpectations(resultNode.result)) { specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; } @@ -524,7 +526,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function optionsMenu(config) { - var optionsMenuDom = createDom( + const optionsMenuDom = createDom( 'div', { className: 'jasmine-run-options' }, createDom('span', { className: 'jasmine-trigger' }, 'Options'), @@ -590,13 +592,15 @@ jasmineRequire.HtmlReporter = function(j$) { ) ); - var failFastCheckbox = optionsMenuDom.querySelector('#jasmine-fail-fast'); + const failFastCheckbox = optionsMenuDom.querySelector( + '#jasmine-fail-fast' + ); failFastCheckbox.checked = config.stopOnSpecFailure; failFastCheckbox.onclick = function() { navigateWithNewParam('stopOnSpecFailure', !config.stopOnSpecFailure); }; - var throwCheckbox = optionsMenuDom.querySelector( + const throwCheckbox = optionsMenuDom.querySelector( '#jasmine-throw-failures' ); throwCheckbox.checked = config.stopSpecOnExpectationFailure; @@ -607,7 +611,7 @@ jasmineRequire.HtmlReporter = function(j$) { ); }; - var randomCheckbox = optionsMenuDom.querySelector( + const randomCheckbox = optionsMenuDom.querySelector( '#jasmine-random-order' ); randomCheckbox.checked = config.random; @@ -615,13 +619,15 @@ jasmineRequire.HtmlReporter = function(j$) { navigateWithNewParam('random', !config.random); }; - var hideDisabled = optionsMenuDom.querySelector('#jasmine-hide-disabled'); + const hideDisabled = optionsMenuDom.querySelector( + '#jasmine-hide-disabled' + ); hideDisabled.checked = config.hideDisabled; hideDisabled.onclick = function() { navigateWithNewParam('hideDisabled', !config.hideDisabled); }; - var optionsTrigger = optionsMenuDom.querySelector('.jasmine-trigger'), + const optionsTrigger = optionsMenuDom.querySelector('.jasmine-trigger'), optionsPayload = optionsMenuDom.querySelector('.jasmine-payload'), isOpen = /\bjasmine-open\b/; @@ -640,7 +646,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function failureDescription(result, suite) { - var wrapper = createDom( + const wrapper = createDom( 'div', { className: 'jasmine-description' }, createDom( @@ -649,7 +655,7 @@ jasmineRequire.HtmlReporter = function(j$) { result.description ) ); - var suiteLink; + let suiteLink; while (suite && suite.parent) { wrapper.insertBefore(createTextNode(' > '), wrapper.firstChild); @@ -667,7 +673,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function suiteHref(suite) { - var els = []; + const els = []; while (suite && suite.parent) { els.unshift(suite.result.description); @@ -683,8 +689,8 @@ jasmineRequire.HtmlReporter = function(j$) { function addDeprecationWarnings(result, runnableType) { if (result && result.deprecationWarnings) { - for (var i = 0; i < result.deprecationWarnings.length; i++) { - var warning = result.deprecationWarnings[i].message; + for (let i = 0; i < result.deprecationWarnings.length; i++) { + const warning = result.deprecationWarnings[i].message; deprecationWarnings.push({ message: warning, stack: result.deprecationWarnings[i].stack, @@ -696,8 +702,8 @@ jasmineRequire.HtmlReporter = function(j$) { } function createExpander(stackTrace) { - var expandLink = createDom('a', { href: '#' }, 'Show stack trace'); - var root = createDom( + const expandLink = createDom('a', { href: '#' }, 'Show stack trace'); + const root = createDom( 'div', { className: 'jasmine-expander' }, expandLink, @@ -728,8 +734,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function clearPrior() { - // return the reporter - var oldReporter = find(''); + const oldReporter = find(''); if (oldReporter) { getContainer().removeChild(oldReporter); @@ -737,22 +742,21 @@ jasmineRequire.HtmlReporter = function(j$) { } function createDom(type, attrs, childrenArrayOrVarArgs) { - var el = createElement(type), - children, - i; + const el = createElement(type); + let children; if (j$.isArray_(childrenArrayOrVarArgs)) { children = childrenArrayOrVarArgs; } else { children = []; - for (i = 2; i < arguments.length; i++) { + for (let i = 2; i < arguments.length; i++) { children.push(arguments[i]); } } - for (i = 0; i < children.length; i++) { - var child = children[i]; + for (let i = 0; i < children.length; i++) { + const child = children[i]; if (typeof child === 'string') { el.appendChild(createTextNode(child)); @@ -763,7 +767,7 @@ jasmineRequire.HtmlReporter = function(j$) { } } - for (var attr in attrs) { + for (const attr in attrs) { if (attr == 'className') { el[attr] = attrs[attr]; } else { @@ -775,7 +779,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function pluralize(singular, count) { - var word = count == 1 ? singular : singular + 's'; + const word = count == 1 ? singular : singular + 's'; return '' + count + ' ' + word; } @@ -805,7 +809,7 @@ jasmineRequire.HtmlReporter = function(j$) { } function noExpectations(result) { - var allExpectations = + const allExpectations = result.failedExpectations.length + result.passedExpectations.length; return ( @@ -820,7 +824,7 @@ jasmineRequire.HtmlReporter = function(j$) { } if (resultNode.type == 'suite') { - for (var i = 0, j = resultNode.children.length; i < j; i++) { + for (let i = 0, j = resultNode.children.length; i < j; i++) { if (hasActiveSpec(resultNode.children[i])) { return true; } diff --git a/src/html/HtmlSpecFilter.js b/src/html/HtmlSpecFilter.js index 7a18f1ec..e5593aae 100644 --- a/src/html/HtmlSpecFilter.js +++ b/src/html/HtmlSpecFilter.js @@ -1,10 +1,10 @@ jasmineRequire.HtmlSpecFilter = function() { function HtmlSpecFilter(options) { - var filterString = + const filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); - var filterPattern = new RegExp(filterString); + const filterPattern = new RegExp(filterString); this.matches = function(specName) { return filterPattern.test(specName); diff --git a/src/html/QueryString.js b/src/html/QueryString.js index c4ce950e..8a1857a3 100644 --- a/src/html/QueryString.js +++ b/src/html/QueryString.js @@ -8,7 +8,7 @@ jasmineRequire.QueryString = function() { }; this.fullStringWithNewParam = function(key, value) { - var paramMap = queryStringToParamMap(); + const paramMap = queryStringToParamMap(); paramMap[key] = value; return toQueryString(paramMap); }; @@ -20,8 +20,8 @@ jasmineRequire.QueryString = function() { return this; function toQueryString(paramMap) { - var qStrPairs = []; - for (var prop in paramMap) { + const qStrPairs = []; + for (const prop in paramMap) { qStrPairs.push( encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]) ); @@ -30,15 +30,15 @@ jasmineRequire.QueryString = function() { } function queryStringToParamMap() { - var paramStr = options.getWindowLocation().search.substring(1), - params = [], - paramMap = {}; + const paramStr = options.getWindowLocation().search.substring(1); + let params = []; + const paramMap = {}; if (paramStr.length > 0) { params = paramStr.split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - var value = decodeURIComponent(p[1]); + for (let i = 0; i < params.length; i++) { + const p = params[i].split('='); + let value = decodeURIComponent(p[1]); if (value === 'true' || value === 'false') { value = JSON.parse(value); } diff --git a/src/html/requireHtml.js b/src/html/requireHtml.js index a8fe2a1e..9df50b08 100644 --- a/src/html/requireHtml.js +++ b/src/html/requireHtml.js @@ -1,3 +1,4 @@ +// eslint-disable-next-line no-var var jasmineRequire = window.jasmineRequire || require('./jasmine.js'); jasmineRequire.html = function(j$) {