diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..cd8fe7f --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,26 @@ +module.exports = { + env: { + browser: true, + es6: true, + node: true + }, + extends: [ + 'standard' + ], + globals: { + Atomics: 'readonly', + SharedArrayBuffer: 'readonly' + }, + parserOptions: { + ecmaFeatures: { + jsx: true + }, + ecmaVersion: 2018, + sourceType: 'module' + }, + plugins: [ + 'react' + ], + rules: { + } +} diff --git a/Gruntfile.js b/Gruntfile.js index 993b787..4b15948 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,30 +1,29 @@ -'use strict'; +'use strict' -var packageJSON = require('./package.json'); +var packageJSON = require('./package.json') module.exports = function (grunt) { + var utils = require('./src/utils')(grunt) + var tunnelId = Math.floor((new Date()).getTime() / 1000 - 1230768000).toString() - var utils = require('./src/utils')(grunt); - var tunnelId = Math.floor((new Date()).getTime() / 1000 - 1230768000).toString(); - - function negateResult(result, callback) { + function negateResult (result, callback) { // Reverses the job's passed status. Can be used as the onTestComplete callback for // the negative tests. - var user = process.env.SAUCE_USERNAME; - var pass = process.env.SAUCE_ACCESS_KEY; + var user = process.env.SAUCE_USERNAME + var pass = process.env.SAUCE_ACCESS_KEY utils - .makeRequest({ - method: 'PUT', - url: ['https://saucelabs.com/rest/v1', user, 'jobs', result.job_id].join('/'), - auth: { user: user, pass: pass }, - json: { passed: !result.passed } - }) - .thenResolve(!result.passed) - .nodeify(callback); + .makeRequest({ + method: 'PUT', + url: ['https://saucelabs.com/rest/v1', user, 'jobs', result.job_id].join('/'), + auth: { user: user, pass: pass }, + json: { passed: !result.passed } + }) + .thenResolve(!result.passed) + .nodeify(callback) } - grunt.task.loadTasks('tasks'); + grunt.task.loadTasks('tasks') require('load-grunt-config')(grunt, { data: { @@ -32,8 +31,8 @@ module.exports = function (grunt) { negateResult: negateResult, tunnelId: tunnelId, baseSaucelabsTaskOptions: { - build: process.env.TRAVIS_JOB_ID || 'dev-'+process.env.USER+':'+Date.now(), - tags: ['v'+packageJSON.version, 'grunt-saucelabs'], + build: process.env.TRAVIS_JOB_ID || 'dev-' + process.env.USER + ':' + Date.now(), + tags: ['v' + packageJSON.version, 'grunt-saucelabs'], browsers: [ ['Windows 7', 'chrome', ''] ], @@ -44,5 +43,5 @@ module.exports = function (grunt) { } } } - }); -}; + }) +} diff --git a/examples/custom/Gruntfile.js b/examples/custom/Gruntfile.js index 4b81b0d..bf15bf0 100644 --- a/examples/custom/Gruntfile.js +++ b/examples/custom/Gruntfile.js @@ -17,7 +17,7 @@ module.exports = function (grunt) { browserName: 'internet explorer', platform: 'VISTA', version: '9' - }]; + }] grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), @@ -47,10 +47,10 @@ module.exports = function (grunt) { } }, watch: {} - }); + }) - grunt.loadNpmTasks('grunt-contrib-connect'); - grunt.loadNpmTasks('grunt-saucelabs'); + grunt.loadNpmTasks('grunt-contrib-connect') + grunt.loadNpmTasks('grunt-saucelabs') - grunt.registerTask('default', ['connect', 'saucelabs-custom']); -}; \ No newline at end of file + grunt.registerTask('default', ['connect', 'saucelabs-custom']) +} diff --git a/examples/jasmine/Gruntfile.js b/examples/jasmine/Gruntfile.js index 8ed1c1e..1f0b738 100644 --- a/examples/jasmine/Gruntfile.js +++ b/examples/jasmine/Gruntfile.js @@ -17,7 +17,7 @@ module.exports = function (grunt) { browserName: 'internet explorer', platform: 'VISTA', version: '9' - }]; + }] grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), @@ -48,10 +48,10 @@ module.exports = function (grunt) { } }, watch: {} - }); + }) - grunt.loadNpmTasks('grunt-contrib-connect'); - grunt.loadNpmTasks('grunt-saucelabs'); + grunt.loadNpmTasks('grunt-contrib-connect') + grunt.loadNpmTasks('grunt-saucelabs') - grunt.registerTask('default', ['connect', 'saucelabs-jasmine']); -}; \ No newline at end of file + grunt.registerTask('default', ['connect', 'saucelabs-jasmine']) +} diff --git a/examples/jasmine/lib/jasmine-jsreporter/jasmine-jsreporter.js b/examples/jasmine/lib/jasmine-jsreporter/jasmine-jsreporter.js index a5f95bc..9dce608 100644 --- a/examples/jasmine/lib/jasmine-jsreporter/jasmine-jsreporter.js +++ b/examples/jasmine/lib/jasmine-jsreporter/jasmine-jsreporter.js @@ -28,9 +28,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (jasmine) { - if (!jasmine) { - throw new Error("[Jasmine JSReporter] 'Jasmine' library not found"); + throw new Error("[Jasmine JSReporter] 'Jasmine' library not found") } // ------------------------------------------------------------------------ @@ -43,7 +42,7 @@ * @param finishMs Finish time in Milliseconds * @return Elapsed time in Seconds */ function elapsedSec (startMs, finishMs) { - return (finishMs - startMs) / 1000; + return (finishMs - startMs) / 1000 } /** @@ -53,8 +52,8 @@ * @param numOfDecDigits Number of Digits to round to. Default value is '2'. * @return Rounded amount */ function round (amount, numOfDecDigits) { - numOfDecDigits = numOfDecDigits || 2; - return Math.round(amount * Math.pow(10, numOfDecDigits)) / Math.pow(10, numOfDecDigits); + numOfDecDigits = numOfDecDigits || 2 + return Math.round(amount * Math.pow(10, numOfDecDigits)) / Math.pow(10, numOfDecDigits) } /** @@ -62,14 +61,14 @@ * @param items Items which will be filtered * @returns {Array} of failed items */ function failures (items) { - var fs = [], i, v; - for (i = 0; i < items.length; i += 1) { - v = items[i]; - if (!v.passed_) { - fs.push(v); - } + var fs = []; var i; var v + for (i = 0; i < items.length; i += 1) { + v = items[i] + if (!v.passed_) { + fs.push(v) } - return fs; + } + return fs } /** @@ -77,109 +76,108 @@ * @param suite The Jasmine Suite to get data from */ function getSuiteData (suite) { - var suiteData = { - description : suite.description, - durationSec : 0, - specs: [], - suites: [], - passed: true - }, - specs = suite.specs(), - suites = suite.suites(), - i, ilen; - - // Loop over all the Suite's Specs - for (i = 0, ilen = specs.length; i < ilen; ++i) { - suiteData.specs[i] = { - description : specs[i].description, - durationSec : specs[i].durationSec, - passed : specs[i].results().passedCount === specs[i].results().totalCount, - skipped : specs[i].results().skipped, - passedCount : specs[i].results().passedCount, - failedCount : specs[i].results().failedCount, - totalCount : specs[i].results().totalCount, - failures: failures(specs[i].results().getItems()) - }; - suiteData.passed = !suiteData.specs[i].passed ? false : suiteData.passed; - suiteData.durationSec += suiteData.specs[i].durationSec; + var suiteData = { + description: suite.description, + durationSec: 0, + specs: [], + suites: [], + passed: true + } + var specs = suite.specs() + var suites = suite.suites() + var i; var ilen + + // Loop over all the Suite's Specs + for (i = 0, ilen = specs.length; i < ilen; ++i) { + suiteData.specs[i] = { + description: specs[i].description, + durationSec: specs[i].durationSec, + passed: specs[i].results().passedCount === specs[i].results().totalCount, + skipped: specs[i].results().skipped, + passedCount: specs[i].results().passedCount, + failedCount: specs[i].results().failedCount, + totalCount: specs[i].results().totalCount, + failures: failures(specs[i].results().getItems()) } + suiteData.passed = !suiteData.specs[i].passed ? false : suiteData.passed + suiteData.durationSec += suiteData.specs[i].durationSec + } - // Loop over all the Suite's sub-Suites - for (i = 0, ilen = suites.length; i < ilen; ++i) { - suiteData.suites[i] = getSuiteData(suites[i]); //< recursive population - suiteData.passed = !suiteData.suites[i].passed ? false : suiteData.passed; - suiteData.durationSec += suiteData.suites[i].durationSec; - } + // Loop over all the Suite's sub-Suites + for (i = 0, ilen = suites.length; i < ilen; ++i) { + suiteData.suites[i] = getSuiteData(suites[i]) // < recursive population + suiteData.passed = !suiteData.suites[i].passed ? false : suiteData.passed + suiteData.durationSec += suiteData.suites[i].durationSec + } - // Rounding duration numbers to 3 decimal digits - suiteData.durationSec = round(suiteData.durationSec, 4); + // Rounding duration numbers to 3 decimal digits + suiteData.durationSec = round(suiteData.durationSec, 4) - return suiteData; + return suiteData } - var JSReporter = function () { - }; + var JSReporter = function () { + } JSReporter.prototype = { - reportRunnerStarting: function (runner) { - // Nothing to do - }, - - reportSpecStarting: function (spec) { - // Start timing this spec - spec.startedAt = new Date(); - }, - - reportSpecResults: function (spec) { - // Finish timing this spec and calculate duration/delta (in sec) - spec.finishedAt = new Date(); - // If the spec was skipped, reportSpecStarting is never called and spec.startedAt is undefined - spec.durationSec = spec.startedAt ? elapsedSec(spec.startedAt.getTime(), spec.finishedAt.getTime()) : 0; - }, - - reportSuiteResults: function (suite) { - // Nothing to do - }, - - reportRunnerResults: function (runner) { - var suites = runner.suites(), - i, j, ilen; - - // Attach results to the "jasmine" object to make those results easy to scrap/find - jasmine.runnerResults = { - suites: [], - durationSec : 0, - passed : true - }; - - // Loop over all the Suites - for (i = 0, ilen = suites.length, j = 0; i < ilen; ++i) { - if (suites[i].parentSuite === null) { - jasmine.runnerResults.suites[j] = getSuiteData(suites[i]); - // If 1 suite fails, the whole runner fails - jasmine.runnerResults.passed = !jasmine.runnerResults.suites[j].passed ? false : jasmine.runnerResults.passed; - // Add up all the durations - jasmine.runnerResults.durationSec += jasmine.runnerResults.suites[j].durationSec; - j++; - } - } - - // Decorate the 'jasmine' object with getters - jasmine.getJSReport = function () { - if (jasmine.runnerResults) { - return jasmine.runnerResults; - } - return null; - }; - jasmine.getJSReportAsString = function () { - return JSON.stringify(jasmine.getJSReport()); - }; + reportRunnerStarting: function (runner) { + // Nothing to do + }, + + reportSpecStarting: function (spec) { + // Start timing this spec + spec.startedAt = new Date() + }, + + reportSpecResults: function (spec) { + // Finish timing this spec and calculate duration/delta (in sec) + spec.finishedAt = new Date() + // If the spec was skipped, reportSpecStarting is never called and spec.startedAt is undefined + spec.durationSec = spec.startedAt ? elapsedSec(spec.startedAt.getTime(), spec.finishedAt.getTime()) : 0 + }, + + reportSuiteResults: function (suite) { + // Nothing to do + }, + + reportRunnerResults: function (runner) { + var suites = runner.suites() + var i; var j; var ilen + + // Attach results to the "jasmine" object to make those results easy to scrap/find + jasmine.runnerResults = { + suites: [], + durationSec: 0, + passed: true } - }; - // export public - jasmine.JSReporter = JSReporter; + // Loop over all the Suites + for (i = 0, ilen = suites.length, j = 0; i < ilen; ++i) { + if (suites[i].parentSuite === null) { + jasmine.runnerResults.suites[j] = getSuiteData(suites[i]) + // If 1 suite fails, the whole runner fails + jasmine.runnerResults.passed = !jasmine.runnerResults.suites[j].passed ? false : jasmine.runnerResults.passed + // Add up all the durations + jasmine.runnerResults.durationSec += jasmine.runnerResults.suites[j].durationSec + j++ + } + } + // Decorate the 'jasmine' object with getters + jasmine.getJSReport = function () { + if (jasmine.runnerResults) { + return jasmine.runnerResults + } + return null + } + jasmine.getJSReportAsString = function () { + return JSON.stringify(jasmine.getJSReport()) + } + } + } + + // export public + jasmine.JSReporter = JSReporter // ------------------------------------------------------------------------ // Jasmine JSReporter for Jasmine 2.0 @@ -188,113 +186,113 @@ /* Simple timer implementation */ - var Timer = function () {}; + var Timer = function () {} Timer.prototype.start = function () { - this.startTime = new Date().getTime(); - return this; - }; + this.startTime = new Date().getTime() + return this + } Timer.prototype.elapsed = function () { if (this.startTime == null) { - return -1; + return -1 } - return new Date().getTime() - this.startTime; - }; + return new Date().getTime() - this.startTime + } /* Utility methods */ var _extend = function (obj1, obj2) { for (var prop in obj2) { - obj1[prop] = obj2[prop]; + obj1[prop] = obj2[prop] } - return obj1; - }; + return obj1 + } var _clone = function (obj) { if (obj !== Object(obj)) { - return obj; + return obj } - return _extend({}, obj); - }; + return _extend({}, obj) + } jasmine.JSReporter2 = function () { - this.specs = {}; - this.suites = {}; - this.rootSuites = []; - this.suiteStack = []; + this.specs = {} + this.suites = {} + this.rootSuites = [] + this.suiteStack = [] // export methods under jasmine namespace - jasmine.getJSReport = this.getJSReport; - jasmine.getJSReportAsString = this.getJSReportAsString; - }; + jasmine.getJSReport = this.getJSReport + jasmine.getJSReportAsString = this.getJSReportAsString + } - var JSR = jasmine.JSReporter2.prototype; + var JSR = jasmine.JSReporter2.prototype // Reporter API methods // -------------------- JSR.suiteStarted = function (suite) { - suite = this._cacheSuite(suite); + suite = this._cacheSuite(suite) // build up suite tree as we go - suite.specs = []; - suite.suites = []; - suite.passed = true; - suite.parentId = this.suiteStack.slice(this.suiteStack.length -1)[0]; + suite.specs = [] + suite.suites = [] + suite.passed = true + suite.parentId = this.suiteStack.slice(this.suiteStack.length - 1)[0] if (suite.parentId) { - this.suites[suite.parentId].suites.push(suite); + this.suites[suite.parentId].suites.push(suite) } else { - this.rootSuites.push(suite.id); + this.rootSuites.push(suite.id) } - this.suiteStack.push(suite.id); - suite.timer = new Timer().start(); - }; + this.suiteStack.push(suite.id) + suite.timer = new Timer().start() + } JSR.suiteDone = function (suite) { - suite = this._cacheSuite(suite); - suite.duration = suite.timer.elapsed(); - suite.durationSec = suite.duration / 1000; - this.suiteStack.pop(); + suite = this._cacheSuite(suite) + suite.duration = suite.timer.elapsed() + suite.durationSec = suite.duration / 1000 + this.suiteStack.pop() // maintain parent suite state - var parent = this.suites[suite.parentId]; + var parent = this.suites[suite.parentId] if (parent) { - parent.passed = parent.passed && suite.passed; + parent.passed = parent.passed && suite.passed } // keep report representation clean - delete suite.timer; - delete suite.id; - delete suite.parentId; - delete suite.fullName; - }; + delete suite.timer + delete suite.id + delete suite.parentId + delete suite.fullName + } JSR.specStarted = function (spec) { - spec = this._cacheSpec(spec); - spec.timer = new Timer().start(); + spec = this._cacheSpec(spec) + spec.timer = new Timer().start() // build up suites->spec tree as we go - spec.suiteId = this.suiteStack.slice(this.suiteStack.length -1)[0]; - this.suites[spec.suiteId].specs.push(spec); - }; + spec.suiteId = this.suiteStack.slice(this.suiteStack.length - 1)[0] + this.suites[spec.suiteId].specs.push(spec) + } JSR.specDone = function (spec) { - spec = this._cacheSpec(spec); + spec = this._cacheSpec(spec) - spec.duration = spec.timer.elapsed(); - spec.durationSec = spec.duration / 1000; + spec.duration = spec.timer.elapsed() + spec.durationSec = spec.duration / 1000 - spec.skipped = spec.status === 'pending'; - spec.passed = spec.skipped || spec.status === 'passed'; + spec.skipped = spec.status === 'pending' + spec.passed = spec.skipped || spec.status === 'passed' // totalCount and passedCount will be populated if/when jasmine#575 gets accepted - spec.totalCount = spec.totalExpectations || 0; - spec.passedCount = spec.passedExpectations ? spec.passedExpectations.length : 0; + spec.totalCount = spec.totalExpectations || 0 + spec.passedCount = spec.passedExpectations ? spec.passedExpectations.length : 0 - spec.failedCount = spec.failedExpectations.length; - spec.failures = []; + spec.failedCount = spec.failedExpectations.length + spec.failures = [] for (var i = 0, j = spec.failedExpectations.length; i < j; i++) { - var fail = spec.failedExpectations[i]; + var fail = spec.failedExpectations[i] spec.failures.push({ type: 'expect', expected: fail.expected, @@ -304,91 +302,90 @@ trace: { stack: fail.stack } - }); + }) } // maintain parent suite state - var parent = this.suites[spec.suiteId]; + var parent = this.suites[spec.suiteId] if (spec.failed) { - parent.failingSpecs.push(spec); + parent.failingSpecs.push(spec) } - parent.passed = parent.passed && spec.passed; + parent.passed = parent.passed && spec.passed // keep report representation clean - delete spec.timer; - delete spec.totalExpectations; - delete spec.passedExpectations; - delete spec.suiteId; - delete spec.fullName; - delete spec.id; - delete spec.status; - delete spec.failedExpectations; - }; + delete spec.timer + delete spec.totalExpectations + delete spec.passedExpectations + delete spec.suiteId + delete spec.fullName + delete spec.id + delete spec.status + delete spec.failedExpectations + } JSR.jasmineDone = function () { - this._buildReport(); - }; + this._buildReport() + } JSR.getJSReport = function () { if (jasmine.jsReport) { - return jasmine.jsReport; + return jasmine.jsReport } - }; + } JSR.getJSReportAsString = function () { if (jasmine.jsReport) { - return JSON.stringify(jasmine.jsReport); + return JSON.stringify(jasmine.jsReport) } - }; + } // Private methods // --------------- JSR._haveSpec = function (spec) { - return this.specs[spec.id] != null; - }; + return this.specs[spec.id] != null + } JSR._cacheSpec = function (spec) { - var existing = this.specs[spec.id]; + var existing = this.specs[spec.id] if (existing == null) { - existing = this.specs[spec.id] = _clone(spec); + existing = this.specs[spec.id] = _clone(spec) } else { - _extend(existing, spec); + _extend(existing, spec) } - return existing; - }; + return existing + } JSR._haveSuite = function (suite) { - return this.suites[suite.id] != null; - }; + return this.suites[suite.id] != null + } JSR._cacheSuite = function (suite) { - var existing = this.suites[suite.id]; + var existing = this.suites[suite.id] if (existing == null) { - existing = this.suites[suite.id] = _clone(suite); + existing = this.suites[suite.id] = _clone(suite) } else { - _extend(existing, suite); + _extend(existing, suite) } - return existing; - }; + return existing + } JSR._buildReport = function () { - var overallDuration = 0; - var overallPassed = true; - var overallSuites = []; + var overallDuration = 0 + var overallPassed = true + var overallSuites = [] for (var i = 0, j = this.rootSuites.length; i < j; i++) { - var suite = this.suites[this.rootSuites[i]]; - overallDuration += suite.duration; - overallPassed = overallPassed && suite.passed; - overallSuites.push(suite); + var suite = this.suites[this.rootSuites[i]] + overallDuration += suite.duration + overallPassed = overallPassed && suite.passed + overallSuites.push(suite) } jasmine.jsReport = { passed: overallPassed, durationSec: overallDuration / 1000, suites: overallSuites - }; - }; - -})(jasmine); \ No newline at end of file + } + } +})(jasmine) diff --git a/examples/jasmine/lib/jasmine/jasmine-html.js b/examples/jasmine/lib/jasmine/jasmine-html.js index 543d569..00719eb 100644 --- a/examples/jasmine/lib/jasmine/jasmine-html.js +++ b/examples/jasmine/lib/jasmine/jasmine-html.js @@ -1,399 +1,395 @@ -jasmine.HtmlReporterHelpers = {}; +jasmine.HtmlReporterHelpers = {} -jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); +jasmine.HtmlReporterHelpers.createDom = function (type, attrs, childrenVarArgs) { + var el = document.createElement(type) for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; + var child = arguments[i] if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); + el.appendChild(document.createTextNode(child)) } else { if (child) { - el.appendChild(child); + el.appendChild(child) } } } for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; + if (attr == 'className') { + el[attr] = attrs[attr] } else { - el.setAttribute(attr, attrs[attr]); + el.setAttribute(attr, attrs[attr]) } } - return el; -}; + return el +} -jasmine.HtmlReporterHelpers.getSpecStatus = function(child) { - var results = child.results(); - var status = results.passed() ? 'passed' : 'failed'; +jasmine.HtmlReporterHelpers.getSpecStatus = function (child) { + var results = child.results() + var status = results.passed() ? 'passed' : 'failed' if (results.skipped) { - status = 'skipped'; + status = 'skipped' } - return status; -}; + return status +} -jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) { - var parentDiv = this.dom.summary; - var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite'; - var parent = child[parentSuite]; +jasmine.HtmlReporterHelpers.appendToSummary = function (child, childElement) { + var parentDiv = this.dom.summary + var parentSuite = (typeof child.parentSuite === 'undefined') ? 'suite' : 'parentSuite' + var parent = child[parentSuite] if (parent) { - if (typeof this.views.suites[parent.id] == 'undefined') { - this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views); + if (typeof this.views.suites[parent.id] === 'undefined') { + this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views) } - parentDiv = this.views.suites[parent.id].element; + parentDiv = this.views.suites[parent.id].element } - parentDiv.appendChild(childElement); -}; - + parentDiv.appendChild(childElement) +} -jasmine.HtmlReporterHelpers.addHelpers = function(ctor) { - for(var fn in jasmine.HtmlReporterHelpers) { - ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn]; +jasmine.HtmlReporterHelpers.addHelpers = function (ctor) { + for (var fn in jasmine.HtmlReporterHelpers) { + ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn] } -}; +} -jasmine.HtmlReporter = function(_doc) { - var self = this; - var doc = _doc || window.document; +jasmine.HtmlReporter = function (_doc) { + var self = this + var doc = _doc || window.document - var reporterView; + var reporterView - var dom = {}; + var dom = {} // Jasmine Reporter Public Interface - self.logRunningSpecs = false; + self.logRunningSpecs = false - self.reportRunnerStarting = function(runner) { - var specs = runner.specs() || []; + self.reportRunnerStarting = function (runner) { + var specs = runner.specs() || [] if (specs.length == 0) { - return; + return } - createReporterDom(runner.env.versionString()); - doc.body.appendChild(dom.reporter); - setExceptionHandling(); + createReporterDom(runner.env.versionString()) + doc.body.appendChild(dom.reporter) + setExceptionHandling() - reporterView = new jasmine.HtmlReporter.ReporterView(dom); - reporterView.addSpecs(specs, self.specFilter); - }; + reporterView = new jasmine.HtmlReporter.ReporterView(dom) + reporterView.addSpecs(specs, self.specFilter) + } - self.reportRunnerResults = function(runner) { - reporterView && reporterView.complete(); - }; + self.reportRunnerResults = function (runner) { + reporterView && reporterView.complete() + } - self.reportSuiteResults = function(suite) { - reporterView.suiteComplete(suite); - }; + self.reportSuiteResults = function (suite) { + reporterView.suiteComplete(suite) + } - self.reportSpecStarting = function(spec) { + self.reportSpecStarting = function (spec) { if (self.logRunningSpecs) { - self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); + self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...') } - }; + } - self.reportSpecResults = function(spec) { - reporterView.specComplete(spec); - }; + self.reportSpecResults = function (spec) { + reporterView.specComplete(spec) + } - self.log = function() { - var console = jasmine.getGlobal().console; + self.log = function () { + var console = jasmine.getGlobal().console if (console && console.log) { if (console.log.apply) { - console.log.apply(console, arguments); + console.log.apply(console, arguments) } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie + console.log(arguments) // ie fix: console.log.apply doesn't exist on ie } } - }; + } - self.specFilter = function(spec) { + self.specFilter = function (spec) { if (!focusedSpecName()) { - return true; + return true } - return spec.getFullName().indexOf(focusedSpecName()) === 0; - }; + return spec.getFullName().indexOf(focusedSpecName()) === 0 + } - return self; + return self - function focusedSpecName() { + function focusedSpecName () { var specName; - (function memoizeFocusedSpec() { + (function memoizeFocusedSpec () { if (specName) { - return; + return } - var paramMap = []; - var params = jasmine.HtmlReporter.parameters(doc); + var paramMap = [] + var params = jasmine.HtmlReporter.parameters(doc) for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); + var p = params[i].split('=') + paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]) } - specName = paramMap.spec; - })(); + specName = paramMap.spec + })() - return specName; + return specName } - function createReporterDom(version) { + function createReporterDom (version) { dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, dom.banner = self.createDom('div', { className: 'banner' }, - self.createDom('span', { className: 'title' }, "Jasmine "), + self.createDom('span', { className: 'title' }, 'Jasmine '), self.createDom('span', { className: 'version' }, version)), - dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), - dom.alert = self.createDom('div', {className: 'alert'}, + dom.symbolSummary = self.createDom('ul', { className: 'symbolSummary' }), + dom.alert = self.createDom('div', { className: 'alert' }, self.createDom('span', { className: 'exceptions' }, - self.createDom('label', { className: 'label', 'for': 'no_try_catch' }, 'No try/catch'), + self.createDom('label', { className: 'label', for: 'no_try_catch' }, 'No try/catch'), self.createDom('input', { id: 'no_try_catch', type: 'checkbox' }))), - dom.results = self.createDom('div', {className: 'results'}, + dom.results = self.createDom('div', { className: 'results' }, dom.summary = self.createDom('div', { className: 'summary' }), dom.details = self.createDom('div', { id: 'details' })) - ); + ) } - function noTryCatch() { - return window.location.search.match(/catch=false/); + function noTryCatch () { + return window.location.search.match(/catch=false/) } - function searchWithCatch() { - var params = jasmine.HtmlReporter.parameters(window.document); - var removed = false; - var i = 0; + function searchWithCatch () { + var params = jasmine.HtmlReporter.parameters(window.document) + var removed = false + var i = 0 while (!removed && i < params.length) { if (params[i].match(/catch=/)) { - params.splice(i, 1); - removed = true; + params.splice(i, 1) + removed = true } - i++; + i++ } if (jasmine.CATCH_EXCEPTIONS) { - params.push("catch=false"); + params.push('catch=false') } - return params.join("&"); + return params.join('&') } - function setExceptionHandling() { - var chxCatch = document.getElementById('no_try_catch'); + function setExceptionHandling () { + var chxCatch = document.getElementById('no_try_catch') if (noTryCatch()) { - chxCatch.setAttribute('checked', true); - jasmine.CATCH_EXCEPTIONS = false; + chxCatch.setAttribute('checked', true) + jasmine.CATCH_EXCEPTIONS = false + } + chxCatch.onclick = function () { + window.location.search = searchWithCatch() } - chxCatch.onclick = function() { - window.location.search = searchWithCatch(); - }; } -}; -jasmine.HtmlReporter.parameters = function(doc) { - var paramStr = doc.location.search.substring(1); - var params = []; +} +jasmine.HtmlReporter.parameters = function (doc) { + var paramStr = doc.location.search.substring(1) + var params = [] if (paramStr.length > 0) { - params = paramStr.split('&'); + params = paramStr.split('&') } - return params; + return params } -jasmine.HtmlReporter.sectionLink = function(sectionName) { - var link = '?'; - var params = []; +jasmine.HtmlReporter.sectionLink = function (sectionName) { + var link = '?' + var params = [] if (sectionName) { - params.push('spec=' + encodeURIComponent(sectionName)); + params.push('spec=' + encodeURIComponent(sectionName)) } if (!jasmine.CATCH_EXCEPTIONS) { - params.push("catch=false"); + params.push('catch=false') } if (params.length > 0) { - link += params.join("&"); - } - - return link; -}; -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter); -jasmine.HtmlReporter.ReporterView = function(dom) { - this.startedAt = new Date(); - this.runningSpecCount = 0; - this.completeSpecCount = 0; - this.passedCount = 0; - this.failedCount = 0; - this.skippedCount = 0; - - this.createResultsMenu = function() { - this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'}, - this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'), + link += params.join('&') + } + + return link +} +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter) +jasmine.HtmlReporter.ReporterView = function (dom) { + this.startedAt = new Date() + this.runningSpecCount = 0 + this.completeSpecCount = 0 + this.passedCount = 0 + this.failedCount = 0 + this.skippedCount = 0 + + this.createResultsMenu = function () { + this.resultsMenu = this.createDom('span', { className: 'resultsMenu bar' }, + this.summaryMenuItem = this.createDom('a', { className: 'summaryMenuItem', href: '#' }, '0 specs'), ' | ', - this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing')); + this.detailsMenuItem = this.createDom('a', { className: 'detailsMenuItem', href: '#' }, '0 failing')) - this.summaryMenuItem.onclick = function() { - dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, ''); - }; + this.summaryMenuItem.onclick = function () { + dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, '') + } - this.detailsMenuItem.onclick = function() { - showDetails(); - }; - }; + this.detailsMenuItem.onclick = function () { + showDetails() + } + } - this.addSpecs = function(specs, specFilter) { - this.totalSpecCount = specs.length; + this.addSpecs = function (specs, specFilter) { + this.totalSpecCount = specs.length this.views = { specs: {}, suites: {} - }; + } for (var i = 0; i < specs.length; i++) { - var spec = specs[i]; - this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views); + var spec = specs[i] + this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views) if (specFilter(spec)) { - this.runningSpecCount++; + this.runningSpecCount++ } } - }; + } - this.specComplete = function(spec) { - this.completeSpecCount++; + this.specComplete = function (spec) { + this.completeSpecCount++ if (isUndefined(this.views.specs[spec.id])) { - this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom); + this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom) } - var specView = this.views.specs[spec.id]; + var specView = this.views.specs[spec.id] switch (specView.status()) { case 'passed': - this.passedCount++; - break; + this.passedCount++ + break case 'failed': - this.failedCount++; - break; + this.failedCount++ + break case 'skipped': - this.skippedCount++; - break; + this.skippedCount++ + break } - specView.refresh(); - this.refresh(); - }; + specView.refresh() + this.refresh() + } - this.suiteComplete = function(suite) { - var suiteView = this.views.suites[suite.id]; + this.suiteComplete = function (suite) { + var suiteView = this.views.suites[suite.id] if (isUndefined(suiteView)) { - return; + return } - suiteView.refresh(); - }; - - this.refresh = function() { + suiteView.refresh() + } + this.refresh = function () { if (isUndefined(this.resultsMenu)) { - this.createResultsMenu(); + this.createResultsMenu() } // currently running UI if (isUndefined(this.runningAlert)) { - this.runningAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "runningAlert bar" }); - dom.alert.appendChild(this.runningAlert); + this.runningAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: 'runningAlert bar' }) + dom.alert.appendChild(this.runningAlert) } - this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount); + this.runningAlert.innerHTML = 'Running ' + this.completeSpecCount + ' of ' + specPluralizedFor(this.totalSpecCount) // skipped specs UI if (isUndefined(this.skippedAlert)) { - this.skippedAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "skippedAlert bar" }); + this.skippedAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: 'skippedAlert bar' }) } - this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; + this.skippedAlert.innerHTML = 'Skipping ' + this.skippedCount + ' of ' + specPluralizedFor(this.totalSpecCount) + ' - run all' if (this.skippedCount === 1 && isDefined(dom.alert)) { - dom.alert.appendChild(this.skippedAlert); + dom.alert.appendChild(this.skippedAlert) } // passing specs UI if (isUndefined(this.passedAlert)) { - this.passedAlert = this.createDom('span', { href: jasmine.HtmlReporter.sectionLink(), className: "passingAlert bar" }); + this.passedAlert = this.createDom('span', { href: jasmine.HtmlReporter.sectionLink(), className: 'passingAlert bar' }) } - this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount); + this.passedAlert.innerHTML = 'Passing ' + specPluralizedFor(this.passedCount) // failing specs UI if (isUndefined(this.failedAlert)) { - this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"}); + this.failedAlert = this.createDom('span', { href: '?', className: 'failingAlert bar' }) } - this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount); + this.failedAlert.innerHTML = 'Failing ' + specPluralizedFor(this.failedCount) if (this.failedCount === 1 && isDefined(dom.alert)) { - dom.alert.appendChild(this.failedAlert); - dom.alert.appendChild(this.resultsMenu); + dom.alert.appendChild(this.failedAlert) + dom.alert.appendChild(this.resultsMenu) } // summary info - this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount); - this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing"; - }; + this.summaryMenuItem.innerHTML = '' + specPluralizedFor(this.runningSpecCount) + this.detailsMenuItem.innerHTML = '' + this.failedCount + ' failing' + } - this.complete = function() { - dom.alert.removeChild(this.runningAlert); + this.complete = function () { + dom.alert.removeChild(this.runningAlert) - this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; + this.skippedAlert.innerHTML = 'Ran ' + this.runningSpecCount + ' of ' + specPluralizedFor(this.totalSpecCount) + ' - run all' if (this.failedCount === 0) { - dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount))); + dom.alert.appendChild(this.createDom('span', { className: 'passingAlert bar' }, 'Passing ' + specPluralizedFor(this.passedCount))) } else { - showDetails(); + showDetails() } - dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s")); - }; + dom.banner.appendChild(this.createDom('span', { className: 'duration' }, 'finished in ' + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + 's')) + } - return this; + return this - function showDetails() { + function showDetails () { if (dom.reporter.className.search(/showDetails/) === -1) { - dom.reporter.className += " showDetails"; + dom.reporter.className += ' showDetails' } } - function isUndefined(obj) { - return typeof obj === 'undefined'; + function isUndefined (obj) { + return typeof obj === 'undefined' } - function isDefined(obj) { - return !isUndefined(obj); + function isDefined (obj) { + return !isUndefined(obj) } - function specPluralizedFor(count) { - var str = count + " spec"; + function specPluralizedFor (count) { + var str = count + ' spec' if (count > 1) { - str += "s" + str += 's' } - return str; + return str } +} -}; - -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView); - +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView) -jasmine.HtmlReporter.SpecView = function(spec, dom, views) { - this.spec = spec; - this.dom = dom; - this.views = views; +jasmine.HtmlReporter.SpecView = function (spec, dom, views) { + this.spec = spec + this.dom = dom + this.views = views - this.symbol = this.createDom('li', { className: 'pending' }); - this.dom.symbolSummary.appendChild(this.symbol); + this.symbol = this.createDom('li', { className: 'pending' }) + this.dom.symbolSummary.appendChild(this.symbol) this.summary = this.createDom('div', { className: 'specSummary' }, this.createDom('a', { @@ -401,281 +397,280 @@ jasmine.HtmlReporter.SpecView = function(spec, dom, views) { href: jasmine.HtmlReporter.sectionLink(this.spec.getFullName()), title: this.spec.getFullName() }, this.spec.description) - ); + ) this.detail = this.createDom('div', { className: 'specDetail' }, - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(this.spec.getFullName()), - title: this.spec.getFullName() - }, this.spec.getFullName()) - ); -}; + this.createDom('a', { + className: 'description', + href: '?spec=' + encodeURIComponent(this.spec.getFullName()), + title: this.spec.getFullName() + }, this.spec.getFullName()) + ) +} -jasmine.HtmlReporter.SpecView.prototype.status = function() { - return this.getSpecStatus(this.spec); -}; +jasmine.HtmlReporter.SpecView.prototype.status = function () { + return this.getSpecStatus(this.spec) +} -jasmine.HtmlReporter.SpecView.prototype.refresh = function() { - this.symbol.className = this.status(); +jasmine.HtmlReporter.SpecView.prototype.refresh = function () { + this.symbol.className = this.status() switch (this.status()) { case 'skipped': - break; + break case 'passed': - this.appendSummaryToSuiteDiv(); - break; + this.appendSummaryToSuiteDiv() + break case 'failed': - this.appendSummaryToSuiteDiv(); - this.appendFailureDetail(); - break; + this.appendSummaryToSuiteDiv() + this.appendFailureDetail() + break } -}; +} -jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() { - this.summary.className += ' ' + this.status(); - this.appendToSummary(this.spec, this.summary); -}; +jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function () { + this.summary.className += ' ' + this.status() + this.appendToSummary(this.spec, this.summary) +} -jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() { - this.detail.className += ' ' + this.status(); +jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function () { + this.detail.className += ' ' + this.status() - var resultItems = this.spec.results().getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); + var resultItems = this.spec.results().getItems() + var messagesDiv = this.createDom('div', { className: 'messages' }) for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; + var result = resultItems[i] if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); + messagesDiv.appendChild(this.createDom('div', { className: 'resultMessage log' }, result.toString())) } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); + messagesDiv.appendChild(this.createDom('div', { className: 'resultMessage fail' }, result.message)) if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); + messagesDiv.appendChild(this.createDom('div', { className: 'stackTrace' }, result.trace.stack)) } } } if (messagesDiv.childNodes.length > 0) { - this.detail.appendChild(messagesDiv); - this.dom.details.appendChild(this.detail); + this.detail.appendChild(messagesDiv) + this.dom.details.appendChild(this.detail) } -}; +} -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { - this.suite = suite; - this.dom = dom; - this.views = views; +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView); jasmine.HtmlReporter.SuiteView = function (suite, dom, views) { + this.suite = suite + this.dom = dom + this.views = views this.element = this.createDom('div', { className: 'suite' }, this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description) - ); + ) - this.appendToSummary(this.suite, this.element); -}; + this.appendToSummary(this.suite, this.element) +} -jasmine.HtmlReporter.SuiteView.prototype.status = function() { - return this.getSpecStatus(this.suite); -}; +jasmine.HtmlReporter.SuiteView.prototype.status = function () { + return this.getSpecStatus(this.suite) +} -jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { - this.element.className += " " + this.status(); -}; +jasmine.HtmlReporter.SuiteView.prototype.refresh = function () { + this.element.className += ' ' + this.status() +} -jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView) /* @deprecated Use jasmine.HtmlReporter instead */ -jasmine.TrivialReporter = function(doc) { - this.document = doc || document; - this.suiteDivs = {}; - this.logRunningSpecs = false; -}; +jasmine.TrivialReporter = function (doc) { + this.document = doc || document + this.suiteDivs = {} + this.logRunningSpecs = false +} -jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); +jasmine.TrivialReporter.prototype.createDom = function (type, attrs, childrenVarArgs) { + var el = document.createElement(type) for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; + var child = arguments[i] if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); + el.appendChild(document.createTextNode(child)) } else { - if (child) { el.appendChild(child); } + if (child) { el.appendChild(child) } } } for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; + if (attr == 'className') { + el[attr] = attrs[attr] } else { - el.setAttribute(attr, attrs[attr]); + el.setAttribute(attr, attrs[attr]) } } - return el; -}; + return el +} -jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { - var showPassed, showSkipped; +jasmine.TrivialReporter.prototype.reportRunnerStarting = function (runner) { + var showPassed, showSkipped this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, - this.createDom('div', { className: 'banner' }, - this.createDom('div', { className: 'logo' }, - this.createDom('span', { className: 'title' }, "Jasmine"), - this.createDom('span', { className: 'version' }, runner.env.versionString())), - this.createDom('div', { className: 'options' }, - "Show ", - showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), - showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") - ) - ), - - this.runnerDiv = this.createDom('div', { className: 'runner running' }, - this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), - this.runnerMessageSpan = this.createDom('span', {}, "Running..."), - this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) - ); - - this.document.body.appendChild(this.outerDiv); - - var suites = runner.suites(); + this.createDom('div', { className: 'banner' }, + this.createDom('div', { className: 'logo' }, + this.createDom('span', { className: 'title' }, 'Jasmine'), + this.createDom('span', { className: 'version' }, runner.env.versionString())), + this.createDom('div', { className: 'options' }, + 'Show ', + showPassed = this.createDom('input', { id: '__jasmine_TrivialReporter_showPassed__', type: 'checkbox' }), + this.createDom('label', { for: '__jasmine_TrivialReporter_showPassed__' }, ' passed '), + showSkipped = this.createDom('input', { id: '__jasmine_TrivialReporter_showSkipped__', type: 'checkbox' }), + this.createDom('label', { for: '__jasmine_TrivialReporter_showSkipped__' }, ' skipped') + ) + ), + + this.runnerDiv = this.createDom('div', { className: 'runner running' }, + this.createDom('a', { className: 'run_spec', href: '?' }, 'run all'), + this.runnerMessageSpan = this.createDom('span', {}, 'Running...'), + this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, '')) + ) + + this.document.body.appendChild(this.outerDiv) + + var suites = runner.suites() for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; + var suite = suites[i] var suiteDiv = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), - this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); - this.suiteDivs[suite.id] = suiteDiv; - var parentDiv = this.outerDiv; + this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, 'run'), + this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)) + this.suiteDivs[suite.id] = suiteDiv + var parentDiv = this.outerDiv if (suite.parentSuite) { - parentDiv = this.suiteDivs[suite.parentSuite.id]; + parentDiv = this.suiteDivs[suite.parentSuite.id] } - parentDiv.appendChild(suiteDiv); + parentDiv.appendChild(suiteDiv) } - this.startedAt = new Date(); + this.startedAt = new Date() - var self = this; - showPassed.onclick = function(evt) { + var self = this + showPassed.onclick = function (evt) { if (showPassed.checked) { - self.outerDiv.className += ' show-passed'; + self.outerDiv.className += ' show-passed' } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); + self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '') } - }; + } - showSkipped.onclick = function(evt) { + showSkipped.onclick = function (evt) { if (showSkipped.checked) { - self.outerDiv.className += ' show-skipped'; + self.outerDiv.className += ' show-skipped' } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); - } - }; -}; - -jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { - var results = runner.results(); - var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; - this.runnerDiv.setAttribute("class", className); - //do it twice for IE - this.runnerDiv.setAttribute("className", className); - var specs = runner.specs(); - var specCount = 0; + self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '') + } + } +} + +jasmine.TrivialReporter.prototype.reportRunnerResults = function (runner) { + var results = runner.results() + var className = (results.failedCount > 0) ? 'runner failed' : 'runner passed' + this.runnerDiv.setAttribute('class', className) + // do it twice for IE + this.runnerDiv.setAttribute('className', className) + var specs = runner.specs() + var specCount = 0 for (var i = 0; i < specs.length; i++) { if (this.specFilter(specs[i])) { - specCount++; + specCount++ } } - var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); - message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; - this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); + var message = '' + specCount + ' spec' + (specCount == 1 ? '' : 's') + ', ' + results.failedCount + ' failure' + ((results.failedCount == 1) ? '' : 's') + message += ' in ' + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + 's' + this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?' }, message), this.runnerMessageSpan.firstChild) - this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); -}; + this.finishedAtSpan.appendChild(document.createTextNode('Finished at ' + new Date().toString())) +} -jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { - var results = suite.results(); - var status = results.passed() ? 'passed' : 'failed'; +jasmine.TrivialReporter.prototype.reportSuiteResults = function (suite) { + var results = suite.results() + var status = results.passed() ? 'passed' : 'failed' if (results.totalCount === 0) { // todo: change this to check results.skipped - status = 'skipped'; + status = 'skipped' } - this.suiteDivs[suite.id].className += " " + status; -}; + this.suiteDivs[suite.id].className += ' ' + status +} -jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { +jasmine.TrivialReporter.prototype.reportSpecStarting = function (spec) { if (this.logRunningSpecs) { - this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); + this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...') } -}; +} -jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { - var results = spec.results(); - var status = results.passed() ? 'passed' : 'failed'; +jasmine.TrivialReporter.prototype.reportSpecResults = function (spec) { + var results = spec.results() + var status = results.passed() ? 'passed' : 'failed' if (results.skipped) { - status = 'skipped'; + status = 'skipped' } - var specDiv = this.createDom('div', { className: 'spec ' + status }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(spec.getFullName()), - title: spec.getFullName() - }, spec.description)); - + var specDiv = this.createDom('div', { className: 'spec ' + status }, + this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, 'run'), + this.createDom('a', { + className: 'description', + href: '?spec=' + encodeURIComponent(spec.getFullName()), + title: spec.getFullName() + }, spec.description)) - var resultItems = results.getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); + var resultItems = results.getItems() + var messagesDiv = this.createDom('div', { className: 'messages' }) for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; + var result = resultItems[i] if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); + messagesDiv.appendChild(this.createDom('div', { className: 'resultMessage log' }, result.toString())) } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); + messagesDiv.appendChild(this.createDom('div', { className: 'resultMessage fail' }, result.message)) if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); + messagesDiv.appendChild(this.createDom('div', { className: 'stackTrace' }, result.trace.stack)) } } } if (messagesDiv.childNodes.length > 0) { - specDiv.appendChild(messagesDiv); + specDiv.appendChild(messagesDiv) } - this.suiteDivs[spec.suite.id].appendChild(specDiv); -}; + this.suiteDivs[spec.suite.id].appendChild(specDiv) +} -jasmine.TrivialReporter.prototype.log = function() { - var console = jasmine.getGlobal().console; +jasmine.TrivialReporter.prototype.log = function () { + var console = jasmine.getGlobal().console if (console && console.log) { if (console.log.apply) { - console.log.apply(console, arguments); + console.log.apply(console, arguments) } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie + console.log(arguments) // ie fix: console.log.apply doesn't exist on ie } } -}; +} -jasmine.TrivialReporter.prototype.getLocation = function() { - return this.document.location; -}; +jasmine.TrivialReporter.prototype.getLocation = function () { + return this.document.location +} -jasmine.TrivialReporter.prototype.specFilter = function(spec) { - var paramMap = {}; - var params = this.getLocation().search.substring(1).split('&'); +jasmine.TrivialReporter.prototype.specFilter = function (spec) { + var paramMap = {} + var params = this.getLocation().search.substring(1).split('&') for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); + var p = params[i].split('=') + paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]) } if (!paramMap.spec) { - return true; + return true } - return spec.getFullName().indexOf(paramMap.spec) === 0; -}; + return spec.getFullName().indexOf(paramMap.spec) === 0 +} diff --git a/examples/jasmine/lib/jasmine/jasmine.js b/examples/jasmine/lib/jasmine/jasmine.js index 6b3459b..26a62c1 100644 --- a/examples/jasmine/lib/jasmine/jasmine.js +++ b/examples/jasmine/lib/jasmine/jasmine.js @@ -1,18 +1,18 @@ -var isCommonJS = typeof window == "undefined" && typeof exports == "object"; +var isCommonJS = typeof window === 'undefined' && typeof exports === 'object' /** * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. * * @namespace */ -var jasmine = {}; -if (isCommonJS) exports.jasmine = jasmine; +var jasmine = {} +if (isCommonJS) exports.jasmine = jasmine /** * @private */ -jasmine.unimplementedMethod_ = function() { - throw new Error("unimplemented method"); -}; +jasmine.unimplementedMethod_ = function () { + throw new Error('unimplemented method') +} /** * Use jasmine.undefined instead of undefined, since undefined is just @@ -20,44 +20,44 @@ jasmine.unimplementedMethod_ = function() { * * @private */ -jasmine.undefined = jasmine.___undefined___; +jasmine.undefined = jasmine.___undefined___ /** * Show diagnostic messages in the console if set to true * */ -jasmine.VERBOSE = false; +jasmine.VERBOSE = false /** * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. * */ -jasmine.DEFAULT_UPDATE_INTERVAL = 250; +jasmine.DEFAULT_UPDATE_INTERVAL = 250 /** * Maximum levels of nesting that will be included when an object is pretty-printed */ -jasmine.MAX_PRETTY_PRINT_DEPTH = 40; +jasmine.MAX_PRETTY_PRINT_DEPTH = 40 /** * Default timeout interval in milliseconds for waitsFor() blocks. */ -jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; +jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000 /** * By default exceptions thrown in the context of a test are caught by jasmine so that it can run the remaining tests in the suite. * Set to false to let the exception bubble up in the browser. * */ -jasmine.CATCH_EXCEPTIONS = true; +jasmine.CATCH_EXCEPTIONS = true -jasmine.getGlobal = function() { - function getGlobal() { - return this; +jasmine.getGlobal = function () { + function getGlobal () { + return this } - return getGlobal(); -}; + return getGlobal() +} /** * Allows for bound functions to be compared. Internal use only. @@ -67,69 +67,69 @@ jasmine.getGlobal = function() { * @param base {Object} bound 'this' for the function * @param name {Function} function to find */ -jasmine.bindOriginal_ = function(base, name) { - var original = base[name]; +jasmine.bindOriginal_ = function (base, name) { + var original = base[name] if (original.apply) { - return function() { - return original.apply(base, arguments); - }; + return function () { + return original.apply(base, arguments) + } } else { // IE support - return jasmine.getGlobal()[name]; + return jasmine.getGlobal()[name] } -}; +} -jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); -jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); -jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); -jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); +jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout') +jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout') +jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval') +jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval') -jasmine.MessageResult = function(values) { - this.type = 'log'; - this.values = values; - this.trace = new Error(); // todo: test better -}; +jasmine.MessageResult = function (values) { + this.type = 'log' + this.values = values + this.trace = new Error() // todo: test better +} -jasmine.MessageResult.prototype.toString = function() { - var text = ""; +jasmine.MessageResult.prototype.toString = function () { + var text = '' for (var i = 0; i < this.values.length; i++) { - if (i > 0) text += " "; + if (i > 0) text += ' ' if (jasmine.isString_(this.values[i])) { - text += this.values[i]; + text += this.values[i] } else { - text += jasmine.pp(this.values[i]); + text += jasmine.pp(this.values[i]) } } - return text; -}; + return text +} -jasmine.ExpectationResult = function(params) { - this.type = 'expect'; - this.matcherName = params.matcherName; - this.passed_ = params.passed; - this.expected = params.expected; - this.actual = params.actual; - this.message = this.passed_ ? 'Passed.' : params.message; +jasmine.ExpectationResult = function (params) { + this.type = 'expect' + this.matcherName = params.matcherName + this.passed_ = params.passed + this.expected = params.expected + this.actual = params.actual + this.message = this.passed_ ? 'Passed.' : params.message - var trace = (params.trace || new Error(this.message)); - this.trace = this.passed_ ? '' : trace; -}; + var trace = (params.trace || new Error(this.message)) + this.trace = this.passed_ ? '' : trace +} jasmine.ExpectationResult.prototype.toString = function () { - return this.message; -}; + return this.message +} jasmine.ExpectationResult.prototype.passed = function () { - return this.passed_; -}; + return this.passed_ +} /** * Getter for the Jasmine environment. Ensures one gets created */ -jasmine.getEnv = function() { - var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); - return env; -}; +jasmine.getEnv = function () { + var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env() + return env +} /** * @ignore @@ -137,9 +137,9 @@ jasmine.getEnv = function() { * @param value * @returns {Boolean} */ -jasmine.isArray_ = function(value) { - return jasmine.isA_("Array", value); -}; +jasmine.isArray_ = function (value) { + return jasmine.isA_('Array', value) +} /** * @ignore @@ -147,9 +147,9 @@ jasmine.isArray_ = function(value) { * @param value * @returns {Boolean} */ -jasmine.isString_ = function(value) { - return jasmine.isA_("String", value); -}; +jasmine.isString_ = function (value) { + return jasmine.isA_('String', value) +} /** * @ignore @@ -157,9 +157,9 @@ jasmine.isString_ = function(value) { * @param value * @returns {Boolean} */ -jasmine.isNumber_ = function(value) { - return jasmine.isA_("Number", value); -}; +jasmine.isNumber_ = function (value) { + return jasmine.isA_('Number', value) +} /** * @ignore @@ -168,9 +168,9 @@ jasmine.isNumber_ = function(value) { * @param value * @returns {Boolean} */ -jasmine.isA_ = function(typeName, value) { - return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; -}; +jasmine.isA_ = function (typeName, value) { + return Object.prototype.toString.apply(value) === '[object ' + typeName + ']' +} /** * Pretty printer for expecations. Takes any object and turns it into a human-readable string. @@ -178,11 +178,11 @@ jasmine.isA_ = function(typeName, value) { * @param value {Object} an object to be outputted * @returns {String} */ -jasmine.pp = function(value) { - var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); - stringPrettyPrinter.format(value); - return stringPrettyPrinter.string; -}; +jasmine.pp = function (value) { + var stringPrettyPrinter = new jasmine.StringPrettyPrinter() + stringPrettyPrinter.format(value) + return stringPrettyPrinter.string +} /** * Returns true if the object is a DOM Node. @@ -190,9 +190,9 @@ jasmine.pp = function(value) { * @param {Object} obj object to check * @returns {Boolean} */ -jasmine.isDomNode = function(obj) { - return obj.nodeType > 0; -}; +jasmine.isDomNode = function (obj) { + return obj.nodeType > 0 +} /** * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. @@ -204,9 +204,9 @@ jasmine.isDomNode = function(obj) { * @param {Class} clazz * @returns matchable object of the type clazz */ -jasmine.any = function(clazz) { - return new jasmine.Matchers.Any(clazz); -}; +jasmine.any = function (clazz) { + return new jasmine.Matchers.Any(clazz) +} /** * Returns a matchable subset of a JSON object. For use in expectations when you don't care about all of the @@ -220,8 +220,8 @@ jasmine.any = function(clazz) { * @returns matchable object for the sample */ jasmine.objectContaining = function (sample) { - return new jasmine.Matchers.ObjectContaining(sample); -}; + return new jasmine.Matchers.ObjectContaining(sample) +} /** * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. @@ -267,20 +267,20 @@ jasmine.objectContaining = function (sample) { * @see spyOn, jasmine.createSpy, jasmine.createSpyObj * @param {String} name */ -jasmine.Spy = function(name) { +jasmine.Spy = function (name) { /** * The name of the spy, if provided. */ - this.identity = name || 'unknown'; + this.identity = name || 'unknown' /** * Is this Object a spy? */ - this.isSpy = true; + this.isSpy = true /** * The actual function this spy stubs. */ - this.plan = function() { - }; + this.plan = function () { + } /** * Tracking of the most recent call to the spy. * @example @@ -288,7 +288,7 @@ jasmine.Spy = function(name) { * mySpy(1, 2); * mySpy.mostRecentCall.args = [1, 2]; */ - this.mostRecentCall = {}; + this.mostRecentCall = {} /** * Holds arguments for each call to the spy, indexed by call count @@ -300,9 +300,9 @@ jasmine.Spy = function(name) { * mySpy.argsForCall[0] = [1, 2]; * mySpy.argsForCall[1] = [7, 8]; */ - this.argsForCall = []; - this.calls = []; -}; + this.argsForCall = [] + this.calls = [] +} /** * Tells a spy to call through to the actual implemenatation. @@ -315,10 +315,10 @@ jasmine.Spy = function(name) { * // defining a spy on an existing property: foo.bar * spyOn(foo, 'bar').andCallThrough(); */ -jasmine.Spy.prototype.andCallThrough = function() { - this.plan = this.originalValue; - return this; -}; +jasmine.Spy.prototype.andCallThrough = function () { + this.plan = this.originalValue + return this +} /** * For setting the return value of a spy. @@ -332,12 +332,12 @@ jasmine.Spy.prototype.andCallThrough = function() { * * @param {Object} value */ -jasmine.Spy.prototype.andReturn = function(value) { - this.plan = function() { - return value; - }; - return this; -}; +jasmine.Spy.prototype.andReturn = function (value) { + this.plan = function () { + return value + } + return this +} /** * For throwing an exception when a spy is called. @@ -351,12 +351,12 @@ jasmine.Spy.prototype.andReturn = function(value) { * * @param {String} exceptionMsg */ -jasmine.Spy.prototype.andThrow = function(exceptionMsg) { - this.plan = function() { - throw exceptionMsg; - }; - return this; -}; +jasmine.Spy.prototype.andThrow = function (exceptionMsg) { + this.plan = function () { + throw exceptionMsg + } + return this +} /** * Calls an alternate implementation when a spy is called. @@ -373,10 +373,10 @@ jasmine.Spy.prototype.andThrow = function(exceptionMsg) { * * @param {Function} fakeFunc */ -jasmine.Spy.prototype.andCallFake = function(fakeFunc) { - this.plan = fakeFunc; - return this; -}; +jasmine.Spy.prototype.andCallFake = function (fakeFunc) { + this.plan = fakeFunc + return this +} /** * Resets all of a spy's the tracking variables so that it can be used again. @@ -392,37 +392,36 @@ jasmine.Spy.prototype.andCallFake = function(fakeFunc) { * * expect(foo.bar.callCount).toEqual(0); */ -jasmine.Spy.prototype.reset = function() { - this.wasCalled = false; - this.callCount = 0; - this.argsForCall = []; - this.calls = []; - this.mostRecentCall = {}; -}; +jasmine.Spy.prototype.reset = function () { + this.wasCalled = false + this.callCount = 0 + this.argsForCall = [] + this.calls = [] + this.mostRecentCall = {} +} -jasmine.createSpy = function(name) { - - var spyObj = function() { - spyObj.wasCalled = true; - spyObj.callCount++; - var args = jasmine.util.argsToArray(arguments); - spyObj.mostRecentCall.object = this; - spyObj.mostRecentCall.args = args; - spyObj.argsForCall.push(args); - spyObj.calls.push({object: this, args: args}); - return spyObj.plan.apply(this, arguments); - }; +jasmine.createSpy = function (name) { + var spyObj = function () { + spyObj.wasCalled = true + spyObj.callCount++ + var args = jasmine.util.argsToArray(arguments) + spyObj.mostRecentCall.object = this + spyObj.mostRecentCall.args = args + spyObj.argsForCall.push(args) + spyObj.calls.push({ object: this, args: args }) + return spyObj.plan.apply(this, arguments) + } - var spy = new jasmine.Spy(name); + var spy = new jasmine.Spy(name) for (var prop in spy) { - spyObj[prop] = spy[prop]; + spyObj[prop] = spy[prop] } - spyObj.reset(); + spyObj.reset() - return spyObj; -}; + return spyObj +} /** * Determines whether an object is a spy. @@ -430,9 +429,9 @@ jasmine.createSpy = function(name) { * @param {jasmine.Spy|Object} putativeSpy * @returns {Boolean} */ -jasmine.isSpy = function(putativeSpy) { - return putativeSpy && putativeSpy.isSpy; -}; +jasmine.isSpy = function (putativeSpy) { + return putativeSpy && putativeSpy.isSpy +} /** * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something @@ -441,26 +440,26 @@ jasmine.isSpy = function(putativeSpy) { * @param {String} baseName name of spy class * @param {Array} methodNames array of names of methods to make spies */ -jasmine.createSpyObj = function(baseName, methodNames) { +jasmine.createSpyObj = function (baseName, methodNames) { if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { - throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); + throw new Error('createSpyObj requires a non-empty array of method names to create spies for') } - var obj = {}; + var obj = {} for (var i = 0; i < methodNames.length; i++) { - obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); + obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]) } - return obj; -}; + return obj +} /** * All parameters are pretty-printed and concatenated together, then written to the current spec's output. * * Be careful not to leave calls to jasmine.log in production code. */ -jasmine.log = function() { - var spec = jasmine.getEnv().currentSpec; - spec.log.apply(spec, arguments); -}; +jasmine.log = function () { + var spec = jasmine.getEnv().currentSpec + spec.log.apply(spec, arguments) +} /** * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. @@ -477,10 +476,10 @@ jasmine.log = function() { * @param methodName * @return {jasmine.Spy} a Jasmine spy that can be chained with all spy methods */ -var spyOn = function(obj, methodName) { - return jasmine.getEnv().currentSpec.spyOn(obj, methodName); -}; -if (isCommonJS) exports.spyOn = spyOn; +var spyOn = function (obj, methodName) { + return jasmine.getEnv().currentSpec.spyOn(obj, methodName) +} +if (isCommonJS) exports.spyOn = spyOn /** * Creates a Jasmine spec that will be added to the current suite. @@ -495,10 +494,10 @@ if (isCommonJS) exports.spyOn = spyOn; * @param {String} desc description of this specification * @param {Function} func defines the preconditions and expectations of the spec */ -var it = function(desc, func) { - return jasmine.getEnv().it(desc, func); -}; -if (isCommonJS) exports.it = it; +var it = function (desc, func) { + return jasmine.getEnv().it(desc, func) +} +if (isCommonJS) exports.it = it /** * Creates a disabled Jasmine spec. @@ -508,10 +507,10 @@ if (isCommonJS) exports.it = it; * @param {String} desc description of this specification * @param {Function} func defines the preconditions and expectations of the spec */ -var xit = function(desc, func) { - return jasmine.getEnv().xit(desc, func); -}; -if (isCommonJS) exports.xit = xit; +var xit = function (desc, func) { + return jasmine.getEnv().xit(desc, func) +} +if (isCommonJS) exports.xit = xit /** * Starts a chain for a Jasmine expectation. @@ -522,20 +521,20 @@ if (isCommonJS) exports.xit = xit; * @param {Object} actual Actual value to test against and expected value * @return {jasmine.Matchers} */ -var expect = function(actual) { - return jasmine.getEnv().currentSpec.expect(actual); -}; -if (isCommonJS) exports.expect = expect; +var expect = function (actual) { + return jasmine.getEnv().currentSpec.expect(actual) +} +if (isCommonJS) exports.expect = expect /** * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. * * @param {Function} func Function that defines part of a jasmine spec. */ -var runs = function(func) { - jasmine.getEnv().currentSpec.runs(func); -}; -if (isCommonJS) exports.runs = runs; +var runs = function (func) { + jasmine.getEnv().currentSpec.runs(func) +} +if (isCommonJS) exports.runs = runs /** * Waits a fixed time period before moving to the next block. @@ -543,10 +542,10 @@ if (isCommonJS) exports.runs = runs; * @deprecated Use waitsFor() instead * @param {Number} timeout milliseconds to wait */ -var waits = function(timeout) { - jasmine.getEnv().currentSpec.waits(timeout); -}; -if (isCommonJS) exports.waits = waits; +var waits = function (timeout) { + jasmine.getEnv().currentSpec.waits(timeout) +} +if (isCommonJS) exports.waits = waits /** * Waits for the latchFunction to return true before proceeding to the next block. @@ -555,10 +554,10 @@ if (isCommonJS) exports.waits = waits; * @param {String} optional_timeoutMessage * @param {Number} optional_timeout */ -var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); -}; -if (isCommonJS) exports.waitsFor = waitsFor; +var waitsFor = function (latchFunction, optional_timeoutMessage, optional_timeout) { + jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments) +} +if (isCommonJS) exports.waitsFor = waitsFor /** * A function that is called before each spec in a suite. @@ -567,10 +566,10 @@ if (isCommonJS) exports.waitsFor = waitsFor; * * @param {Function} beforeEachFunction */ -var beforeEach = function(beforeEachFunction) { - jasmine.getEnv().beforeEach(beforeEachFunction); -}; -if (isCommonJS) exports.beforeEach = beforeEach; +var beforeEach = function (beforeEachFunction) { + jasmine.getEnv().beforeEach(beforeEachFunction) +} +if (isCommonJS) exports.beforeEach = beforeEach /** * A function that is called after each spec in a suite. @@ -579,10 +578,10 @@ if (isCommonJS) exports.beforeEach = beforeEach; * * @param {Function} afterEachFunction */ -var afterEach = function(afterEachFunction) { - jasmine.getEnv().afterEach(afterEachFunction); -}; -if (isCommonJS) exports.afterEach = afterEach; +var afterEach = function (afterEachFunction) { + jasmine.getEnv().afterEach(afterEachFunction) +} +if (isCommonJS) exports.afterEach = afterEach /** * Defines a suite of specifications. @@ -599,10 +598,10 @@ if (isCommonJS) exports.afterEach = afterEach; * @param {String} description A string, usually the class under test. * @param {Function} specDefinitions function that defines several specs. */ -var describe = function(description, specDefinitions) { - return jasmine.getEnv().describe(description, specDefinitions); -}; -if (isCommonJS) exports.describe = describe; +var describe = function (description, specDefinitions) { + return jasmine.getEnv().describe(description, specDefinitions) +} +if (isCommonJS) exports.describe = describe /** * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. @@ -610,43 +609,42 @@ if (isCommonJS) exports.describe = describe; * @param {String} description A string, usually the class under test. * @param {Function} specDefinitions function that defines several specs. */ -var xdescribe = function(description, specDefinitions) { - return jasmine.getEnv().xdescribe(description, specDefinitions); -}; -if (isCommonJS) exports.xdescribe = xdescribe; - +var xdescribe = function (description, specDefinitions) { + return jasmine.getEnv().xdescribe(description, specDefinitions) +} +if (isCommonJS) exports.xdescribe = xdescribe // Provide the XMLHttpRequest class for IE 5.x-6.x: -jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { - function tryIt(f) { +jasmine.XmlHttpRequest = (typeof XMLHttpRequest === 'undefined') ? function () { + function tryIt (f) { try { - return f(); - } catch(e) { + return f() + } catch (e) { } - return null; + return null } - var xhr = tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.6.0"); + var xhr = tryIt(function () { + return new ActiveXObject('Msxml2.XMLHTTP.6.0') }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.3.0"); + tryIt(function () { + return new ActiveXObject('Msxml2.XMLHTTP.3.0') }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP"); + tryIt(function () { + return new ActiveXObject('Msxml2.XMLHTTP') }) || - tryIt(function() { - return new ActiveXObject("Microsoft.XMLHTTP"); - }); + tryIt(function () { + return new ActiveXObject('Microsoft.XMLHTTP') + }) - if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); + if (!xhr) throw new Error('This browser does not support XMLHttpRequest.') - return xhr; -} : XMLHttpRequest; + return xhr +} : XMLHttpRequest /** * @namespace */ -jasmine.util = {}; +jasmine.util = {} /** * Declare that a child class inherit it's prototype from the parent class. @@ -655,391 +653,382 @@ jasmine.util = {}; * @param {Function} childClass * @param {Function} parentClass */ -jasmine.util.inherit = function(childClass, parentClass) { +jasmine.util.inherit = function (childClass, parentClass) { /** * @private */ - var subclass = function() { - }; - subclass.prototype = parentClass.prototype; - childClass.prototype = new subclass(); -}; + var subclass = function () { + } + subclass.prototype = parentClass.prototype + childClass.prototype = new subclass() +} -jasmine.util.formatException = function(e) { - var lineNumber; +jasmine.util.formatException = function (e) { + var lineNumber if (e.line) { - lineNumber = e.line; - } - else if (e.lineNumber) { - lineNumber = e.lineNumber; + lineNumber = e.line + } else if (e.lineNumber) { + lineNumber = e.lineNumber } - var file; + var file if (e.sourceURL) { - file = e.sourceURL; - } - else if (e.fileName) { - file = e.fileName; + file = e.sourceURL + } else if (e.fileName) { + file = e.fileName } - var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); + var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString() if (file && lineNumber) { - message += ' in ' + file + ' (line ' + lineNumber + ')'; + message += ' in ' + file + ' (line ' + lineNumber + ')' } - return message; -}; + return message +} -jasmine.util.htmlEscape = function(str) { - if (!str) return str; +jasmine.util.htmlEscape = function (str) { + if (!str) return str return str.replace(/&/g, '&') .replace(//g, '>'); -}; + .replace(/>/g, '>') +} -jasmine.util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); - return arrayOfArgs; -}; +jasmine.util.argsToArray = function (args) { + var arrayOfArgs = [] + for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]) + return arrayOfArgs +} -jasmine.util.extend = function(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; -}; +jasmine.util.extend = function (destination, source) { + for (var property in source) destination[property] = source[property] + return destination +} /** * Environment for Jasmine * * @constructor */ -jasmine.Env = function() { - this.currentSpec = null; - this.currentSuite = null; - this.currentRunner_ = new jasmine.Runner(this); +jasmine.Env = function () { + this.currentSpec = null + this.currentSuite = null + this.currentRunner_ = new jasmine.Runner(this) - this.reporter = new jasmine.MultiReporter(); + this.reporter = new jasmine.MultiReporter() - this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; - this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; - this.lastUpdate = 0; - this.specFilter = function() { - return true; - }; + this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL + this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL + this.lastUpdate = 0 + this.specFilter = function () { + return true + } - this.nextSpecId_ = 0; - this.nextSuiteId_ = 0; - this.equalityTesters_ = []; + this.nextSpecId_ = 0 + this.nextSuiteId_ = 0 + this.equalityTesters_ = [] // wrap matchers - this.matchersClass = function() { - jasmine.Matchers.apply(this, arguments); - }; - jasmine.util.inherit(this.matchersClass, jasmine.Matchers); - - jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); -}; + this.matchersClass = function () { + jasmine.Matchers.apply(this, arguments) + } + jasmine.util.inherit(this.matchersClass, jasmine.Matchers) + jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass) +} -jasmine.Env.prototype.setTimeout = jasmine.setTimeout; -jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; -jasmine.Env.prototype.setInterval = jasmine.setInterval; -jasmine.Env.prototype.clearInterval = jasmine.clearInterval; +jasmine.Env.prototype.setTimeout = jasmine.setTimeout +jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout +jasmine.Env.prototype.setInterval = jasmine.setInterval +jasmine.Env.prototype.clearInterval = jasmine.clearInterval /** * @returns an object containing jasmine version build info, if set. */ jasmine.Env.prototype.version = function () { if (jasmine.version_) { - return jasmine.version_; + return jasmine.version_ } else { - throw new Error('Version not set'); + throw new Error('Version not set') } -}; +} /** * @returns string containing jasmine version build info, if set. */ -jasmine.Env.prototype.versionString = function() { +jasmine.Env.prototype.versionString = function () { if (!jasmine.version_) { - return "version unknown"; + return 'version unknown' } - var version = this.version(); - var versionString = version.major + "." + version.minor + "." + version.build; + var version = this.version() + var versionString = version.major + '.' + version.minor + '.' + version.build if (version.release_candidate) { - versionString += ".rc" + version.release_candidate; + versionString += '.rc' + version.release_candidate } - versionString += " revision " + version.revision; - return versionString; -}; + versionString += ' revision ' + version.revision + return versionString +} /** * @returns a sequential integer starting at 0 */ jasmine.Env.prototype.nextSpecId = function () { - return this.nextSpecId_++; -}; + return this.nextSpecId_++ +} /** * @returns a sequential integer starting at 0 */ jasmine.Env.prototype.nextSuiteId = function () { - return this.nextSuiteId_++; -}; + return this.nextSuiteId_++ +} /** * Register a reporter to receive status updates from Jasmine. * @param {jasmine.Reporter} reporter An object which will receive status updates. */ -jasmine.Env.prototype.addReporter = function(reporter) { - this.reporter.addReporter(reporter); -}; +jasmine.Env.prototype.addReporter = function (reporter) { + this.reporter.addReporter(reporter) +} -jasmine.Env.prototype.execute = function() { - this.currentRunner_.execute(); -}; +jasmine.Env.prototype.execute = function () { + this.currentRunner_.execute() +} -jasmine.Env.prototype.describe = function(description, specDefinitions) { - var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); +jasmine.Env.prototype.describe = function (description, specDefinitions) { + var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite) - var parentSuite = this.currentSuite; + var parentSuite = this.currentSuite if (parentSuite) { - parentSuite.add(suite); + parentSuite.add(suite) } else { - this.currentRunner_.add(suite); + this.currentRunner_.add(suite) } - this.currentSuite = suite; + this.currentSuite = suite - var declarationError = null; + var declarationError = null try { - specDefinitions.call(suite); - } catch(e) { - declarationError = e; + specDefinitions.call(suite) + } catch (e) { + declarationError = e } if (declarationError) { - this.it("encountered a declaration exception", function() { - throw declarationError; - }); + this.it('encountered a declaration exception', function () { + throw declarationError + }) } - this.currentSuite = parentSuite; + this.currentSuite = parentSuite - return suite; -}; + return suite +} -jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { +jasmine.Env.prototype.beforeEach = function (beforeEachFunction) { if (this.currentSuite) { - this.currentSuite.beforeEach(beforeEachFunction); + this.currentSuite.beforeEach(beforeEachFunction) } else { - this.currentRunner_.beforeEach(beforeEachFunction); + this.currentRunner_.beforeEach(beforeEachFunction) } -}; +} jasmine.Env.prototype.currentRunner = function () { - return this.currentRunner_; -}; + return this.currentRunner_ +} -jasmine.Env.prototype.afterEach = function(afterEachFunction) { +jasmine.Env.prototype.afterEach = function (afterEachFunction) { if (this.currentSuite) { - this.currentSuite.afterEach(afterEachFunction); + this.currentSuite.afterEach(afterEachFunction) } else { - this.currentRunner_.afterEach(afterEachFunction); + this.currentRunner_.afterEach(afterEachFunction) } +} -}; - -jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { +jasmine.Env.prototype.xdescribe = function (desc, specDefinitions) { return { - execute: function() { + execute: function () { } - }; -}; + } +} -jasmine.Env.prototype.it = function(description, func) { - var spec = new jasmine.Spec(this, this.currentSuite, description); - this.currentSuite.add(spec); - this.currentSpec = spec; +jasmine.Env.prototype.it = function (description, func) { + var spec = new jasmine.Spec(this, this.currentSuite, description) + this.currentSuite.add(spec) + this.currentSpec = spec if (func) { - spec.runs(func); + spec.runs(func) } - return spec; -}; + return spec +} -jasmine.Env.prototype.xit = function(desc, func) { +jasmine.Env.prototype.xit = function (desc, func) { return { id: this.nextSpecId(), - runs: function() { + runs: function () { } - }; -}; + } +} -jasmine.Env.prototype.compareRegExps_ = function(a, b, mismatchKeys, mismatchValues) { - if (a.source != b.source) - mismatchValues.push("expected pattern /" + b.source + "/ is not equal to the pattern /" + a.source + "/"); +jasmine.Env.prototype.compareRegExps_ = function (a, b, mismatchKeys, mismatchValues) { + if (a.source != b.source) { mismatchValues.push('expected pattern /' + b.source + '/ is not equal to the pattern /' + a.source + '/') } - if (a.ignoreCase != b.ignoreCase) - mismatchValues.push("expected modifier i was" + (b.ignoreCase ? " " : " not ") + "set and does not equal the origin modifier"); + if (a.ignoreCase != b.ignoreCase) { mismatchValues.push('expected modifier i was' + (b.ignoreCase ? ' ' : ' not ') + 'set and does not equal the origin modifier') } - if (a.global != b.global) - mismatchValues.push("expected modifier g was" + (b.global ? " " : " not ") + "set and does not equal the origin modifier"); + if (a.global != b.global) { mismatchValues.push('expected modifier g was' + (b.global ? ' ' : ' not ') + 'set and does not equal the origin modifier') } - if (a.multiline != b.multiline) - mismatchValues.push("expected modifier m was" + (b.multiline ? " " : " not ") + "set and does not equal the origin modifier"); + if (a.multiline != b.multiline) { mismatchValues.push('expected modifier m was' + (b.multiline ? ' ' : ' not ') + 'set and does not equal the origin modifier') } - if (a.sticky != b.sticky) - mismatchValues.push("expected modifier y was" + (b.sticky ? " " : " not ") + "set and does not equal the origin modifier"); + if (a.sticky != b.sticky) { mismatchValues.push('expected modifier y was' + (b.sticky ? ' ' : ' not ') + 'set and does not equal the origin modifier') } - return (mismatchValues.length === 0); -}; + return (mismatchValues.length === 0) +} -jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { +jasmine.Env.prototype.compareObjects_ = function (a, b, mismatchKeys, mismatchValues) { if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { - return true; + return true } - a.__Jasmine_been_here_before__ = b; - b.__Jasmine_been_here_before__ = a; + a.__Jasmine_been_here_before__ = b + b.__Jasmine_been_here_before__ = a - var hasKey = function(obj, keyName) { - return obj !== null && obj[keyName] !== jasmine.undefined; - }; + var hasKey = function (obj, keyName) { + return obj !== null && obj[keyName] !== jasmine.undefined + } for (var property in b) { if (!hasKey(a, property) && hasKey(b, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); + mismatchKeys.push("expected has key '" + property + "', but missing from actual.") } } for (property in a) { if (!hasKey(b, property) && hasKey(a, property)) { - mismatchKeys.push("expected missing key '" + property + "', but present in actual."); + mismatchKeys.push("expected missing key '" + property + "', but present in actual.") } } for (property in b) { - if (property == '__Jasmine_been_here_before__') continue; + if (property == '__Jasmine_been_here_before__') continue if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); + mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual.") } } if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { - mismatchValues.push("arrays were not the same length"); + mismatchValues.push('arrays were not the same length') } - delete a.__Jasmine_been_here_before__; - delete b.__Jasmine_been_here_before__; - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; + delete a.__Jasmine_been_here_before__ + delete b.__Jasmine_been_here_before__ + return (mismatchKeys.length === 0 && mismatchValues.length === 0) +} -jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; +jasmine.Env.prototype.equals_ = function (a, b, mismatchKeys, mismatchValues) { + mismatchKeys = mismatchKeys || [] + mismatchValues = mismatchValues || [] for (var i = 0; i < this.equalityTesters_.length; i++) { - var equalityTester = this.equalityTesters_[i]; - var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); - if (result !== jasmine.undefined) return result; + var equalityTester = this.equalityTesters_[i] + var result = equalityTester(a, b, this, mismatchKeys, mismatchValues) + if (result !== jasmine.undefined) return result } - if (a === b) return true; + if (a === b) return true if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { - return (a == jasmine.undefined && b == jasmine.undefined); + return (a == jasmine.undefined && b == jasmine.undefined) } if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { - return a === b; + return a === b } if (a instanceof Date && b instanceof Date) { - return a.getTime() == b.getTime(); + return a.getTime() == b.getTime() } if (a.jasmineMatches) { - return a.jasmineMatches(b); + return a.jasmineMatches(b) } if (b.jasmineMatches) { - return b.jasmineMatches(a); + return b.jasmineMatches(a) } if (a instanceof jasmine.Matchers.ObjectContaining) { - return a.matches(b); + return a.matches(b) } if (b instanceof jasmine.Matchers.ObjectContaining) { - return b.matches(a); + return b.matches(a) } if (jasmine.isString_(a) && jasmine.isString_(b)) { - return (a == b); + return (a == b) } if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { - return (a == b); + return (a == b) } if (a instanceof RegExp && b instanceof RegExp) { - return this.compareRegExps_(a, b, mismatchKeys, mismatchValues); + return this.compareRegExps_(a, b, mismatchKeys, mismatchValues) } - if (typeof a === "object" && typeof b === "object") { - return this.compareObjects_(a, b, mismatchKeys, mismatchValues); + if (typeof a === 'object' && typeof b === 'object') { + return this.compareObjects_(a, b, mismatchKeys, mismatchValues) } - //Straight check - return (a === b); -}; + // Straight check + return (a === b) +} -jasmine.Env.prototype.contains_ = function(haystack, needle) { +jasmine.Env.prototype.contains_ = function (haystack, needle) { if (jasmine.isArray_(haystack)) { for (var i = 0; i < haystack.length; i++) { - if (this.equals_(haystack[i], needle)) return true; + if (this.equals_(haystack[i], needle)) return true } - return false; + return false } - return haystack.indexOf(needle) >= 0; -}; + return haystack.indexOf(needle) >= 0 +} -jasmine.Env.prototype.addEqualityTester = function(equalityTester) { - this.equalityTesters_.push(equalityTester); -}; +jasmine.Env.prototype.addEqualityTester = function (equalityTester) { + this.equalityTesters_.push(equalityTester) +} /** No-op base class for Jasmine reporters. * * @constructor */ -jasmine.Reporter = function() { -}; +jasmine.Reporter = function () { +} -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { -}; +// noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportRunnerStarting = function (runner) { +} -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerResults = function(runner) { -}; +// noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportRunnerResults = function (runner) { +} -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSuiteResults = function(suite) { -}; +// noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSuiteResults = function (suite) { +} -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecStarting = function(spec) { -}; +// noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSpecStarting = function (spec) { +} -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecResults = function(spec) { -}; +// noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSpecResults = function (spec) { +} -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.log = function(str) { -}; +// noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.log = function (str) { +} /** * Blocks are functions with executable code that make up a spec. @@ -1049,110 +1038,109 @@ jasmine.Reporter.prototype.log = function(str) { * @param {Function} func * @param {jasmine.Spec} spec */ -jasmine.Block = function(env, func, spec) { - this.env = env; - this.func = func; - this.spec = spec; -}; +jasmine.Block = function (env, func, spec) { + this.env = env + this.func = func + this.spec = spec +} -jasmine.Block.prototype.execute = function(onComplete) { +jasmine.Block.prototype.execute = function (onComplete) { if (!jasmine.CATCH_EXCEPTIONS) { - this.func.apply(this.spec); - } - else { + this.func.apply(this.spec) + } else { try { - this.func.apply(this.spec); + this.func.apply(this.spec) } catch (e) { - this.spec.fail(e); + this.spec.fail(e) } } - onComplete(); -}; + onComplete() +} /** JavaScript API reporter. * * @constructor */ -jasmine.JsApiReporter = function() { - this.started = false; - this.finished = false; - this.suites_ = []; - this.results_ = {}; -}; +jasmine.JsApiReporter = function () { + this.started = false + this.finished = false + this.suites_ = [] + this.results_ = {} +} -jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { - this.started = true; - var suites = runner.topLevelSuites(); +jasmine.JsApiReporter.prototype.reportRunnerStarting = function (runner) { + this.started = true + var suites = runner.topLevelSuites() for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - this.suites_.push(this.summarize_(suite)); + var suite = suites[i] + this.suites_.push(this.summarize_(suite)) } -}; +} -jasmine.JsApiReporter.prototype.suites = function() { - return this.suites_; -}; +jasmine.JsApiReporter.prototype.suites = function () { + return this.suites_ +} -jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { - var isSuite = suiteOrSpec instanceof jasmine.Suite; +jasmine.JsApiReporter.prototype.summarize_ = function (suiteOrSpec) { + var isSuite = suiteOrSpec instanceof jasmine.Suite var summary = { id: suiteOrSpec.id, name: suiteOrSpec.description, type: isSuite ? 'suite' : 'spec', children: [] - }; - + } + if (isSuite) { - var children = suiteOrSpec.children(); + var children = suiteOrSpec.children() for (var i = 0; i < children.length; i++) { - summary.children.push(this.summarize_(children[i])); + summary.children.push(this.summarize_(children[i])) } } - return summary; -}; + return summary +} -jasmine.JsApiReporter.prototype.results = function() { - return this.results_; -}; +jasmine.JsApiReporter.prototype.results = function () { + return this.results_ +} -jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { - return this.results_[specId]; -}; +jasmine.JsApiReporter.prototype.resultsForSpec = function (specId) { + return this.results_[specId] +} -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { - this.finished = true; -}; +// noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportRunnerResults = function (runner) { + this.finished = true +} -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { -}; +// noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportSuiteResults = function (suite) { +} -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { +// noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportSpecResults = function (spec) { this.results_[spec.id] = { messages: spec.results().getItems(), - result: spec.results().failedCount > 0 ? "failed" : "passed" - }; -}; + result: spec.results().failedCount > 0 ? 'failed' : 'passed' + } +} -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.log = function(str) { -}; +// noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.log = function (str) { +} -jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ - var results = {}; +jasmine.JsApiReporter.prototype.resultsForSpecs = function (specIds) { + var results = {} for (var i = 0; i < specIds.length; i++) { - var specId = specIds[i]; - results[specId] = this.summarizeResult_(this.results_[specId]); + var specId = specIds[i] + results[specId] = this.summarizeResult_(this.results_[specId]) } - return results; -}; + return results +} -jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ - var summaryMessages = []; - var messagesLength = result.messages.length; +jasmine.JsApiReporter.prototype.summarizeResult_ = function (result) { + var summaryMessages = [] + var messagesLength = result.messages.length for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { - var resultMessage = result.messages[messageIndex]; + var resultMessage = result.messages[messageIndex] summaryMessages.push({ text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, passed: resultMessage.passed ? resultMessage.passed() : true, @@ -1161,14 +1149,14 @@ jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ trace: { stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined } - }); + }) } return { - result : result.result, - messages : summaryMessages - }; -}; + result: result.result, + messages: summaryMessages + } +} /** * @constructor @@ -1176,60 +1164,60 @@ jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ * @param actual * @param {jasmine.Spec} spec */ -jasmine.Matchers = function(env, actual, spec, opt_isNot) { - this.env = env; - this.actual = actual; - this.spec = spec; - this.isNot = opt_isNot || false; - this.reportWasCalled_ = false; -}; +jasmine.Matchers = function (env, actual, spec, opt_isNot) { + this.env = env + this.actual = actual + this.spec = spec + this.isNot = opt_isNot || false + this.reportWasCalled_ = false +} // todo: @deprecated as of Jasmine 0.11, remove soon [xw] -jasmine.Matchers.pp = function(str) { - throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); -}; +jasmine.Matchers.pp = function (str) { + throw new Error('jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!') +} // todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] -jasmine.Matchers.prototype.report = function(result, failing_message, details) { - throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); -}; +jasmine.Matchers.prototype.report = function (result, failing_message, details) { + throw new Error('As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs') +} -jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { +jasmine.Matchers.wrapInto_ = function (prototype, matchersClass) { for (var methodName in prototype) { - if (methodName == 'report') continue; - var orig = prototype[methodName]; - matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); + if (methodName == 'report') continue + var orig = prototype[methodName] + matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig) } -}; +} -jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { - return function() { - var matcherArgs = jasmine.util.argsToArray(arguments); - var result = matcherFunction.apply(this, arguments); +jasmine.Matchers.matcherFn_ = function (matcherName, matcherFunction) { + return function () { + var matcherArgs = jasmine.util.argsToArray(arguments) + var result = matcherFunction.apply(this, arguments) if (this.isNot) { - result = !result; + result = !result } - if (this.reportWasCalled_) return result; + if (this.reportWasCalled_) return result - var message; + var message if (!result) { if (this.message) { - message = this.message.apply(this, arguments); + message = this.message.apply(this, arguments) if (jasmine.isArray_(message)) { - message = message[this.isNot ? 1 : 0]; + message = message[this.isNot ? 1 : 0] } } else { - var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); - message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; + var englishyPredicate = matcherName.replace(/[A-Z]/g, function (s) { return ' ' + s.toLowerCase() }) + message = 'Expected ' + jasmine.pp(this.actual) + (this.isNot ? ' not ' : ' ') + englishyPredicate if (matcherArgs.length > 0) { for (var i = 0; i < matcherArgs.length; i++) { - if (i > 0) message += ","; - message += " " + jasmine.pp(matcherArgs[i]); + if (i > 0) message += ',' + message += ' ' + jasmine.pp(matcherArgs[i]) } } - message += "."; + message += '.' } } var expectationResult = new jasmine.ExpectationResult({ @@ -1238,49 +1226,46 @@ jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], actual: this.actual, message: message - }); - this.spec.addMatcherResult(expectationResult); - return jasmine.undefined; - }; -}; - - - + }) + this.spec.addMatcherResult(expectationResult) + return jasmine.undefined + } +} /** * toBe: compares the actual to the expected using === * @param expected */ -jasmine.Matchers.prototype.toBe = function(expected) { - return this.actual === expected; -}; +jasmine.Matchers.prototype.toBe = function (expected) { + return this.actual === expected +} /** * toNotBe: compares the actual to the expected using !== * @param expected * @deprecated as of 1.0. Use not.toBe() instead. */ -jasmine.Matchers.prototype.toNotBe = function(expected) { - return this.actual !== expected; -}; +jasmine.Matchers.prototype.toNotBe = function (expected) { + return this.actual !== expected +} /** * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. * * @param expected */ -jasmine.Matchers.prototype.toEqual = function(expected) { - return this.env.equals_(this.actual, expected); -}; +jasmine.Matchers.prototype.toEqual = function (expected) { + return this.env.equals_(this.actual, expected) +} /** * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual * @param expected * @deprecated as of 1.0. Use not.toEqual() instead. */ -jasmine.Matchers.prototype.toNotEqual = function(expected) { - return !this.env.equals_(this.actual, expected); -}; +jasmine.Matchers.prototype.toNotEqual = function (expected) { + return !this.env.equals_(this.actual, expected) +} /** * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes @@ -1288,115 +1273,113 @@ jasmine.Matchers.prototype.toNotEqual = function(expected) { * * @param expected */ -jasmine.Matchers.prototype.toMatch = function(expected) { - return new RegExp(expected).test(this.actual); -}; +jasmine.Matchers.prototype.toMatch = function (expected) { + return new RegExp(expected).test(this.actual) +} /** * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch * @param expected * @deprecated as of 1.0. Use not.toMatch() instead. */ -jasmine.Matchers.prototype.toNotMatch = function(expected) { - return !(new RegExp(expected).test(this.actual)); -}; +jasmine.Matchers.prototype.toNotMatch = function (expected) { + return !(new RegExp(expected).test(this.actual)) +} /** * Matcher that compares the actual to jasmine.undefined. */ -jasmine.Matchers.prototype.toBeDefined = function() { - return (this.actual !== jasmine.undefined); -}; +jasmine.Matchers.prototype.toBeDefined = function () { + return (this.actual !== jasmine.undefined) +} /** * Matcher that compares the actual to jasmine.undefined. */ -jasmine.Matchers.prototype.toBeUndefined = function() { - return (this.actual === jasmine.undefined); -}; +jasmine.Matchers.prototype.toBeUndefined = function () { + return (this.actual === jasmine.undefined) +} /** * Matcher that compares the actual to null. */ -jasmine.Matchers.prototype.toBeNull = function() { - return (this.actual === null); -}; +jasmine.Matchers.prototype.toBeNull = function () { + return (this.actual === null) +} /** * Matcher that compares the actual to NaN. */ -jasmine.Matchers.prototype.toBeNaN = function() { - this.message = function() { - return [ "Expected " + jasmine.pp(this.actual) + " to be NaN." ]; - }; +jasmine.Matchers.prototype.toBeNaN = function () { + this.message = function () { + return ['Expected ' + jasmine.pp(this.actual) + ' to be NaN.'] + } - return (this.actual !== this.actual); -}; + return (this.actual !== this.actual) +} /** * Matcher that boolean not-nots the actual. */ -jasmine.Matchers.prototype.toBeTruthy = function() { - return !!this.actual; -}; - +jasmine.Matchers.prototype.toBeTruthy = function () { + return !!this.actual +} /** * Matcher that boolean nots the actual. */ -jasmine.Matchers.prototype.toBeFalsy = function() { - return !this.actual; -}; - +jasmine.Matchers.prototype.toBeFalsy = function () { + return !this.actual +} /** * Matcher that checks to see if the actual, a Jasmine spy, was called. */ -jasmine.Matchers.prototype.toHaveBeenCalled = function() { +jasmine.Matchers.prototype.toHaveBeenCalled = function () { if (arguments.length > 0) { - throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); + throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith') } if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.') } - this.message = function() { + this.message = function () { return [ - "Expected spy " + this.actual.identity + " to have been called.", - "Expected spy " + this.actual.identity + " not to have been called." - ]; - }; + 'Expected spy ' + this.actual.identity + ' to have been called.', + 'Expected spy ' + this.actual.identity + ' not to have been called.' + ] + } - return this.actual.wasCalled; -}; + return this.actual.wasCalled +} /** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ -jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; +jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled /** * Matcher that checks to see if the actual, a Jasmine spy, was not called. * * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead */ -jasmine.Matchers.prototype.wasNotCalled = function() { +jasmine.Matchers.prototype.wasNotCalled = function () { if (arguments.length > 0) { - throw new Error('wasNotCalled does not take arguments'); + throw new Error('wasNotCalled does not take arguments') } if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.') } - this.message = function() { + this.message = function () { return [ - "Expected spy " + this.actual.identity + " to not have been called.", - "Expected spy " + this.actual.identity + " to have been called." - ]; - }; + 'Expected spy ' + this.actual.identity + ' to not have been called.', + 'Expected spy ' + this.actual.identity + ' to have been called.' + ] + } - return !this.actual.wasCalled; -}; + return !this.actual.wasCalled +} /** * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. @@ -1404,53 +1387,53 @@ jasmine.Matchers.prototype.wasNotCalled = function() { * @example * */ -jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); +jasmine.Matchers.prototype.toHaveBeenCalledWith = function () { + var expectedArgs = jasmine.util.argsToArray(arguments) if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.') } - this.message = function() { - var invertedMessage = "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was."; - var positiveMessage = ""; + this.message = function () { + var invertedMessage = 'Expected spy ' + this.actual.identity + ' not to have been called with ' + jasmine.pp(expectedArgs) + ' but it was.' + var positiveMessage = '' if (this.actual.callCount === 0) { - positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called."; + positiveMessage = 'Expected spy ' + this.actual.identity + ' to have been called with ' + jasmine.pp(expectedArgs) + ' but it was never called.' } else { - positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but actual calls were " + jasmine.pp(this.actual.argsForCall).replace(/^\[ | \]$/g, '') + positiveMessage = 'Expected spy ' + this.actual.identity + ' to have been called with ' + jasmine.pp(expectedArgs) + ' but actual calls were ' + jasmine.pp(this.actual.argsForCall).replace(/^\[ | \]$/g, '') } - return [positiveMessage, invertedMessage]; - }; + return [positiveMessage, invertedMessage] + } - return this.env.contains_(this.actual.argsForCall, expectedArgs); -}; + return this.env.contains_(this.actual.argsForCall, expectedArgs) +} /** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; +jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith /** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasNotCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); +jasmine.Matchers.prototype.wasNotCalledWith = function () { + var expectedArgs = jasmine.util.argsToArray(arguments) if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.') } - this.message = function() { + this.message = function () { return [ - "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", - "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" - ]; - }; + 'Expected spy not to have been called with ' + jasmine.pp(expectedArgs) + ' but it was', + 'Expected spy to have been called with ' + jasmine.pp(expectedArgs) + ' but it was' + ] + } - return !this.env.contains_(this.actual.argsForCall, expectedArgs); -}; + return !this.env.contains_(this.actual.argsForCall, expectedArgs) +} /** * Matcher that checks that the expected item is an element in the actual Array. * * @param {Object} expected */ -jasmine.Matchers.prototype.toContain = function(expected) { - return this.env.contains_(this.actual, expected); -}; +jasmine.Matchers.prototype.toContain = function (expected) { + return this.env.contains_(this.actual, expected) +} /** * Matcher that checks that the expected item is NOT an element in the actual Array. @@ -1458,17 +1441,17 @@ jasmine.Matchers.prototype.toContain = function(expected) { * @param {Object} expected * @deprecated as of 1.0. Use not.toContain() instead. */ -jasmine.Matchers.prototype.toNotContain = function(expected) { - return !this.env.contains_(this.actual, expected); -}; +jasmine.Matchers.prototype.toNotContain = function (expected) { + return !this.env.contains_(this.actual, expected) +} -jasmine.Matchers.prototype.toBeLessThan = function(expected) { - return this.actual < expected; -}; +jasmine.Matchers.prototype.toBeLessThan = function (expected) { + return this.actual < expected +} -jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { - return this.actual > expected; -}; +jasmine.Matchers.prototype.toBeGreaterThan = function (expected) { + return this.actual > expected +} /** * Matcher that checks that the expected item is equal to the actual item @@ -1477,189 +1460,187 @@ jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { * @param {Number} expected * @param {Number} precision, as number of decimal places */ -jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { +jasmine.Matchers.prototype.toBeCloseTo = function (expected, precision) { if (!(precision === 0)) { - precision = precision || 2; + precision = precision || 2 } - return Math.abs(expected - this.actual) < (Math.pow(10, -precision) / 2); -}; + return Math.abs(expected - this.actual) < (Math.pow(10, -precision) / 2) +} /** * Matcher that checks that the expected exception was thrown by the actual. * * @param {String} [expected] */ -jasmine.Matchers.prototype.toThrow = function(expected) { - var result = false; - var exception; - if (typeof this.actual != 'function') { - throw new Error('Actual is not a function'); +jasmine.Matchers.prototype.toThrow = function (expected) { + var result = false + var exception + if (typeof this.actual !== 'function') { + throw new Error('Actual is not a function') } try { - this.actual(); + this.actual() } catch (e) { - exception = e; + exception = e } if (exception) { - result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); + result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)) } - var not = this.isNot ? "not " : ""; + var not = this.isNot ? 'not ' : '' - this.message = function() { + this.message = function () { if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { - return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); + return ['Expected function ' + not + 'to throw', expected ? expected.message || expected : 'an exception', ', but it threw', exception.message || exception].join(' ') } else { - return "Expected function to throw an exception."; + return 'Expected function to throw an exception.' } - }; + } - return result; -}; + return result +} -jasmine.Matchers.Any = function(expectedClass) { - this.expectedClass = expectedClass; -}; +jasmine.Matchers.Any = function (expectedClass) { + this.expectedClass = expectedClass +} -jasmine.Matchers.Any.prototype.jasmineMatches = function(other) { +jasmine.Matchers.Any.prototype.jasmineMatches = function (other) { if (this.expectedClass == String) { - return typeof other == 'string' || other instanceof String; + return typeof other === 'string' || other instanceof String } if (this.expectedClass == Number) { - return typeof other == 'number' || other instanceof Number; + return typeof other === 'number' || other instanceof Number } if (this.expectedClass == Function) { - return typeof other == 'function' || other instanceof Function; + return typeof other === 'function' || other instanceof Function } if (this.expectedClass == Object) { - return typeof other == 'object'; + return typeof other === 'object' } - return other instanceof this.expectedClass; -}; + return other instanceof this.expectedClass +} -jasmine.Matchers.Any.prototype.jasmineToString = function() { - return ''; -}; +jasmine.Matchers.Any.prototype.jasmineToString = function () { + return '' +} jasmine.Matchers.ObjectContaining = function (sample) { - this.sample = sample; -}; + this.sample = sample +} -jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; +jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function (other, mismatchKeys, mismatchValues) { + mismatchKeys = mismatchKeys || [] + mismatchValues = mismatchValues || [] - var env = jasmine.getEnv(); + var env = jasmine.getEnv() - var hasKey = function(obj, keyName) { - return obj != null && obj[keyName] !== jasmine.undefined; - }; + var hasKey = function (obj, keyName) { + return obj != null && obj[keyName] !== jasmine.undefined + } for (var property in this.sample) { if (!hasKey(other, property) && hasKey(this.sample, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual."); + mismatchKeys.push("expected has key '" + property + "', but missing from actual.") + } else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) { + mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual.") } } - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; + return (mismatchKeys.length === 0 && mismatchValues.length === 0) +} jasmine.Matchers.ObjectContaining.prototype.jasmineToString = function () { - return ""; -}; + return '' +} // Mock setTimeout, clearTimeout // Contributed by Pivotal Computer Systems, www.pivotalsf.com -jasmine.FakeTimer = function() { - this.reset(); +jasmine.FakeTimer = function () { + this.reset() - var self = this; - self.setTimeout = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); - return self.timeoutsMade; - }; + var self = this + self.setTimeout = function (funcToCall, millis) { + self.timeoutsMade++ + self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false) + return self.timeoutsMade + } - self.setInterval = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); - return self.timeoutsMade; - }; + self.setInterval = function (funcToCall, millis) { + self.timeoutsMade++ + self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true) + return self.timeoutsMade + } - self.clearTimeout = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; + self.clearTimeout = function (timeoutKey) { + self.scheduledFunctions[timeoutKey] = jasmine.undefined + } - self.clearInterval = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; + self.clearInterval = function (timeoutKey) { + self.scheduledFunctions[timeoutKey] = jasmine.undefined + } +} -}; +jasmine.FakeTimer.prototype.reset = function () { + this.timeoutsMade = 0 + this.scheduledFunctions = {} + this.nowMillis = 0 +} -jasmine.FakeTimer.prototype.reset = function() { - this.timeoutsMade = 0; - this.scheduledFunctions = {}; - this.nowMillis = 0; -}; +jasmine.FakeTimer.prototype.tick = function (millis) { + var oldMillis = this.nowMillis + var newMillis = oldMillis + millis + this.runFunctionsWithinRange(oldMillis, newMillis) + this.nowMillis = newMillis +} -jasmine.FakeTimer.prototype.tick = function(millis) { - var oldMillis = this.nowMillis; - var newMillis = oldMillis + millis; - this.runFunctionsWithinRange(oldMillis, newMillis); - this.nowMillis = newMillis; -}; - -jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { - var scheduledFunc; - var funcsToRun = []; +jasmine.FakeTimer.prototype.runFunctionsWithinRange = function (oldMillis, nowMillis) { + var scheduledFunc + var funcsToRun = [] for (var timeoutKey in this.scheduledFunctions) { - scheduledFunc = this.scheduledFunctions[timeoutKey]; + scheduledFunc = this.scheduledFunctions[timeoutKey] if (scheduledFunc != jasmine.undefined && scheduledFunc.runAtMillis >= oldMillis && scheduledFunc.runAtMillis <= nowMillis) { - funcsToRun.push(scheduledFunc); - this.scheduledFunctions[timeoutKey] = jasmine.undefined; + funcsToRun.push(scheduledFunc) + this.scheduledFunctions[timeoutKey] = jasmine.undefined } } if (funcsToRun.length > 0) { - funcsToRun.sort(function(a, b) { - return a.runAtMillis - b.runAtMillis; - }); + funcsToRun.sort(function (a, b) { + return a.runAtMillis - b.runAtMillis + }) for (var i = 0; i < funcsToRun.length; ++i) { try { - var funcToRun = funcsToRun[i]; - this.nowMillis = funcToRun.runAtMillis; - funcToRun.funcToCall(); + var funcToRun = funcsToRun[i] + this.nowMillis = funcToRun.runAtMillis + funcToRun.funcToCall() if (funcToRun.recurring) { this.scheduleFunction(funcToRun.timeoutKey, - funcToRun.funcToCall, - funcToRun.millis, - true); + funcToRun.funcToCall, + funcToRun.millis, + true) } - } catch(e) { + } catch (e) { } } - this.runFunctionsWithinRange(oldMillis, nowMillis); + this.runFunctionsWithinRange(oldMillis, nowMillis) } -}; +} -jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { +jasmine.FakeTimer.prototype.scheduleFunction = function (timeoutKey, funcToCall, millis, recurring) { this.scheduledFunctions[timeoutKey] = { runAtMillis: this.nowMillis + millis, funcToCall: funcToCall, recurring: recurring, timeoutKey: timeoutKey, millis: millis - }; -}; + } +} /** * @namespace @@ -1667,40 +1648,40 @@ jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, jasmine.Clock = { defaultFakeTimer: new jasmine.FakeTimer(), - reset: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.reset(); + reset: function () { + jasmine.Clock.assertInstalled() + jasmine.Clock.defaultFakeTimer.reset() }, - tick: function(millis) { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.tick(millis); + tick: function (millis) { + jasmine.Clock.assertInstalled() + jasmine.Clock.defaultFakeTimer.tick(millis) }, - runFunctionsWithinRange: function(oldMillis, nowMillis) { - jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); + runFunctionsWithinRange: function (oldMillis, nowMillis) { + jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis) }, - scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { - jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); + scheduleFunction: function (timeoutKey, funcToCall, millis, recurring) { + jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring) }, - useMock: function() { + useMock: function () { if (!jasmine.Clock.isInstalled()) { - var spec = jasmine.getEnv().currentSpec; - spec.after(jasmine.Clock.uninstallMock); + var spec = jasmine.getEnv().currentSpec + spec.after(jasmine.Clock.uninstallMock) - jasmine.Clock.installMock(); + jasmine.Clock.installMock() } }, - installMock: function() { - jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; + installMock: function () { + jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer }, - uninstallMock: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.installed = jasmine.Clock.real; + uninstallMock: function () { + jasmine.Clock.assertInstalled() + jasmine.Clock.installed = jasmine.Clock.real }, real: { @@ -1710,415 +1691,413 @@ jasmine.Clock = { clearInterval: jasmine.getGlobal().clearInterval }, - assertInstalled: function() { + assertInstalled: function () { if (!jasmine.Clock.isInstalled()) { - throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); + throw new Error('Mock clock is not installed, use jasmine.Clock.useMock()') } }, - isInstalled: function() { - return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; + isInstalled: function () { + return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer }, installed: null -}; -jasmine.Clock.installed = jasmine.Clock.real; +} +jasmine.Clock.installed = jasmine.Clock.real -//else for IE support -jasmine.getGlobal().setTimeout = function(funcToCall, millis) { +// else for IE support +jasmine.getGlobal().setTimeout = function (funcToCall, millis) { if (jasmine.Clock.installed.setTimeout.apply) { - return jasmine.Clock.installed.setTimeout.apply(this, arguments); + return jasmine.Clock.installed.setTimeout.apply(this, arguments) } else { - return jasmine.Clock.installed.setTimeout(funcToCall, millis); + return jasmine.Clock.installed.setTimeout(funcToCall, millis) } -}; +} -jasmine.getGlobal().setInterval = function(funcToCall, millis) { +jasmine.getGlobal().setInterval = function (funcToCall, millis) { if (jasmine.Clock.installed.setInterval.apply) { - return jasmine.Clock.installed.setInterval.apply(this, arguments); + return jasmine.Clock.installed.setInterval.apply(this, arguments) } else { - return jasmine.Clock.installed.setInterval(funcToCall, millis); + return jasmine.Clock.installed.setInterval(funcToCall, millis) } -}; +} -jasmine.getGlobal().clearTimeout = function(timeoutKey) { +jasmine.getGlobal().clearTimeout = function (timeoutKey) { if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearTimeout.apply(this, arguments); + return jasmine.Clock.installed.clearTimeout.apply(this, arguments) } else { - return jasmine.Clock.installed.clearTimeout(timeoutKey); + return jasmine.Clock.installed.clearTimeout(timeoutKey) } -}; +} -jasmine.getGlobal().clearInterval = function(timeoutKey) { +jasmine.getGlobal().clearInterval = function (timeoutKey) { if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearInterval.apply(this, arguments); + return jasmine.Clock.installed.clearInterval.apply(this, arguments) } else { - return jasmine.Clock.installed.clearInterval(timeoutKey); + return jasmine.Clock.installed.clearInterval(timeoutKey) } -}; +} /** * @constructor */ -jasmine.MultiReporter = function() { - this.subReporters_ = []; -}; -jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); +jasmine.MultiReporter = function () { + this.subReporters_ = [] +} +jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter) -jasmine.MultiReporter.prototype.addReporter = function(reporter) { - this.subReporters_.push(reporter); +jasmine.MultiReporter.prototype.addReporter = function (reporter) { + this.subReporters_.push(reporter) }; -(function() { +(function () { var functionNames = [ - "reportRunnerStarting", - "reportRunnerResults", - "reportSuiteResults", - "reportSpecStarting", - "reportSpecResults", - "log" - ]; + 'reportRunnerStarting', + 'reportRunnerResults', + 'reportSuiteResults', + 'reportSpecStarting', + 'reportSpecResults', + 'log' + ] for (var i = 0; i < functionNames.length; i++) { - var functionName = functionNames[i]; - jasmine.MultiReporter.prototype[functionName] = (function(functionName) { - return function() { + var functionName = functionNames[i] + jasmine.MultiReporter.prototype[functionName] = (function (functionName) { + return function () { for (var j = 0; j < this.subReporters_.length; j++) { - var subReporter = this.subReporters_[j]; + var subReporter = this.subReporters_[j] if (subReporter[functionName]) { - subReporter[functionName].apply(subReporter, arguments); + subReporter[functionName].apply(subReporter, arguments) } } - }; - })(functionName); + } + })(functionName) } -})(); +})() /** * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults * * @constructor */ -jasmine.NestedResults = function() { +jasmine.NestedResults = function () { /** * The total count of results */ - this.totalCount = 0; + this.totalCount = 0 /** * Number of passed results */ - this.passedCount = 0; + this.passedCount = 0 /** * Number of failed results */ - this.failedCount = 0; + this.failedCount = 0 /** * Was this suite/spec skipped? */ - this.skipped = false; + this.skipped = false /** * @ignore */ - this.items_ = []; -}; + this.items_ = [] +} /** * Roll up the result counts. * * @param result */ -jasmine.NestedResults.prototype.rollupCounts = function(result) { - this.totalCount += result.totalCount; - this.passedCount += result.passedCount; - this.failedCount += result.failedCount; -}; +jasmine.NestedResults.prototype.rollupCounts = function (result) { + this.totalCount += result.totalCount + this.passedCount += result.passedCount + this.failedCount += result.failedCount +} /** * Adds a log message. * @param values Array of message parts which will be concatenated later. */ -jasmine.NestedResults.prototype.log = function(values) { - this.items_.push(new jasmine.MessageResult(values)); -}; +jasmine.NestedResults.prototype.log = function (values) { + this.items_.push(new jasmine.MessageResult(values)) +} /** * Getter for the results: message & results. */ -jasmine.NestedResults.prototype.getItems = function() { - return this.items_; -}; +jasmine.NestedResults.prototype.getItems = function () { + return this.items_ +} /** * Adds a result, tracking counts (total, passed, & failed) * @param {jasmine.ExpectationResult|jasmine.NestedResults} result */ -jasmine.NestedResults.prototype.addResult = function(result) { +jasmine.NestedResults.prototype.addResult = function (result) { if (result.type != 'log') { if (result.items_) { - this.rollupCounts(result); + this.rollupCounts(result) } else { - this.totalCount++; + this.totalCount++ if (result.passed()) { - this.passedCount++; + this.passedCount++ } else { - this.failedCount++; + this.failedCount++ } } } - this.items_.push(result); -}; + this.items_.push(result) +} /** * @returns {Boolean} True if everything below passed */ -jasmine.NestedResults.prototype.passed = function() { - return this.passedCount === this.totalCount; -}; +jasmine.NestedResults.prototype.passed = function () { + return this.passedCount === this.totalCount +} /** * Base class for pretty printing for expectation results. */ -jasmine.PrettyPrinter = function() { - this.ppNestLevel_ = 0; -}; +jasmine.PrettyPrinter = function () { + this.ppNestLevel_ = 0 +} /** * Formats a value in a nice, human-readable string. * * @param value */ -jasmine.PrettyPrinter.prototype.format = function(value) { - this.ppNestLevel_++; +jasmine.PrettyPrinter.prototype.format = function (value) { + this.ppNestLevel_++ try { if (value === jasmine.undefined) { - this.emitScalar('undefined'); + this.emitScalar('undefined') } else if (value === null) { - this.emitScalar('null'); + this.emitScalar('null') } else if (value === jasmine.getGlobal()) { - this.emitScalar(''); + this.emitScalar('') } else if (value.jasmineToString) { - this.emitScalar(value.jasmineToString()); + this.emitScalar(value.jasmineToString()) } else if (typeof value === 'string') { - this.emitString(value); + this.emitString(value) } else if (jasmine.isSpy(value)) { - this.emitScalar("spy on " + value.identity); + this.emitScalar('spy on ' + value.identity) } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); + this.emitScalar(value.toString()) } else if (typeof value === 'function') { - this.emitScalar('Function'); + this.emitScalar('Function') } else if (typeof value.nodeType === 'number') { - this.emitScalar('HTMLNode'); + this.emitScalar('HTMLNode') } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); + this.emitScalar('Date(' + value + ')') } else if (value.__Jasmine_been_here_before__) { - this.emitScalar(''); - } else if (jasmine.isArray_(value) || typeof value == 'object') { - value.__Jasmine_been_here_before__ = true; + this.emitScalar('') + } else if (jasmine.isArray_(value) || typeof value === 'object') { + value.__Jasmine_been_here_before__ = true if (jasmine.isArray_(value)) { - this.emitArray(value); + this.emitArray(value) } else { - this.emitObject(value); + this.emitObject(value) } - delete value.__Jasmine_been_here_before__; + delete value.__Jasmine_been_here_before__ } else { - this.emitScalar(value.toString()); + this.emitScalar(value.toString()) } } finally { - this.ppNestLevel_--; + this.ppNestLevel_-- } -}; +} -jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { +jasmine.PrettyPrinter.prototype.iterateObject = function (obj, fn) { for (var property in obj) { - if (!obj.hasOwnProperty(property)) continue; - if (property == '__Jasmine_been_here_before__') continue; - fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && - obj.__lookupGetter__(property) !== null) : false); + if (!obj.hasOwnProperty(property)) continue + if (property == '__Jasmine_been_here_before__') continue + fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && + obj.__lookupGetter__(property) !== null) : false) } -}; +} -jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_ +jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_ +jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_ +jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_ -jasmine.StringPrettyPrinter = function() { - jasmine.PrettyPrinter.call(this); +jasmine.StringPrettyPrinter = function () { + jasmine.PrettyPrinter.call(this) - this.string = ''; -}; -jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); + this.string = '' +} +jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter) -jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { - this.append(value); -}; +jasmine.StringPrettyPrinter.prototype.emitScalar = function (value) { + this.append(value) +} -jasmine.StringPrettyPrinter.prototype.emitString = function(value) { - this.append("'" + value + "'"); -}; +jasmine.StringPrettyPrinter.prototype.emitString = function (value) { + this.append("'" + value + "'") +} -jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { +jasmine.StringPrettyPrinter.prototype.emitArray = function (array) { if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) { - this.append("Array"); - return; + this.append('Array') + return } - this.append('[ '); + this.append('[ ') for (var i = 0; i < array.length; i++) { if (i > 0) { - this.append(', '); + this.append(', ') } - this.format(array[i]); + this.format(array[i]) } - this.append(' ]'); -}; + this.append(' ]') +} -jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { +jasmine.StringPrettyPrinter.prototype.emitObject = function (obj) { if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) { - this.append("Object"); - return; + this.append('Object') + return } - var self = this; - this.append('{ '); - var first = true; + var self = this + this.append('{ ') + var first = true - this.iterateObject(obj, function(property, isGetter) { + this.iterateObject(obj, function (property, isGetter) { if (first) { - first = false; + first = false } else { - self.append(', '); + self.append(', ') } - self.append(property); - self.append(' : '); + self.append(property) + self.append(' : ') if (isGetter) { - self.append(''); + self.append('') } else { - self.format(obj[property]); + self.format(obj[property]) } - }); + }) - this.append(' }'); -}; + this.append(' }') +} -jasmine.StringPrettyPrinter.prototype.append = function(value) { - this.string += value; -}; -jasmine.Queue = function(env) { - this.env = env; +jasmine.StringPrettyPrinter.prototype.append = function (value) { + this.string += value +} +jasmine.Queue = function (env) { + this.env = env // parallel to blocks. each true value in this array means the block will // get executed even if we abort - this.ensured = []; - this.blocks = []; - this.running = false; - this.index = 0; - this.offset = 0; - this.abort = false; -}; - -jasmine.Queue.prototype.addBefore = function(block, ensure) { + this.ensured = [] + this.blocks = [] + this.running = false + this.index = 0 + this.offset = 0 + this.abort = false +} + +jasmine.Queue.prototype.addBefore = function (block, ensure) { if (ensure === jasmine.undefined) { - ensure = false; + ensure = false } - this.blocks.unshift(block); - this.ensured.unshift(ensure); -}; + this.blocks.unshift(block) + this.ensured.unshift(ensure) +} -jasmine.Queue.prototype.add = function(block, ensure) { +jasmine.Queue.prototype.add = function (block, ensure) { if (ensure === jasmine.undefined) { - ensure = false; + ensure = false } - this.blocks.push(block); - this.ensured.push(ensure); -}; + this.blocks.push(block) + this.ensured.push(ensure) +} -jasmine.Queue.prototype.insertNext = function(block, ensure) { +jasmine.Queue.prototype.insertNext = function (block, ensure) { if (ensure === jasmine.undefined) { - ensure = false; + ensure = false } - this.ensured.splice((this.index + this.offset + 1), 0, ensure); - this.blocks.splice((this.index + this.offset + 1), 0, block); - this.offset++; -}; + this.ensured.splice((this.index + this.offset + 1), 0, ensure) + this.blocks.splice((this.index + this.offset + 1), 0, block) + this.offset++ +} -jasmine.Queue.prototype.start = function(onComplete) { - this.running = true; - this.onComplete = onComplete; - this.next_(); -}; +jasmine.Queue.prototype.start = function (onComplete) { + this.running = true + this.onComplete = onComplete + this.next_() +} -jasmine.Queue.prototype.isRunning = function() { - return this.running; -}; +jasmine.Queue.prototype.isRunning = function () { + return this.running +} -jasmine.Queue.LOOP_DONT_RECURSE = true; +jasmine.Queue.LOOP_DONT_RECURSE = true -jasmine.Queue.prototype.next_ = function() { - var self = this; - var goAgain = true; +jasmine.Queue.prototype.next_ = function () { + var self = this + var goAgain = true while (goAgain) { - goAgain = false; - + goAgain = false + if (self.index < self.blocks.length && !(this.abort && !this.ensured[self.index])) { - var calledSynchronously = true; - var completedSynchronously = false; + var calledSynchronously = true + var completedSynchronously = false var onComplete = function () { if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { - completedSynchronously = true; - return; + completedSynchronously = true + return } if (self.blocks[self.index].abort) { - self.abort = true; + self.abort = true } - self.offset = 0; - self.index++; + self.offset = 0 + self.index++ - var now = new Date().getTime(); + var now = new Date().getTime() if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { - self.env.lastUpdate = now; - self.env.setTimeout(function() { - self.next_(); - }, 0); + self.env.lastUpdate = now + self.env.setTimeout(function () { + self.next_() + }, 0) } else { if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { - goAgain = true; + goAgain = true } else { - self.next_(); + self.next_() } } - }; - self.blocks[self.index].execute(onComplete); + } + self.blocks[self.index].execute(onComplete) - calledSynchronously = false; + calledSynchronously = false if (completedSynchronously) { - onComplete(); + onComplete() } - } else { - self.running = false; + self.running = false if (self.onComplete) { - self.onComplete(); + self.onComplete() } } } -}; +} -jasmine.Queue.prototype.results = function() { - var results = new jasmine.NestedResults(); +jasmine.Queue.prototype.results = function () { + var results = new jasmine.NestedResults() for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].results) { - results.addResult(this.blocks[i].results()); + results.addResult(this.blocks[i].results()) } } - return results; -}; - + return results +} /** * Runner @@ -2126,77 +2105,76 @@ jasmine.Queue.prototype.results = function() { * @constructor * @param {jasmine.Env} env */ -jasmine.Runner = function(env) { - var self = this; - self.env = env; - self.queue = new jasmine.Queue(env); - self.before_ = []; - self.after_ = []; - self.suites_ = []; -}; - -jasmine.Runner.prototype.execute = function() { - var self = this; +jasmine.Runner = function (env) { + var self = this + self.env = env + self.queue = new jasmine.Queue(env) + self.before_ = [] + self.after_ = [] + self.suites_ = [] +} + +jasmine.Runner.prototype.execute = function () { + var self = this if (self.env.reporter.reportRunnerStarting) { - self.env.reporter.reportRunnerStarting(this); + self.env.reporter.reportRunnerStarting(this) } self.queue.start(function () { - self.finishCallback(); - }); -}; - -jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.splice(0,0,beforeEachFunction); -}; + self.finishCallback() + }) +} -jasmine.Runner.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.splice(0,0,afterEachFunction); -}; +jasmine.Runner.prototype.beforeEach = function (beforeEachFunction) { + beforeEachFunction.typeName = 'beforeEach' + this.before_.splice(0, 0, beforeEachFunction) +} +jasmine.Runner.prototype.afterEach = function (afterEachFunction) { + afterEachFunction.typeName = 'afterEach' + this.after_.splice(0, 0, afterEachFunction) +} -jasmine.Runner.prototype.finishCallback = function() { - this.env.reporter.reportRunnerResults(this); -}; +jasmine.Runner.prototype.finishCallback = function () { + this.env.reporter.reportRunnerResults(this) +} -jasmine.Runner.prototype.addSuite = function(suite) { - this.suites_.push(suite); -}; +jasmine.Runner.prototype.addSuite = function (suite) { + this.suites_.push(suite) +} -jasmine.Runner.prototype.add = function(block) { +jasmine.Runner.prototype.add = function (block) { if (block instanceof jasmine.Suite) { - this.addSuite(block); + this.addSuite(block) } - this.queue.add(block); -}; + this.queue.add(block) +} jasmine.Runner.prototype.specs = function () { - var suites = this.suites(); - var specs = []; + var suites = this.suites() + var specs = [] for (var i = 0; i < suites.length; i++) { - specs = specs.concat(suites[i].specs()); + specs = specs.concat(suites[i].specs()) } - return specs; -}; + return specs +} -jasmine.Runner.prototype.suites = function() { - return this.suites_; -}; +jasmine.Runner.prototype.suites = function () { + return this.suites_ +} -jasmine.Runner.prototype.topLevelSuites = function() { - var topLevelSuites = []; +jasmine.Runner.prototype.topLevelSuites = function () { + var topLevelSuites = [] for (var i = 0; i < this.suites_.length; i++) { if (!this.suites_[i].parentSuite) { - topLevelSuites.push(this.suites_[i]); + topLevelSuites.push(this.suites_[i]) } } - return topLevelSuites; -}; + return topLevelSuites +} -jasmine.Runner.prototype.results = function() { - return this.queue.results(); -}; +jasmine.Runner.prototype.results = function () { + return this.queue.results() +} /** * Internal representation of a Jasmine specification, or test. * @@ -2205,72 +2183,71 @@ jasmine.Runner.prototype.results = function() { * @param {jasmine.Suite} suite * @param {String} description */ -jasmine.Spec = function(env, suite, description) { +jasmine.Spec = function (env, suite, description) { if (!env) { - throw new Error('jasmine.Env() required'); + throw new Error('jasmine.Env() required') } if (!suite) { - throw new Error('jasmine.Suite() required'); + throw new Error('jasmine.Suite() required') } - var spec = this; - spec.id = env.nextSpecId ? env.nextSpecId() : null; - spec.env = env; - spec.suite = suite; - spec.description = description; - spec.queue = new jasmine.Queue(env); - - spec.afterCallbacks = []; - spec.spies_ = []; + var spec = this + spec.id = env.nextSpecId ? env.nextSpecId() : null + spec.env = env + spec.suite = suite + spec.description = description + spec.queue = new jasmine.Queue(env) - spec.results_ = new jasmine.NestedResults(); - spec.results_.description = description; - spec.matchersClass = null; -}; + spec.afterCallbacks = [] + spec.spies_ = [] -jasmine.Spec.prototype.getFullName = function() { - return this.suite.getFullName() + ' ' + this.description + '.'; -}; + spec.results_ = new jasmine.NestedResults() + spec.results_.description = description + spec.matchersClass = null +} +jasmine.Spec.prototype.getFullName = function () { + return this.suite.getFullName() + ' ' + this.description + '.' +} -jasmine.Spec.prototype.results = function() { - return this.results_; -}; +jasmine.Spec.prototype.results = function () { + return this.results_ +} /** * All parameters are pretty-printed and concatenated together, then written to the spec's output. * * Be careful not to leave calls to jasmine.log in production code. */ -jasmine.Spec.prototype.log = function() { - return this.results_.log(arguments); -}; +jasmine.Spec.prototype.log = function () { + return this.results_.log(arguments) +} jasmine.Spec.prototype.runs = function (func) { - var block = new jasmine.Block(this.env, func, this); - this.addToQueue(block); - return this; -}; + var block = new jasmine.Block(this.env, func, this) + this.addToQueue(block) + return this +} jasmine.Spec.prototype.addToQueue = function (block) { if (this.queue.isRunning()) { - this.queue.insertNext(block); + this.queue.insertNext(block) } else { - this.queue.add(block); + this.queue.add(block) } -}; +} /** * @param {jasmine.ExpectationResult} result */ -jasmine.Spec.prototype.addMatcherResult = function(result) { - this.results_.addResult(result); -}; +jasmine.Spec.prototype.addMatcherResult = function (result) { + this.results_.addResult(result) +} -jasmine.Spec.prototype.expect = function(actual) { - var positive = new (this.getMatchersClass_())(this.env, actual, this); - positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); - return positive; -}; +jasmine.Spec.prototype.expect = function (actual) { + var positive = new (this.getMatchersClass_())(this.env, actual, this) + positive.not = new (this.getMatchersClass_())(this.env, actual, this, true) + return positive +} /** * Waits a fixed time period before moving to the next block. @@ -2278,11 +2255,11 @@ jasmine.Spec.prototype.expect = function(actual) { * @deprecated Use waitsFor() instead * @param {Number} timeout milliseconds to wait */ -jasmine.Spec.prototype.waits = function(timeout) { - var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); - this.addToQueue(waitsFunc); - return this; -}; +jasmine.Spec.prototype.waits = function (timeout) { + var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this) + this.addToQueue(waitsFunc) + return this +} /** * Waits for the latchFunction to return true before proceeding to the next block. @@ -2291,154 +2268,154 @@ jasmine.Spec.prototype.waits = function(timeout) { * @param {String} optional_timeoutMessage * @param {Number} optional_timeout */ -jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - var latchFunction_ = null; - var optional_timeoutMessage_ = null; - var optional_timeout_ = null; +jasmine.Spec.prototype.waitsFor = function (latchFunction, optional_timeoutMessage, optional_timeout) { + var latchFunction_ = null + var optional_timeoutMessage_ = null + var optional_timeout_ = null for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i]; + var arg = arguments[i] switch (typeof arg) { case 'function': - latchFunction_ = arg; - break; + latchFunction_ = arg + break case 'string': - optional_timeoutMessage_ = arg; - break; + optional_timeoutMessage_ = arg + break case 'number': - optional_timeout_ = arg; - break; + optional_timeout_ = arg + break } } - var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); - this.addToQueue(waitsForFunc); - return this; -}; + var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this) + this.addToQueue(waitsForFunc) + return this +} jasmine.Spec.prototype.fail = function (e) { var expectationResult = new jasmine.ExpectationResult({ passed: false, message: e ? jasmine.util.formatException(e) : 'Exception', trace: { stack: e.stack } - }); - this.results_.addResult(expectationResult); -}; - -jasmine.Spec.prototype.getMatchersClass_ = function() { - return this.matchersClass || this.env.matchersClass; -}; - -jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { - var parent = this.getMatchersClass_(); - var newMatchersClass = function() { - parent.apply(this, arguments); - }; - jasmine.util.inherit(newMatchersClass, parent); - jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); - this.matchersClass = newMatchersClass; -}; - -jasmine.Spec.prototype.finishCallback = function() { - this.env.reporter.reportSpecResults(this); -}; - -jasmine.Spec.prototype.finish = function(onComplete) { - this.removeAllSpies(); - this.finishCallback(); + }) + this.results_.addResult(expectationResult) +} + +jasmine.Spec.prototype.getMatchersClass_ = function () { + return this.matchersClass || this.env.matchersClass +} + +jasmine.Spec.prototype.addMatchers = function (matchersPrototype) { + var parent = this.getMatchersClass_() + var newMatchersClass = function () { + parent.apply(this, arguments) + } + jasmine.util.inherit(newMatchersClass, parent) + jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass) + this.matchersClass = newMatchersClass +} + +jasmine.Spec.prototype.finishCallback = function () { + this.env.reporter.reportSpecResults(this) +} + +jasmine.Spec.prototype.finish = function (onComplete) { + this.removeAllSpies() + this.finishCallback() if (onComplete) { - onComplete(); + onComplete() } -}; +} -jasmine.Spec.prototype.after = function(doAfter) { +jasmine.Spec.prototype.after = function (doAfter) { if (this.queue.isRunning()) { - this.queue.add(new jasmine.Block(this.env, doAfter, this), true); + this.queue.add(new jasmine.Block(this.env, doAfter, this), true) } else { - this.afterCallbacks.unshift(doAfter); + this.afterCallbacks.unshift(doAfter) } -}; +} -jasmine.Spec.prototype.execute = function(onComplete) { - var spec = this; +jasmine.Spec.prototype.execute = function (onComplete) { + var spec = this if (!spec.env.specFilter(spec)) { - spec.results_.skipped = true; - spec.finish(onComplete); - return; + spec.results_.skipped = true + spec.finish(onComplete) + return } - this.env.reporter.reportSpecStarting(this); + this.env.reporter.reportSpecStarting(this) - spec.env.currentSpec = spec; + spec.env.currentSpec = spec - spec.addBeforesAndAftersToQueue(); + spec.addBeforesAndAftersToQueue() spec.queue.start(function () { - spec.finish(onComplete); - }); -}; + spec.finish(onComplete) + }) +} -jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { - var runner = this.env.currentRunner(); - var i; +jasmine.Spec.prototype.addBeforesAndAftersToQueue = function () { + var runner = this.env.currentRunner() + var i for (var suite = this.suite; suite; suite = suite.parentSuite) { for (i = 0; i < suite.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); + this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)) } } for (i = 0; i < runner.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); + this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)) } for (i = 0; i < this.afterCallbacks.length; i++) { - this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this), true); + this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this), true) } for (suite = this.suite; suite; suite = suite.parentSuite) { for (i = 0; i < suite.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, suite.after_[i], this), true); + this.queue.add(new jasmine.Block(this.env, suite.after_[i], this), true) } } for (i = 0; i < runner.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, runner.after_[i], this), true); + this.queue.add(new jasmine.Block(this.env, runner.after_[i], this), true) } -}; +} -jasmine.Spec.prototype.explodes = function() { - throw 'explodes function should not have been called'; -}; +jasmine.Spec.prototype.explodes = function () { + throw 'explodes function should not have been called' +} -jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { +jasmine.Spec.prototype.spyOn = function (obj, methodName, ignoreMethodDoesntExist) { if (obj == jasmine.undefined) { - throw "spyOn could not find an object to spy upon for " + methodName + "()"; + throw 'spyOn could not find an object to spy upon for ' + methodName + '()' } if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { - throw methodName + '() method does not exist'; + throw methodName + '() method does not exist' } if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { - throw new Error(methodName + ' has already been spied upon'); + throw new Error(methodName + ' has already been spied upon') } - var spyObj = jasmine.createSpy(methodName); + var spyObj = jasmine.createSpy(methodName) - this.spies_.push(spyObj); - spyObj.baseObj = obj; - spyObj.methodName = methodName; - spyObj.originalValue = obj[methodName]; + this.spies_.push(spyObj) + spyObj.baseObj = obj + spyObj.methodName = methodName + spyObj.originalValue = obj[methodName] - obj[methodName] = spyObj; + obj[methodName] = spyObj - return spyObj; -}; + return spyObj +} -jasmine.Spec.prototype.removeAllSpies = function() { +jasmine.Spec.prototype.removeAllSpies = function () { for (var i = 0; i < this.spies_.length; i++) { - var spy = this.spies_[i]; - spy.baseObj[spy.methodName] = spy.originalValue; + var spy = this.spies_[i] + spy.baseObj[spy.methodName] = spy.originalValue } - this.spies_ = []; -}; + this.spies_ = [] +} /** * Internal representation of a Jasmine suite. @@ -2449,94 +2426,94 @@ jasmine.Spec.prototype.removeAllSpies = function() { * @param {Function} specDefinitions * @param {jasmine.Suite} parentSuite */ -jasmine.Suite = function(env, description, specDefinitions, parentSuite) { - var self = this; - self.id = env.nextSuiteId ? env.nextSuiteId() : null; - self.description = description; - self.queue = new jasmine.Queue(env); - self.parentSuite = parentSuite; - self.env = env; - self.before_ = []; - self.after_ = []; - self.children_ = []; - self.suites_ = []; - self.specs_ = []; -}; - -jasmine.Suite.prototype.getFullName = function() { - var fullName = this.description; +jasmine.Suite = function (env, description, specDefinitions, parentSuite) { + var self = this + self.id = env.nextSuiteId ? env.nextSuiteId() : null + self.description = description + self.queue = new jasmine.Queue(env) + self.parentSuite = parentSuite + self.env = env + self.before_ = [] + self.after_ = [] + self.children_ = [] + self.suites_ = [] + self.specs_ = [] +} + +jasmine.Suite.prototype.getFullName = function () { + var fullName = this.description for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { - fullName = parentSuite.description + ' ' + fullName; + fullName = parentSuite.description + ' ' + fullName } - return fullName; -}; + return fullName +} -jasmine.Suite.prototype.finish = function(onComplete) { - this.env.reporter.reportSuiteResults(this); - this.finished = true; - if (typeof(onComplete) == 'function') { - onComplete(); +jasmine.Suite.prototype.finish = function (onComplete) { + this.env.reporter.reportSuiteResults(this) + this.finished = true + if (typeof (onComplete) === 'function') { + onComplete() } -}; +} -jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.unshift(beforeEachFunction); -}; +jasmine.Suite.prototype.beforeEach = function (beforeEachFunction) { + beforeEachFunction.typeName = 'beforeEach' + this.before_.unshift(beforeEachFunction) +} -jasmine.Suite.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.unshift(afterEachFunction); -}; +jasmine.Suite.prototype.afterEach = function (afterEachFunction) { + afterEachFunction.typeName = 'afterEach' + this.after_.unshift(afterEachFunction) +} -jasmine.Suite.prototype.results = function() { - return this.queue.results(); -}; +jasmine.Suite.prototype.results = function () { + return this.queue.results() +} -jasmine.Suite.prototype.add = function(suiteOrSpec) { - this.children_.push(suiteOrSpec); +jasmine.Suite.prototype.add = function (suiteOrSpec) { + this.children_.push(suiteOrSpec) if (suiteOrSpec instanceof jasmine.Suite) { - this.suites_.push(suiteOrSpec); - this.env.currentRunner().addSuite(suiteOrSpec); + this.suites_.push(suiteOrSpec) + this.env.currentRunner().addSuite(suiteOrSpec) } else { - this.specs_.push(suiteOrSpec); + this.specs_.push(suiteOrSpec) } - this.queue.add(suiteOrSpec); -}; + this.queue.add(suiteOrSpec) +} -jasmine.Suite.prototype.specs = function() { - return this.specs_; -}; +jasmine.Suite.prototype.specs = function () { + return this.specs_ +} -jasmine.Suite.prototype.suites = function() { - return this.suites_; -}; +jasmine.Suite.prototype.suites = function () { + return this.suites_ +} -jasmine.Suite.prototype.children = function() { - return this.children_; -}; +jasmine.Suite.prototype.children = function () { + return this.children_ +} -jasmine.Suite.prototype.execute = function(onComplete) { - var self = this; +jasmine.Suite.prototype.execute = function (onComplete) { + var self = this this.queue.start(function () { - self.finish(onComplete); - }); -}; -jasmine.WaitsBlock = function(env, timeout, spec) { - this.timeout = timeout; - jasmine.Block.call(this, env, null, spec); -}; + self.finish(onComplete) + }) +} +jasmine.WaitsBlock = function (env, timeout, spec) { + this.timeout = timeout + jasmine.Block.call(this, env, null, spec) +} -jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); +jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block) jasmine.WaitsBlock.prototype.execute = function (onComplete) { if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); + this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...') } this.env.setTimeout(function () { - onComplete(); - }, this.timeout); -}; + onComplete() + }, this.timeout) +} /** * A block which waits for some condition to become true, with timeout. * @@ -2548,53 +2525,53 @@ jasmine.WaitsBlock.prototype.execute = function (onComplete) { * @param {String} message The message to display if the desired condition hasn't been met within the given time period. * @param {jasmine.Spec} spec The Jasmine spec. */ -jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { - this.timeout = timeout || env.defaultTimeoutInterval; - this.latchFunction = latchFunction; - this.message = message; - this.totalTimeSpentWaitingForLatch = 0; - jasmine.Block.call(this, env, null, spec); -}; -jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); +jasmine.WaitsForBlock = function (env, timeout, latchFunction, message, spec) { + this.timeout = timeout || env.defaultTimeoutInterval + this.latchFunction = latchFunction + this.message = message + this.totalTimeSpentWaitingForLatch = 0 + jasmine.Block.call(this, env, null, spec) +} +jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block) -jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; +jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10 -jasmine.WaitsForBlock.prototype.execute = function(onComplete) { +jasmine.WaitsForBlock.prototype.execute = function (onComplete) { if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); + this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')) } - var latchFunctionResult; + var latchFunctionResult try { - latchFunctionResult = this.latchFunction.apply(this.spec); + latchFunctionResult = this.latchFunction.apply(this.spec) } catch (e) { - this.spec.fail(e); - onComplete(); - return; + this.spec.fail(e) + onComplete() + return } if (latchFunctionResult) { - onComplete(); + onComplete() } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { - var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); + var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen') this.spec.fail({ name: 'timeout', message: message - }); + }) - this.abort = true; - onComplete(); + this.abort = true + onComplete() } else { - this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; - var self = this; - this.env.setTimeout(function() { - self.execute(onComplete); - }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); - } -}; - -jasmine.version_= { - "major": 1, - "minor": 3, - "build": 1, - "revision": 1354556913 -}; + this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT + var self = this + this.env.setTimeout(function () { + self.execute(onComplete) + }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT) + } +} + +jasmine.version_ = { + major: 1, + minor: 3, + build: 1, + revision: 1354556913 +} diff --git a/examples/jasmine/spec/PlayerSpec.js b/examples/jasmine/spec/PlayerSpec.js index 79f1022..9f34547 100644 --- a/examples/jasmine/spec/PlayerSpec.js +++ b/examples/jasmine/spec/PlayerSpec.js @@ -1,58 +1,58 @@ -describe("Player", function() { - var player; - var song; +describe('Player', function () { + var player + var song - beforeEach(function() { - player = new Player(); - song = new Song(); - }); + beforeEach(function () { + player = new Player() + song = new Song() + }) - it("should be able to play a Song", function() { - player.play(song); - expect(player.currentlyPlayingSong).toEqual(song); + it('should be able to play a Song', function () { + player.play(song) + expect(player.currentlyPlayingSong).toEqual(song) - //demonstrates use of custom matcher - expect(player).toBePlaying(song); - }); + // demonstrates use of custom matcher + expect(player).toBePlaying(song) + }) - describe("when song has been paused", function() { - beforeEach(function() { - player.play(song); - player.pause(); - }); + describe('when song has been paused', function () { + beforeEach(function () { + player.play(song) + player.pause() + }) - it("should indicate that the song is currently paused", function() { - expect(player.isPlaying).toBeFalsy(); + it('should indicate that the song is currently paused', function () { + expect(player.isPlaying).toBeFalsy() // demonstrates use of 'not' with a custom matcher - expect(player).not.toBePlaying(song); - }); + expect(player).not.toBePlaying(song) + }) - it("should be possible to resume", function() { - player.resume(); - expect(player.isPlaying).toBeTruthy(); - expect(player.currentlyPlayingSong).toEqual(song); - }); - }); + it('should be possible to resume', function () { + player.resume() + expect(player.isPlaying).toBeTruthy() + expect(player.currentlyPlayingSong).toEqual(song) + }) + }) // demonstrates use of spies to intercept and test method calls - it("tells the current song if the user has made it a favorite", function() { - spyOn(song, 'persistFavoriteStatus'); - - player.play(song); - player.makeFavorite(); - - expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true); - }); - - //demonstrates use of expected exceptions - describe("#resume", function() { - it("should throw an exception if song is already playing", function() { - player.play(song); - - expect(function() { - player.resume(); - }).toThrow("song is already playing"); - }); - }); -}); \ No newline at end of file + it('tells the current song if the user has made it a favorite', function () { + spyOn(song, 'persistFavoriteStatus') + + player.play(song) + player.makeFavorite() + + expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true) + }) + + // demonstrates use of expected exceptions + describe('#resume', function () { + it('should throw an exception if song is already playing', function () { + player.play(song) + + expect(function () { + player.resume() + }).toThrow('song is already playing') + }) + }) +}) diff --git a/examples/jasmine/spec/SpecHelper.js b/examples/jasmine/spec/SpecHelper.js index e9b8284..b391460 100644 --- a/examples/jasmine/spec/SpecHelper.js +++ b/examples/jasmine/spec/SpecHelper.js @@ -1,9 +1,9 @@ -beforeEach(function() { +beforeEach(function () { this.addMatchers({ - toBePlaying: function(expectedSong) { - var player = this.actual; - return player.currentlyPlayingSong === expectedSong && - player.isPlaying; + toBePlaying: function (expectedSong) { + var player = this.actual + return player.currentlyPlayingSong === expectedSong && + player.isPlaying } - }); -}); + }) +}) diff --git a/examples/jasmine/src/Player.js b/examples/jasmine/src/Player.js index fcce826..a387a72 100644 --- a/examples/jasmine/src/Player.js +++ b/examples/jasmine/src/Player.js @@ -1,22 +1,22 @@ -function Player() { +function Player () { +} +Player.prototype.play = function (song) { + this.currentlyPlayingSong = song + this.isPlaying = true } -Player.prototype.play = function(song) { - this.currentlyPlayingSong = song; - this.isPlaying = true; -}; -Player.prototype.pause = function() { - this.isPlaying = false; -}; +Player.prototype.pause = function () { + this.isPlaying = false +} -Player.prototype.resume = function() { +Player.prototype.resume = function () { if (this.isPlaying) { - throw new Error("song is already playing"); + throw new Error('song is already playing') } - this.isPlaying = true; -}; + this.isPlaying = true +} -Player.prototype.makeFavorite = function() { - this.currentlyPlayingSong.persistFavoriteStatus(true); -}; \ No newline at end of file +Player.prototype.makeFavorite = function () { + this.currentlyPlayingSong.persistFavoriteStatus(true) +} diff --git a/examples/jasmine/src/Song.js b/examples/jasmine/src/Song.js index a8a3f2d..05baa85 100644 --- a/examples/jasmine/src/Song.js +++ b/examples/jasmine/src/Song.js @@ -1,7 +1,7 @@ -function Song() { +function Song () { } -Song.prototype.persistFavoriteStatus = function(value) { +Song.prototype.persistFavoriteStatus = function (value) { // something complicated - throw new Error("not yet implemented"); -}; \ No newline at end of file + throw new Error('not yet implemented') +} diff --git a/examples/mocha/Gruntfile.js b/examples/mocha/Gruntfile.js index 3711917..af5c8c8 100644 --- a/examples/mocha/Gruntfile.js +++ b/examples/mocha/Gruntfile.js @@ -17,7 +17,7 @@ module.exports = function (grunt) { browserName: 'internet explorer', platform: 'VISTA', version: '9' - }]; + }] grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), @@ -47,10 +47,10 @@ module.exports = function (grunt) { } }, watch: {} - }); + }) - grunt.loadNpmTasks('grunt-contrib-connect'); - grunt.loadNpmTasks('grunt-saucelabs'); + grunt.loadNpmTasks('grunt-contrib-connect') + grunt.loadNpmTasks('grunt-saucelabs') - grunt.registerTask('default', ['connect', 'saucelabs-mocha']); -}; \ No newline at end of file + grunt.registerTask('default', ['connect', 'saucelabs-mocha']) +} diff --git a/examples/mocha/lib/expect/index.js b/examples/mocha/lib/expect/index.js index b1e921d..09ea0f9 100644 --- a/examples/mocha/lib/expect/index.js +++ b/examples/mocha/lib/expect/index.js @@ -1,34 +1,33 @@ (function (global, module) { - - var exports = module.exports; + var exports = module.exports /** * Exports. */ - module.exports = expect; - expect.Assertion = Assertion; + module.exports = expect + expect.Assertion = Assertion /** * Exports version. */ - expect.version = '0.3.1'; + expect.version = '0.3.1' /** * Possible assertion flags. */ var flags = { - not: ['to', 'be', 'have', 'include', 'only'] - , to: ['be', 'have', 'include', 'only', 'not'] - , only: ['have'] - , have: ['own'] - , be: ['an'] - }; + not: ['to', 'be', 'have', 'include', 'only'], + to: ['be', 'have', 'include', 'only', 'not'], + only: ['have'], + have: ['own'], + be: ['an'] + } function expect (obj) { - return new Assertion(obj); + return new Assertion(obj) } /** @@ -38,44 +37,44 @@ */ function Assertion (obj, flag, parent) { - this.obj = obj; - this.flags = {}; + this.obj = obj + this.flags = {} if (undefined != parent) { - this.flags[flag] = true; + this.flags[flag] = true for (var i in parent.flags) { if (parent.flags.hasOwnProperty(i)) { - this.flags[i] = true; + this.flags[i] = true } } } var $flags = flag ? flags[flag] : keys(flags) - , self = this; + var self = this if ($flags) { for (var i = 0, l = $flags.length; i < l; i++) { // avoid recursion - if (this.flags[$flags[i]]) continue; + if (this.flags[$flags[i]]) continue var name = $flags[i] - , assertion = new Assertion(this.obj, name, this) + var assertion = new Assertion(this.obj, name, this) - if ('function' == typeof Assertion.prototype[name]) { + if (typeof Assertion.prototype[name] === 'function') { // clone the function, make sure we dont touch the prot reference - var old = this[name]; + var old = this[name] this[name] = function () { - return old.apply(self, arguments); - }; + return old.apply(self, arguments) + } for (var fn in Assertion.prototype) { if (Assertion.prototype.hasOwnProperty(fn) && fn != name) { - this[name][fn] = bind(assertion[fn], assertion); + this[name][fn] = bind(assertion[fn], assertion) } } } else { - this[name] = assertion; + this[name] = assertion } } } @@ -89,21 +88,21 @@ Assertion.prototype.assert = function (truth, msg, error, expected) { var msg = this.flags.not ? error : msg - , ok = this.flags.not ? !truth : truth - , err; + var ok = this.flags.not ? !truth : truth + var err if (!ok) { - err = new Error(msg.call(this)); + err = new Error(msg.call(this)) if (arguments.length > 3) { - err.actual = this.obj; - err.expected = expected; - err.showDiff = true; + err.actual = this.obj + err.expected = expected + err.showDiff = true } - throw err; + throw err } - this.and = new Assertion(this.obj); - }; + this.and = new Assertion(this.obj) + } /** * Check if the value is truthy @@ -113,10 +112,10 @@ Assertion.prototype.ok = function () { this.assert( - !!this.obj - , function(){ return 'expected ' + i(this.obj) + ' to be truthy' } - , function(){ return 'expected ' + i(this.obj) + ' to be falsy' }); - }; + !!this.obj + , function () { return 'expected ' + i(this.obj) + ' to be truthy' } + , function () { return 'expected ' + i(this.obj) + ' to be falsy' }) + } /** * Creates an anonymous function which calls fn with arguments. @@ -124,12 +123,12 @@ * @api public */ - Assertion.prototype.withArgs = function() { - expect(this.obj).to.be.a('function'); - var fn = this.obj; - var args = Array.prototype.slice.call(arguments); - return expect(function() { fn.apply(null, args); }); - }; + Assertion.prototype.withArgs = function () { + expect(this.obj).to.be.a('function') + var fn = this.obj + var args = Array.prototype.slice.call(arguments) + return expect(function () { fn.apply(null, args) }) + } /** * Assert that the function throws. @@ -140,39 +139,39 @@ Assertion.prototype.throwError = Assertion.prototype.throwException = function (fn) { - expect(this.obj).to.be.a('function'); + expect(this.obj).to.be.a('function') var thrown = false - , not = this.flags.not; + var not = this.flags.not try { - this.obj(); + this.obj() } catch (e) { if (isRegExp(fn)) { - var subject = 'string' == typeof e ? e : e.message; + var subject = typeof e === 'string' ? e : e.message if (not) { - expect(subject).to.not.match(fn); + expect(subject).to.not.match(fn) } else { - expect(subject).to.match(fn); + expect(subject).to.match(fn) } - } else if ('function' == typeof fn) { - fn(e); + } else if (typeof fn === 'function') { + fn(e) } - thrown = true; + thrown = true } if (isRegExp(fn) && not) { // in the presence of a matcher, ensure the `not` only applies to // the matching. - this.flags.not = false; + this.flags.not = false } - var name = this.obj.name || 'fn'; + var name = this.obj.name || 'fn' this.assert( - thrown - , function(){ return 'expected ' + name + ' to throw an exception' } - , function(){ return 'expected ' + name + ' not to throw an exception' }); - }; + thrown + , function () { return 'expected ' + name + ' to throw an exception' } + , function () { return 'expected ' + name + ' not to throw an exception' }) + } /** * Checks if the array is empty. @@ -181,29 +180,29 @@ */ Assertion.prototype.empty = function () { - var expectation; + var expectation - if ('object' == typeof this.obj && null !== this.obj && !isArray(this.obj)) { - if ('number' == typeof this.obj.length) { - expectation = !this.obj.length; + if (typeof this.obj === 'object' && this.obj !== null && !isArray(this.obj)) { + if (typeof this.obj.length === 'number') { + expectation = !this.obj.length } else { - expectation = !keys(this.obj).length; + expectation = !keys(this.obj).length } } else { - if ('string' != typeof this.obj) { - expect(this.obj).to.be.an('object'); + if (typeof this.obj !== 'string') { + expect(this.obj).to.be.an('object') } - expect(this.obj).to.have.property('length'); - expectation = !this.obj.length; + expect(this.obj).to.have.property('length') + expectation = !this.obj.length } this.assert( - expectation - , function(){ return 'expected ' + i(this.obj) + ' to be empty' } - , function(){ return 'expected ' + i(this.obj) + ' to not be empty' }); - return this; - }; + expectation + , function () { return 'expected ' + i(this.obj) + ' to be empty' } + , function () { return 'expected ' + i(this.obj) + ' to not be empty' }) + return this + } /** * Checks if the obj exactly equals another. @@ -214,11 +213,11 @@ Assertion.prototype.be = Assertion.prototype.equal = function (obj) { this.assert( - obj === this.obj - , function(){ return 'expected ' + i(this.obj) + ' to equal ' + i(obj) } - , function(){ return 'expected ' + i(this.obj) + ' to not equal ' + i(obj) }); - return this; - }; + obj === this.obj + , function () { return 'expected ' + i(this.obj) + ' to equal ' + i(obj) } + , function () { return 'expected ' + i(this.obj) + ' to not equal ' + i(obj) }) + return this + } /** * Checks if the obj sortof equals another. @@ -228,12 +227,12 @@ Assertion.prototype.eql = function (obj) { this.assert( - expect.eql(this.obj, obj) - , function(){ return 'expected ' + i(this.obj) + ' to sort of equal ' + i(obj) } - , function(){ return 'expected ' + i(this.obj) + ' to sort of not equal ' + i(obj) } - , obj); - return this; - }; + expect.eql(this.obj, obj) + , function () { return 'expected ' + i(this.obj) + ' to sort of equal ' + i(obj) } + , function () { return 'expected ' + i(this.obj) + ' to sort of not equal ' + i(obj) } + , obj) + return this + } /** * Assert within start to finish (inclusive). @@ -244,13 +243,13 @@ */ Assertion.prototype.within = function (start, finish) { - var range = start + '..' + finish; + var range = start + '..' + finish this.assert( - this.obj >= start && this.obj <= finish - , function(){ return 'expected ' + i(this.obj) + ' to be within ' + range } - , function(){ return 'expected ' + i(this.obj) + ' to not be within ' + range }); - return this; - }; + this.obj >= start && this.obj <= finish + , function () { return 'expected ' + i(this.obj) + ' to be within ' + range } + , function () { return 'expected ' + i(this.obj) + ' to not be within ' + range }) + return this + } /** * Assert typeof / instance of @@ -260,30 +259,30 @@ Assertion.prototype.a = Assertion.prototype.an = function (type) { - if ('string' == typeof type) { + if (typeof type === 'string') { // proper english in error msg - var n = /^[aeiou]/.test(type) ? 'n' : ''; + var n = /^[aeiou]/.test(type) ? 'n' : '' // typeof with support for 'array' this.assert( - 'array' == type ? isArray(this.obj) : - 'regexp' == type ? isRegExp(this.obj) : - 'object' == type - ? 'object' == typeof this.obj && null !== this.obj - : type == typeof this.obj - , function(){ return 'expected ' + i(this.obj) + ' to be a' + n + ' ' + type } - , function(){ return 'expected ' + i(this.obj) + ' not to be a' + n + ' ' + type }); + type == 'array' ? isArray(this.obj) + : type == 'regexp' ? isRegExp(this.obj) + : type == 'object' + ? typeof this.obj === 'object' && this.obj !== null + : type === typeof this.obj + , function () { return 'expected ' + i(this.obj) + ' to be a' + n + ' ' + type } + , function () { return 'expected ' + i(this.obj) + ' not to be a' + n + ' ' + type }) } else { // instanceof - var name = type.name || 'supplied constructor'; + var name = type.name || 'supplied constructor' this.assert( - this.obj instanceof type - , function(){ return 'expected ' + i(this.obj) + ' to be an instance of ' + name } - , function(){ return 'expected ' + i(this.obj) + ' not to be an instance of ' + name }); + this.obj instanceof type + , function () { return 'expected ' + i(this.obj) + ' to be an instance of ' + name } + , function () { return 'expected ' + i(this.obj) + ' not to be an instance of ' + name }) } - return this; - }; + return this + } /** * Assert numeric value above _n_. @@ -295,11 +294,11 @@ Assertion.prototype.greaterThan = Assertion.prototype.above = function (n) { this.assert( - this.obj > n - , function(){ return 'expected ' + i(this.obj) + ' to be above ' + n } - , function(){ return 'expected ' + i(this.obj) + ' to be below ' + n }); - return this; - }; + this.obj > n + , function () { return 'expected ' + i(this.obj) + ' to be above ' + n } + , function () { return 'expected ' + i(this.obj) + ' to be below ' + n }) + return this + } /** * Assert numeric value below _n_. @@ -311,11 +310,11 @@ Assertion.prototype.lessThan = Assertion.prototype.below = function (n) { this.assert( - this.obj < n - , function(){ return 'expected ' + i(this.obj) + ' to be below ' + n } - , function(){ return 'expected ' + i(this.obj) + ' to be above ' + n }); - return this; - }; + this.obj < n + , function () { return 'expected ' + i(this.obj) + ' to be below ' + n } + , function () { return 'expected ' + i(this.obj) + ' to be above ' + n }) + return this + } /** * Assert string value matches _regexp_. @@ -326,11 +325,11 @@ Assertion.prototype.match = function (regexp) { this.assert( - regexp.exec(this.obj) - , function(){ return 'expected ' + i(this.obj) + ' to match ' + regexp } - , function(){ return 'expected ' + i(this.obj) + ' not to match ' + regexp }); - return this; - }; + regexp.exec(this.obj) + , function () { return 'expected ' + i(this.obj) + ' to match ' + regexp } + , function () { return 'expected ' + i(this.obj) + ' not to match ' + regexp }) + return this + } /** * Assert property "length" exists and has value of _n_. @@ -340,14 +339,14 @@ */ Assertion.prototype.length = function (n) { - expect(this.obj).to.have.property('length'); - var len = this.obj.length; + expect(this.obj).to.have.property('length') + var len = this.obj.length this.assert( - n == len - , function(){ return 'expected ' + i(this.obj) + ' to have a length of ' + n + ' but got ' + len } - , function(){ return 'expected ' + i(this.obj) + ' to not have a length of ' + len }); - return this; - }; + n == len + , function () { return 'expected ' + i(this.obj) + ' to have a length of ' + n + ' but got ' + len } + , function () { return 'expected ' + i(this.obj) + ' to not have a length of ' + len }) + return this + } /** * Assert property _name_ exists, with optional _val_. @@ -360,18 +359,18 @@ Assertion.prototype.property = function (name, val) { if (this.flags.own) { this.assert( - Object.prototype.hasOwnProperty.call(this.obj, name) - , function(){ return 'expected ' + i(this.obj) + ' to have own property ' + i(name) } - , function(){ return 'expected ' + i(this.obj) + ' to not have own property ' + i(name) }); - return this; + Object.prototype.hasOwnProperty.call(this.obj, name) + , function () { return 'expected ' + i(this.obj) + ' to have own property ' + i(name) } + , function () { return 'expected ' + i(this.obj) + ' to not have own property ' + i(name) }) + return this } if (this.flags.not && undefined !== val) { if (undefined === this.obj[name]) { - throw new Error(i(this.obj) + ' has no property ' + i(name)); + throw new Error(i(this.obj) + ' has no property ' + i(name)) } } else { - var hasProp; + var hasProp try { hasProp = name in this.obj } catch (e) { @@ -379,23 +378,27 @@ } this.assert( - hasProp - , function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name) } - , function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) }); + hasProp + , function () { return 'expected ' + i(this.obj) + ' to have a property ' + i(name) } + , function () { return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) }) } if (undefined !== val) { this.assert( - val === this.obj[name] - , function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name) - + ' of ' + i(val) + ', but got ' + i(this.obj[name]) } - , function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) - + ' of ' + i(val) }); + val === this.obj[name] + , function () { + return 'expected ' + i(this.obj) + ' to have a property ' + i(name) + + ' of ' + i(val) + ', but got ' + i(this.obj[name]) + } + , function () { + return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) + + ' of ' + i(val) + }) } - this.obj = this.obj[name]; - return this; - }; + this.obj = this.obj[name] + return this + } /** * Assert that the array contains _obj_ or string contains _obj_. @@ -406,19 +409,19 @@ Assertion.prototype.string = Assertion.prototype.contain = function (obj) { - if ('string' == typeof this.obj) { + if (typeof this.obj === 'string') { this.assert( - ~this.obj.indexOf(obj) - , function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) } - , function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) }); + ~this.obj.indexOf(obj) + , function () { return 'expected ' + i(this.obj) + ' to contain ' + i(obj) } + , function () { return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) }) } else { this.assert( - ~indexOf(this.obj, obj) - , function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) } - , function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) }); + ~indexOf(this.obj, obj) + , function () { return 'expected ' + i(this.obj) + ' to contain ' + i(obj) } + , function () { return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) }) } - return this; - }; + return this + } /** * Assert exact keys or inclusion of keys by using @@ -431,52 +434,52 @@ Assertion.prototype.key = Assertion.prototype.keys = function ($keys) { var str - , ok = true; + var ok = true $keys = isArray($keys) ? $keys - : Array.prototype.slice.call(arguments); + : Array.prototype.slice.call(arguments) - if (!$keys.length) throw new Error('keys required'); + if (!$keys.length) throw new Error('keys required') var actual = keys(this.obj) - , len = $keys.length; + var len = $keys.length // Inclusion ok = every($keys, function (key) { - return ~indexOf(actual, key); - }); + return ~indexOf(actual, key) + }) // Strict if (!this.flags.not && this.flags.only) { - ok = ok && $keys.length == actual.length; + ok = ok && $keys.length == actual.length } // Key string if (len > 1) { $keys = map($keys, function (key) { - return i(key); - }); - var last = $keys.pop(); - str = $keys.join(', ') + ', and ' + last; + return i(key) + }) + var last = $keys.pop() + str = $keys.join(', ') + ', and ' + last } else { - str = i($keys[0]); + str = i($keys[0]) } // Form - str = (len > 1 ? 'keys ' : 'key ') + str; + str = (len > 1 ? 'keys ' : 'key ') + str // Have / include - str = (!this.flags.only ? 'include ' : 'only have ') + str; + str = (!this.flags.only ? 'include ' : 'only have ') + str // Assertion this.assert( - ok - , function(){ return 'expected ' + i(this.obj) + ' to ' + str } - , function(){ return 'expected ' + i(this.obj) + ' to not ' + str }); + ok + , function () { return 'expected ' + i(this.obj) + ' to ' + str } + , function () { return 'expected ' + i(this.obj) + ' to not ' + str }) - return this; - }; + return this + } /** * Assert a failure. @@ -485,10 +488,10 @@ * @api public */ Assertion.prototype.fail = function (msg) { - var error = function() { return msg || "explicit failure"; } - this.assert(false, error, error); - return this; - }; + var error = function () { return msg || 'explicit failure' } + this.assert(false, error, error) + return this + } /** * Function bind implementation. @@ -496,7 +499,7 @@ function bind (fn, scope) { return function () { - return fn.apply(scope, arguments); + return fn.apply(scope, arguments) } } @@ -508,13 +511,13 @@ */ function every (arr, fn, thisObj) { - var scope = thisObj || global; + var scope = thisObj || global for (var i = 0, j = arr.length; i < j; ++i) { if (!fn.call(scope, arr[i], i, arr)) { - return false; + return false } } - return true; + return true } /** @@ -526,47 +529,47 @@ function indexOf (arr, o, i) { if (Array.prototype.indexOf) { - return Array.prototype.indexOf.call(arr, o, i); + return Array.prototype.indexOf.call(arr, o, i) } if (arr.length === undefined) { - return -1; + return -1 } for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0 - ; i < j && arr[i] !== o; i++); + ; i < j && arr[i] !== o; i++); - return j <= i ? -1 : i; + return j <= i ? -1 : i } // https://gist.github.com/1044128/ - var getOuterHTML = function(element) { - if ('outerHTML' in element) return element.outerHTML; - var ns = "http://www.w3.org/1999/xhtml"; - var container = document.createElementNS(ns, '_'); - var xmlSerializer = new XMLSerializer(); - var html; + var getOuterHTML = function (element) { + if ('outerHTML' in element) return element.outerHTML + var ns = 'http://www.w3.org/1999/xhtml' + var container = document.createElementNS(ns, '_') + var xmlSerializer = new XMLSerializer() + var html if (document.xmlVersion) { - return xmlSerializer.serializeToString(element); + return xmlSerializer.serializeToString(element) } else { - container.appendChild(element.cloneNode(false)); - html = container.innerHTML.replace('><', '>' + element.innerHTML + '<'); - container.innerHTML = ''; - return html; + container.appendChild(element.cloneNode(false)) + html = container.innerHTML.replace('><', '>' + element.innerHTML + '<') + container.innerHTML = '' + return html } - }; + } // Returns true if object is a DOM element. var isDOMElement = function (object) { if (typeof HTMLElement === 'object') { - return object instanceof HTMLElement; + return object instanceof HTMLElement } else { return object && typeof object === 'object' && object.nodeType === 1 && - typeof object.nodeName === 'string'; + typeof object.nodeName === 'string' } - }; + } /** * Inspects an object. @@ -576,10 +579,10 @@ */ function i (obj, showHidden, depth) { - var seen = []; + var seen = [] function stylize (str) { - return str; + return str } function format (value, recurseTimes) { @@ -590,163 +593,163 @@ value !== exports && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { - return value.inspect(recurseTimes); + return value.inspect(recurseTimes) } // Primitive types cannot have properties switch (typeof value) { case 'undefined': - return stylize('undefined', 'undefined'); + return stylize('undefined', 'undefined') case 'string': var simple = '\'' + json.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return stylize(simple, 'string'); + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\'' + return stylize(simple, 'string') case 'number': - return stylize('' + value, 'number'); + return stylize('' + value, 'number') case 'boolean': - return stylize('' + value, 'boolean'); + return stylize('' + value, 'boolean') } // For some reason typeof null is "object", so special case here. if (value === null) { - return stylize('null', 'null'); + return stylize('null', 'null') } if (isDOMElement(value)) { - return getOuterHTML(value); + return getOuterHTML(value) } // Look up the keys of the object. - var visible_keys = keys(value); - var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys; + var visible_keys = keys(value) + var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys // Functions without properties can be shortcutted. if (typeof value === 'function' && $keys.length === 0) { if (isRegExp(value)) { - return stylize('' + value, 'regexp'); + return stylize('' + value, 'regexp') } else { - var name = value.name ? ': ' + value.name : ''; - return stylize('[Function' + name + ']', 'special'); + var name = value.name ? ': ' + value.name : '' + return stylize('[Function' + name + ']', 'special') } } // Dates without properties can be shortcutted if (isDate(value) && $keys.length === 0) { - return stylize(value.toUTCString(), 'date'); + return stylize(value.toUTCString(), 'date') } - + // Error objects can be shortcutted if (value instanceof Error) { - return stylize("["+value.toString()+"]", 'Error'); + return stylize('[' + value.toString() + ']', 'Error') } - var base, type, braces; + var base, type, braces // Determine the object type if (isArray(value)) { - type = 'Array'; - braces = ['[', ']']; + type = 'Array' + braces = ['[', ']'] } else { - type = 'Object'; - braces = ['{', '}']; + type = 'Object' + braces = ['{', '}'] } // Make functions say that they are functions if (typeof value === 'function') { - var n = value.name ? ': ' + value.name : ''; - base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']'; + var n = value.name ? ': ' + value.name : '' + base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']' } else { - base = ''; + base = '' } // Make dates with properties first say the date if (isDate(value)) { - base = ' ' + value.toUTCString(); + base = ' ' + value.toUTCString() } if ($keys.length === 0) { - return braces[0] + base + braces[1]; + return braces[0] + base + braces[1] } if (recurseTimes < 0) { if (isRegExp(value)) { - return stylize('' + value, 'regexp'); + return stylize('' + value, 'regexp') } else { - return stylize('[Object]', 'special'); + return stylize('[Object]', 'special') } } - seen.push(value); + seen.push(value) var output = map($keys, function (key) { - var name, str; + var name, str if (value.__lookupGetter__) { if (value.__lookupGetter__(key)) { if (value.__lookupSetter__(key)) { - str = stylize('[Getter/Setter]', 'special'); + str = stylize('[Getter/Setter]', 'special') } else { - str = stylize('[Getter]', 'special'); + str = stylize('[Getter]', 'special') } } else { if (value.__lookupSetter__(key)) { - str = stylize('[Setter]', 'special'); + str = stylize('[Setter]', 'special') } } } if (indexOf(visible_keys, key) < 0) { - name = '[' + key + ']'; + name = '[' + key + ']' } if (!str) { if (indexOf(seen, value[key]) < 0) { if (recurseTimes === null) { - str = format(value[key]); + str = format(value[key]) } else { - str = format(value[key], recurseTimes - 1); + str = format(value[key], recurseTimes - 1) } if (str.indexOf('\n') > -1) { if (isArray(value)) { str = map(str.split('\n'), function (line) { - return ' ' + line; - }).join('\n').substr(2); + return ' ' + line + }).join('\n').substr(2) } else { str = '\n' + map(str.split('\n'), function (line) { - return ' ' + line; - }).join('\n'); + return ' ' + line + }).join('\n') } } } else { - str = stylize('[Circular]', 'special'); + str = stylize('[Circular]', 'special') } } if (typeof name === 'undefined') { if (type === 'Array' && key.match(/^\d+$/)) { - return str; + return str } - name = json.stringify('' + key); + name = json.stringify('' + key) if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = stylize(name, 'name'); + name = name.substr(1, name.length - 2) + name = stylize(name, 'name') } else { name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = stylize(name, 'string'); + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'") + name = stylize(name, 'string') } } - return name + ': ' + str; - }); + return name + ': ' + str + }) - seen.pop(); + seen.pop() - var numLinesEst = 0; + var numLinesEst = 0 var length = reduce(output, function (prev, cur) { - numLinesEst++; - if (indexOf(cur, '\n') >= 0) numLinesEst++; - return prev + cur.length + 1; - }, 0); + numLinesEst++ + if (indexOf(cur, '\n') >= 0) numLinesEst++ + return prev + cur.length + 1 + }, 0) if (length > 50) { output = braces[0] + @@ -754,114 +757,109 @@ ' ' + output.join(',\n ') + ' ' + - braces[1]; - + braces[1] } else { - output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1] } - return output; + return output } - return format(obj, (typeof depth === 'undefined' ? 2 : depth)); + return format(obj, (typeof depth === 'undefined' ? 2 : depth)) } - expect.stringify = i; + expect.stringify = i function isArray (ar) { - return Object.prototype.toString.call(ar) === '[object Array]'; + return Object.prototype.toString.call(ar) === '[object Array]' } - function isRegExp(re) { - var s; + function isRegExp (re) { + var s try { - s = '' + re; + s = '' + re } catch (e) { - return false; + return false } return re instanceof RegExp || // easy case // duck-type for context-switching evalcx case - typeof(re) === 'function' && + typeof (re) === 'function' && re.constructor.name === 'RegExp' && re.compile && re.test && re.exec && - s.match(/^\/.*\/[gim]{0,3}$/); + s.match(/^\/.*\/[gim]{0,3}$/) } - function isDate(d) { - return d instanceof Date; + function isDate (d) { + return d instanceof Date } function keys (obj) { if (Object.keys) { - return Object.keys(obj); + return Object.keys(obj) } - var keys = []; + var keys = [] for (var i in obj) { if (Object.prototype.hasOwnProperty.call(obj, i)) { - keys.push(i); + keys.push(i) } } - return keys; + return keys } function map (arr, mapper, that) { if (Array.prototype.map) { - return Array.prototype.map.call(arr, mapper, that); + return Array.prototype.map.call(arr, mapper, that) } - var other= new Array(arr.length); + var other = new Array(arr.length) - for (var i= 0, n = arr.length; i= 2) { - var rv = arguments[1]; + var rv = arguments[1] } else { do { if (i in this) { - rv = this[i++]; - break; + rv = this[i++] + break } // if array contains no values, no initial value to return - if (++i >= len) - throw new TypeError(); - } while (true); + if (++i >= len) { throw new TypeError() } + } while (true) } for (; i < len; i++) { - if (i in this) - rv = fun.call(null, rv, this[i], i, this); + if (i in this) { rv = fun.call(null, rv, this[i], i, this) } } - return rv; + return rv } /** @@ -871,33 +869,33 @@ * @api private */ - expect.eql = function eql(actual, expected) { + expect.eql = function eql (actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { - return true; - } else if ('undefined' != typeof Buffer - && Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { - if (actual.length != expected.length) return false; + return true + } else if (typeof Buffer !== 'undefined' && + Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { + if (actual.length != expected.length) return false for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; + if (actual[i] !== expected[i]) return false } - return true; + return true // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); + return actual.getTime() === expected.getTime() // 7.3. Other pairs that do not both pass typeof value == "object", // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; + } else if (typeof actual !== 'object' && typeof expected !== 'object') { + return actual == expected // If both are regular expression use the special `regExpEquiv` method // to determine equivalence. } else if (isRegExp(actual) && isRegExp(expected)) { - return regExpEquiv(actual, expected); + return regExpEquiv(actual, expected) // 7.4. For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys @@ -905,380 +903,364 @@ // corresponding key, and an identical "prototype" property. Note: this // accounts for both named and indexed properties on Arrays. } else { - return objEquiv(actual, expected); + return objEquiv(actual, expected) } - }; + } function isUndefinedOrNull (value) { - return value === null || value === undefined; + return value === null || value === undefined } function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; + return Object.prototype.toString.call(object) == '[object Arguments]' } function regExpEquiv (a, b) { return a.source === b.source && a.global === b.global && - a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; + a.ignoreCase === b.ignoreCase && a.multiline === b.multiline } function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) - return false; + if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) { return false } // an identical "prototype" property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. + if (a.prototype !== b.prototype) return false + // ~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { - return false; + return false } - a = pSlice.call(a); - b = pSlice.call(b); - return expect.eql(a, b); + a = pSlice.call(a) + b = pSlice.call(b) + return expect.eql(a, b) } - try{ - var ka = keys(a), - kb = keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; + try { + var ka = keys(a) + var kb = keys(b) + var key; var i + } catch (e) { // happens when one is a string literal and the other isn't + return false } // having the same number of owned properties (keys incorporates hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test + if (ka.length != kb.length) { return false } + // the same set of keys (although not necessarily the same order), + ka.sort() + kb.sort() + // ~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; + if (ka[i] != kb[i]) { return false } } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test + // equivalent values for every corresponding key, and + // ~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!expect.eql(a[key], b[key])) - return false; + key = ka[i] + if (!expect.eql(a[key], b[key])) { return false } } - return true; + return true } var json = (function () { - "use strict"; + 'use strict' - if ('object' == typeof JSON && JSON.parse && JSON.stringify) { + if (typeof JSON === 'object' && JSON.parse && JSON.stringify) { return { - parse: nativeJSON.parse - , stringify: nativeJSON.stringify + parse: nativeJSON.parse, + stringify: nativeJSON.stringify } } - var JSON = {}; + var JSON = {} - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; + function f (n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n } - function date(d, key) { - return isFinite(d.valueOf()) ? - d.getUTCFullYear() + '-' + + function date (d, key) { + return isFinite(d.valueOf()) + ? d.getUTCFullYear() + '-' + f(d.getUTCMonth() + 1) + '-' + - f(d.getUTCDate()) + 'T' + - f(d.getUTCHours()) + ':' + - f(d.getUTCMinutes()) + ':' + - f(d.getUTCSeconds()) + 'Z' : null; + f(d.getUTCDate()) + 'T' + + f(d.getUTCHours()) + ':' + + f(d.getUTCMinutes()) + ':' + + f(d.getUTCSeconds()) + 'Z' : null } - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - - // If the string contains no control characters, no quote characters, and no - // backslash characters, then we can safely slap some quotes around it. - // Otherwise we must also replace the offending characters with safe escape - // sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g + var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g + var gap + var indent + var meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"': '\\"', + '\\': '\\\\' + } + var rep + + function quote (string) { + // If the string contains no control characters, no quote characters, and no + // backslash characters, then we can safely slap some quotes around it. + // Otherwise we must also replace the offending characters with safe escape + // sequences. + + escapable.lastIndex = 0 + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a] + return typeof c === 'string' ? c + : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4) + }) + '"' : '"' + string + '"' } + function str (key, holder) { + // Produce a string from holder[key]. - function str(key, holder) { - - // Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; + var i // The loop counter. + var k // The member key. + var v // The member value. + var length + var mind = gap + var partial + var value = holder[key] - // If the value has a toJSON method, call it to obtain a replacement value. + // If the value has a toJSON method, call it to obtain a replacement value. - if (value instanceof Date) { - value = date(key); - } + if (value instanceof Date) { + value = date(key) + } - // If we were called with a replacer function, then call the replacer to - // obtain a replacement value. + // If we were called with a replacer function, then call the replacer to + // obtain a replacement value. - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } + if (typeof rep === 'function') { + value = rep.call(holder, key, value) + } - // What happens next depends on the value's type. + // What happens next depends on the value's type. - switch (typeof value) { + switch (typeof value) { case 'string': - return quote(value); + return quote(value) case 'number': - // JSON numbers must be finite. Encode non-finite numbers as null. + // JSON numbers must be finite. Encode non-finite numbers as null. - return isFinite(value) ? String(value) : 'null'; + return isFinite(value) ? String(value) : 'null' case 'boolean': case 'null': - // If the value is a boolean or null, convert it to a string. Note: - // typeof null does not produce 'null'. The case is included here in - // the remote chance that this gets fixed someday. + // If the value is a boolean or null, convert it to a string. Note: + // typeof null does not produce 'null'. The case is included here in + // the remote chance that this gets fixed someday. - return String(value); + return String(value) - // If the type is 'object', we might be dealing with an object or an array or - // null. + // If the type is 'object', we might be dealing with an object or an array or + // null. case 'object': - // Due to a specification blunder in ECMAScript, typeof null is 'object', - // so watch out for that case. + // Due to a specification blunder in ECMAScript, typeof null is 'object', + // so watch out for that case. - if (!value) { - return 'null'; - } + if (!value) { + return 'null' + } - // Make an array to hold the partial results of stringifying this object value. + // Make an array to hold the partial results of stringifying this object value. - gap += indent; - partial = []; + gap += indent + partial = [] - // Is the value an array? + // Is the value an array? - if (Object.prototype.toString.apply(value) === '[object Array]') { + if (Object.prototype.toString.apply(value) === '[object Array]') { + // The value is an array. Stringify every element. Use null as a placeholder + // for non-JSON values. - // The value is an array. Stringify every element. Use null as a placeholder - // for non-JSON values. + length = value.length + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null' + } - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } + // Join all of the elements together, separated with commas, and wrap them in + // brackets. - // Join all of the elements together, separated with commas, and wrap them in - // brackets. + v = partial.length === 0 ? '[]' : gap + ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' + : '[' + partial.join(',') + ']' + gap = mind + return v + } - v = partial.length === 0 ? '[]' : gap ? - '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } + // If the replacer is an array, use it to select the members to be stringified. - // If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } + if (rep && typeof rep === 'object') { + length = rep.length + for (i = 0; i < length; i += 1) { + if (typeof rep[i] === 'string') { + k = rep[i] + v = str(k, value) + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v) } - } else { - - // Otherwise, iterate through all of the keys in the object. + } + } + } else { + // Otherwise, iterate through all of the keys in the object. - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value) + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v) } + } } + } - // Join all of the member texts together, separated with commas, - // and wrap them in braces. + // Join all of the member texts together, separated with commas, + // and wrap them in braces. - v = partial.length === 0 ? '{}' : gap ? - '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - } + v = partial.length === 0 ? '{}' : gap + ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' + : '{' + partial.join(',') + '}' + gap = mind + return v + } } - // If the JSON object does not yet have a stringify method, give it one. + // If the JSON object does not yet have a stringify method, give it one. JSON.stringify = function (value, replacer, space) { - - // The stringify method takes a value and an optional replacer, and an optional - // space parameter, and returns a JSON text. The replacer can be a function - // that can replace values, or an array of strings that will select the keys. - // A default replacer method can be provided. Use of the space parameter can - // produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - - // If the space parameter is a number, make an indent string containing that - // many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - - // If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; + // The stringify method takes a value and an optional replacer, and an optional + // space parameter, and returns a JSON text. The replacer can be a function + // that can replace values, or an array of strings that will select the keys. + // A default replacer method can be provided. Use of the space parameter can + // produce text that is more easily readable. + + var i + gap = '' + indent = '' + + // If the space parameter is a number, make an indent string containing that + // many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' ' } - // If there is a replacer, it must be a function or an array. - // Otherwise, throw an error. + // If the space parameter is a string, it will be used as the indent string. + } else if (typeof space === 'string') { + indent = space + } + + // If there is a replacer, it must be a function or an array. + // Otherwise, throw an error. - rep = replacer; - if (replacer && typeof replacer !== 'function' && + rep = replacer + if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } + throw new Error('JSON.stringify') + } - // Make a fake root object containing our value under the key of ''. - // Return the result of stringifying the value. + // Make a fake root object containing our value under the key of ''. + // Return the result of stringifying the value. - return str('', {'': value}); - }; + return str('', { '': value }) + } - // If the JSON object does not yet have a parse method, give it one. + // If the JSON object does not yet have a parse method, give it one. JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. - var j; + var j - function walk(holder, key) { + function walk (holder, key) { + // The walk method is used to recursively walk the resulting structure so + // that modifications can be made. - // The walk method is used to recursively walk the resulting structure so - // that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } + var k; var v; var value = holder[key] + if (value && typeof value === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k) + if (v !== undefined) { + value[k] = v + } else { + delete value[k] + } } - return reviver.call(holder, key, value); - } - - - // Parsing happens in four stages. In the first stage, we replace certain - // Unicode characters with escape sequences. JavaScript handles many characters - // incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); + } } + return reviver.call(holder, key, value) + } - // In the second stage, we run the text against regular expressions that look - // for non-JSON patterns. We are especially concerned with '()' and 'new' - // because they can cause invocation, and '=' because it can cause mutation. - // But just to be safe, we want to reject all unexpected forms. - - // We split the second stage into 4 regexp operations in order to work around - // crippling inefficiencies in IE's and Safari's regexp engines. First we - // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we - // replace all simple value tokens with ']' characters. Third, we delete all - // open brackets that follow a colon or comma or that begin the text. Finally, - // we look to see that the remaining characters are only whitespace or ']' or - // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - - // In the third stage we use the eval function to compile the text into a - // JavaScript structure. The '{' operator is subject to a syntactic ambiguity - // in JavaScript: it can begin a block or an object literal. We wrap the text - // in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - - // In the optional fourth stage, we recursively walk the new structure, passing - // each name/value pair to a reviver function for possible transformation. + // Parsing happens in four stages. In the first stage, we replace certain + // Unicode characters with escape sequences. JavaScript handles many characters + // incorrectly, either silently deleting them, or treating them as line endings. + + text = String(text) + cx.lastIndex = 0 + if (cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + + ('0000' + a.charCodeAt(0).toString(16)).slice(-4) + }) + } - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } + // In the second stage, we run the text against regular expressions that look + // for non-JSON patterns. We are especially concerned with '()' and 'new' + // because they can cause invocation, and '=' because it can cause mutation. + // But just to be safe, we want to reject all unexpected forms. + + // We split the second stage into 4 regexp operations in order to work around + // crippling inefficiencies in IE's and Safari's regexp engines. First we + // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we + // replace all simple value tokens with ']' characters. Third, we delete all + // open brackets that follow a colon or comma or that begin the text. Finally, + // we look to see that the remaining characters are only whitespace or ']' or + // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. + + if (/^[\],:{}\s]*$/ + .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') + .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + // In the third stage we use the eval function to compile the text into a + // JavaScript structure. The '{' operator is subject to a syntactic ambiguity + // in JavaScript: it can begin a block or an object literal. We wrap the text + // in parens to eliminate the ambiguity. + + j = eval('(' + text + ')') + + // In the optional fourth stage, we recursively walk the new structure, passing + // each name/value pair to a reviver function for possible transformation. + + return typeof reviver === 'function' + ? walk({ '': j }, '') : j + } - // If the text is not JSON parseable, then a SyntaxError is thrown. + // If the text is not JSON parseable, then a SyntaxError is thrown. - throw new SyntaxError('JSON.parse'); - }; + throw new SyntaxError('JSON.parse') + } - return JSON; - })(); + return JSON + })() - if ('undefined' != typeof window) { - window.expect = module.exports; + if (typeof window !== 'undefined') { + window.expect = module.exports } - })( - this - , 'undefined' != typeof module ? module : {exports: {}} -); + this + , typeof module !== 'undefined' ? module : { exports: {} } +) diff --git a/examples/mocha/lib/mocha/mocha.js b/examples/mocha/lib/mocha/mocha.js index 19edc87..08fa4cf 100644 --- a/examples/mocha/lib/mocha/mocha.js +++ b/examples/mocha/lib/mocha/mocha.js @@ -1,65 +1,61 @@ -;(function(){ - +;(function () { // CommonJS require() -function require(p){ + function require (p) { var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); + var mod = require.modules[path] + if (!mod) throw new Error('failed to require "' + p + '"') if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); + mod.exports = {} + mod.call(mod.exports, mod, mod.exports, require.relative(path)) } - return mod.exports; + return mod.exports } -require.modules = {}; + require.modules = {} -require.resolve = function (path){ + require.resolve = function (path) { var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; + var reg = path + '.js' + var index = path + '/index.js' + return require.modules[reg] && reg || + require.modules[index] && index || + orig + } -require.register = function (path, fn){ - require.modules[path] = fn; - }; + require.register = function (path, fn) { + require.modules[path] = fn + } -require.relative = function (parent) { - return function(p){ - if ('.' != p.charAt(0)) return require(p); + require.relative = function (parent) { + return function (p) { + if (p.charAt(0) != '.') return require(p) var path = parent.split('/') - , segs = p.split('/'); - path.pop(); + var segs = p.split('/') + path.pop() for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); + var seg = segs[i] + if (seg == '..') path.pop() + else if (seg != '.') path.push(seg) } - return require(path.join('/')); - }; - }; - - -require.register("browser/debug.js", function(module, exports, require){ - -module.exports = function(type){ - return function(){ + return require(path.join('/')) + } } -}; -}); // module: browser/debug.js + require.register('browser/debug.js', function (module, exports, require) { + module.exports = function (type) { + return function () { + } + } + }) // module: browser/debug.js -require.register("browser/diff.js", function(module, exports, require){ -/* See LICENSE file for terms of use */ + require.register('browser/diff.js', function (module, exports, require) { + /* See LICENSE file for terms of use */ -/* + /* * Text diff implementation. * * This library supports the following APIS: @@ -73,555 +69,553 @@ require.register("browser/diff.js", function(module, exports, require){ * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 */ -var JsDiff = (function() { - /*jshint maxparams: 5*/ - function clonePath(path) { - return { newPos: path.newPos, components: path.components.slice(0) }; - } - function removeEmpty(array) { - var ret = []; - for (var i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); + var JsDiff = (function () { + /* jshint maxparams: 5 */ + function clonePath (path) { + return { newPos: path.newPos, components: path.components.slice(0) } + } + function removeEmpty (array) { + var ret = [] + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]) + } + } + return ret + } + function escapeHTML (s) { + var n = s + n = n.replace(/&/g, '&') + n = n.replace(//g, '>') + n = n.replace(/"/g, '"') + + return n } - } - return ret; - } - function escapeHTML(s) { - var n = s; - n = n.replace(/&/g, '&'); - n = n.replace(//g, '>'); - n = n.replace(/"/g, '"'); - - return n; - } - var Diff = function(ignoreWhitespace) { - this.ignoreWhitespace = ignoreWhitespace; - }; - Diff.prototype = { - diff: function(oldString, newString) { + var Diff = function (ignoreWhitespace) { + this.ignoreWhitespace = ignoreWhitespace + } + Diff.prototype = { + diff: function (oldString, newString) { // Handle the identity case (this is due to unrolling editLength == 0 - if (newString === oldString) { - return [{ value: newString }]; - } - if (!newString) { - return [{ value: oldString, removed: true }]; - } - if (!oldString) { - return [{ value: newString, added: true }]; - } + if (newString === oldString) { + return [{ value: newString }] + } + if (!newString) { + return [{ value: oldString, removed: true }] + } + if (!oldString) { + return [{ value: newString, added: true }] + } - newString = this.tokenize(newString); - oldString = this.tokenize(oldString); + newString = this.tokenize(newString) + oldString = this.tokenize(oldString) - var newLen = newString.length, oldLen = oldString.length; - var maxEditLength = newLen + oldLen; - var bestPath = [{ newPos: -1, components: [] }]; + var newLen = newString.length; var oldLen = oldString.length + var maxEditLength = newLen + oldLen + var bestPath = [{ newPos: -1, components: [] }] - // Seed editLength = 0 - var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); - if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { - return bestPath[0].components; - } + // Seed editLength = 0 + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0) + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + return bestPath[0].components + } - for (var editLength = 1; editLength <= maxEditLength; editLength++) { - for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { - var basePath; - var addPath = bestPath[diagonalPath-1], - removePath = bestPath[diagonalPath+1]; - oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; - if (addPath) { + for (var editLength = 1; editLength <= maxEditLength; editLength++) { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath + var addPath = bestPath[diagonalPath - 1] + var removePath = bestPath[diagonalPath + 1] + oldPos = (removePath ? removePath.newPos : 0) - diagonalPath + if (addPath) { // No one else is going to attempt to use this value, clear it - bestPath[diagonalPath-1] = undefined; - } + bestPath[diagonalPath - 1] = undefined + } - var canAdd = addPath && addPath.newPos+1 < newLen; - var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; - if (!canAdd && !canRemove) { - bestPath[diagonalPath] = undefined; - continue; - } + var canAdd = addPath && addPath.newPos + 1 < newLen + var canRemove = removePath && oldPos >= 0 && oldPos < oldLen + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = undefined + continue + } - // Select the diagonal that we want to branch from. We select the prior - // path whose position in the new string is the farthest from the origin - // and does not pass the bounds of the diff graph - if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { - basePath = clonePath(removePath); - this.pushComponent(basePath.components, oldString[oldPos], undefined, true); - } else { - basePath = clonePath(addPath); - basePath.newPos++; - this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); - } + // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { + basePath = clonePath(removePath) + this.pushComponent(basePath.components, oldString[oldPos], undefined, true) + } else { + basePath = clonePath(addPath) + basePath.newPos++ + this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined) + } - var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); + var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath) - if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { - return basePath.components; - } else { - bestPath[diagonalPath] = basePath; + if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + return basePath.components + } else { + bestPath[diagonalPath] = basePath + } } } - } - }, + }, - pushComponent: function(components, value, added, removed) { - var last = components[components.length-1]; - if (last && last.added === added && last.removed === removed) { + pushComponent: function (components, value, added, removed) { + var last = components[components.length - 1] + if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone - components[components.length-1] = - {value: this.join(last.value, value), added: added, removed: removed }; - } else { - components.push({value: value, added: added, removed: removed }); - } - }, - extractCommon: function(basePath, newString, oldString, diagonalPath) { - var newLen = newString.length, - oldLen = oldString.length, - newPos = basePath.newPos, - oldPos = newPos - diagonalPath; - while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { - newPos++; - oldPos++; - - this.pushComponent(basePath.components, newString[newPos], undefined, undefined); - } - basePath.newPos = newPos; - return oldPos; - }, - - equals: function(left, right) { - var reWhitespace = /\S/; - if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { - return true; - } else { - return left === right; + components[components.length - 1] = + { value: this.join(last.value, value), added: added, removed: removed } + } else { + components.push({ value: value, added: added, removed: removed }) + } + }, + extractCommon: function (basePath, newString, oldString, diagonalPath) { + var newLen = newString.length + var oldLen = oldString.length + var newPos = basePath.newPos + var oldPos = newPos - diagonalPath + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++ + oldPos++ + + this.pushComponent(basePath.components, newString[newPos], undefined, undefined) + } + basePath.newPos = newPos + return oldPos + }, + + equals: function (left, right) { + var reWhitespace = /\S/ + if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { + return true + } else { + return left === right + } + }, + join: function (left, right) { + return left + right + }, + tokenize: function (value) { + return value } - }, - join: function(left, right) { - return left + right; - }, - tokenize: function(value) { - return value; } - }; - - var CharDiff = new Diff(); - var WordDiff = new Diff(true); - var WordWithSpaceDiff = new Diff(); - WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { - return removeEmpty(value.split(/(\s+|\b)/)); - }; + var CharDiff = new Diff() - var CssDiff = new Diff(true); - CssDiff.tokenize = function(value) { - return removeEmpty(value.split(/([{}:;,]|\s+)/)); - }; + var WordDiff = new Diff(true) + var WordWithSpaceDiff = new Diff() + WordDiff.tokenize = WordWithSpaceDiff.tokenize = function (value) { + return removeEmpty(value.split(/(\s+|\b)/)) + } - var LineDiff = new Diff(); - LineDiff.tokenize = function(value) { - return value.split(/^/m); - }; + var CssDiff = new Diff(true) + CssDiff.tokenize = function (value) { + return removeEmpty(value.split(/([{}:;,]|\s+)/)) + } - return { - Diff: Diff, + var LineDiff = new Diff() + LineDiff.tokenize = function (value) { + return value.split(/^/m) + } - diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, - diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, - diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, - diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, + return { + Diff: Diff, - diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, + diffChars: function (oldStr, newStr) { return CharDiff.diff(oldStr, newStr) }, + diffWords: function (oldStr, newStr) { return WordDiff.diff(oldStr, newStr) }, + diffWordsWithSpace: function (oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr) }, + diffLines: function (oldStr, newStr) { return LineDiff.diff(oldStr, newStr) }, - createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { - var ret = []; + diffCss: function (oldStr, newStr) { return CssDiff.diff(oldStr, newStr) }, - ret.push('Index: ' + fileName); - ret.push('==================================================================='); - ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); - ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); + createPatch: function (fileName, oldStr, newStr, oldHeader, newHeader) { + var ret = [] - var diff = LineDiff.diff(oldStr, newStr); - if (!diff[diff.length-1].value) { - diff.pop(); // Remove trailing newline add - } - diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier + ret.push('Index: ' + fileName) + ret.push('===================================================================') + ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)) + ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)) - function contextLines(lines) { - return lines.map(function(entry) { return ' ' + entry; }); - } - function eofNL(curRange, i, current) { - var last = diff[diff.length-2], - isLast = i === diff.length-2, - isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); - - // Figure out if this is the last line for the given file and missing NL - if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { - curRange.push('\\ No newline at end of file'); - } - } + var diff = LineDiff.diff(oldStr, newStr) + if (!diff[diff.length - 1].value) { + diff.pop() // Remove trailing newline add + } + diff.push({ value: '', lines: [] }) // Append an empty value to make cleanup easier - var oldRangeStart = 0, newRangeStart = 0, curRange = [], - oldLine = 1, newLine = 1; - for (var i = 0; i < diff.length; i++) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - current.lines = lines; - - if (current.added || current.removed) { - if (!oldRangeStart) { - var prev = diff[i-1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - - if (prev) { - curRange = contextLines(prev.lines.slice(-4)); - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; + function contextLines (lines) { + return lines.map(function (entry) { return ' ' + entry }) + } + function eofNL (curRange, i, current) { + var last = diff[diff.length - 2] + var isLast = i === diff.length - 2 + var isLastOfType = i === diff.length - 3 && (current.added !== last.added || current.removed !== last.removed) + + // Figure out if this is the last line for the given file and missing NL + if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { + curRange.push('\\ No newline at end of file') } } - curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); - eofNL(curRange, i, current); - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= 8 && i < diff.length-2) { - // Overlapping - curRange.push.apply(curRange, contextLines(lines)); - } else { - // end the range and output - var contextSize = Math.min(lines.length, 4); - ret.push( - '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) - + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) - + ' @@'); - ret.push.apply(ret, curRange); - ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); - if (lines.length <= 4) { - eofNL(ret, i, current); + var oldRangeStart = 0; var newRangeStart = 0; var curRange = [] + var oldLine = 1; var newLine = 1 + for (var i = 0; i < diff.length; i++) { + var current = diff[i] + var lines = current.lines || current.value.replace(/\n$/, '').split('\n') + current.lines = lines + + if (current.added || current.removed) { + if (!oldRangeStart) { + var prev = diff[i - 1] + oldRangeStart = oldLine + newRangeStart = newLine + + if (prev) { + curRange = contextLines(prev.lines.slice(-4)) + oldRangeStart -= curRange.length + newRangeStart -= curRange.length + } } + curRange.push.apply(curRange, lines.map(function (entry) { return (current.added ? '+' : '-') + entry })) + eofNL(curRange, i, current) - oldRangeStart = 0; newRangeStart = 0; curRange = []; + if (current.added) { + newLine += lines.length + } else { + oldLine += lines.length + } + } else { + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= 8 && i < diff.length - 2) { + // Overlapping + curRange.push.apply(curRange, contextLines(lines)) + } else { + // end the range and output + var contextSize = Math.min(lines.length, 4) + ret.push( + '@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize) + + ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize) + + ' @@') + ret.push.apply(ret, curRange) + ret.push.apply(ret, contextLines(lines.slice(0, contextSize))) + if (lines.length <= 4) { + eofNL(ret, i, current) + } + + oldRangeStart = 0; newRangeStart = 0; curRange = [] + } + } + oldLine += lines.length + newLine += lines.length } } - oldLine += lines.length; - newLine += lines.length; - } - } - return ret.join('\n') + '\n'; - }, - - applyPatch: function(oldStr, uniDiff) { - var diffstr = uniDiff.split('\n'); - var diff = []; - var remEOFNL = false, - addEOFNL = false; - - for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { - if(diffstr[i][0] === '@') { - var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); - diff.unshift({ - start:meh[3], - oldlength:meh[2], - oldlines:[], - newlength:meh[4], - newlines:[] - }); - } else if(diffstr[i][0] === '+') { - diff[0].newlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === '-') { - diff[0].oldlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === ' ') { - diff[0].newlines.push(diffstr[i].substr(1)); - diff[0].oldlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === '\\') { - if (diffstr[i-1][0] === '+') { - remEOFNL = true; - } else if(diffstr[i-1][0] === '-') { - addEOFNL = true; + return ret.join('\n') + '\n' + }, + + applyPatch: function (oldStr, uniDiff) { + var diffstr = uniDiff.split('\n') + var diff = [] + var remEOFNL = false + var addEOFNL = false + + for (var i = (diffstr[0][0] === 'I' ? 4 : 0); i < diffstr.length; i++) { + if (diffstr[i][0] === '@') { + var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/) + diff.unshift({ + start: meh[3], + oldlength: meh[2], + oldlines: [], + newlength: meh[4], + newlines: [] + }) + } else if (diffstr[i][0] === '+') { + diff[0].newlines.push(diffstr[i].substr(1)) + } else if (diffstr[i][0] === '-') { + diff[0].oldlines.push(diffstr[i].substr(1)) + } else if (diffstr[i][0] === ' ') { + diff[0].newlines.push(diffstr[i].substr(1)) + diff[0].oldlines.push(diffstr[i].substr(1)) + } else if (diffstr[i][0] === '\\') { + if (diffstr[i - 1][0] === '+') { + remEOFNL = true + } else if (diffstr[i - 1][0] === '-') { + addEOFNL = true + } + } } - } - } - var str = oldStr.split('\n'); - for (var i = diff.length - 1; i >= 0; i--) { - var d = diff[i]; - for (var j = 0; j < d.oldlength; j++) { - if(str[d.start-1+j] !== d.oldlines[j]) { - return false; + var str = oldStr.split('\n') + for (var i = diff.length - 1; i >= 0; i--) { + var d = diff[i] + for (var j = 0; j < d.oldlength; j++) { + if (str[d.start - 1 + j] !== d.oldlines[j]) { + return false + } + } + Array.prototype.splice.apply(str, [d.start - 1, +d.oldlength].concat(d.newlines)) } - } - Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); - } - if (remEOFNL) { - while (!str[str.length-1]) { - str.pop(); - } - } else if (addEOFNL) { - str.push(''); - } - return str.join('\n'); - }, - - convertChangesToXML: function(changes){ - var ret = []; - for ( var i = 0; i < changes.length; i++) { - var change = changes[i]; - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); - } + if (remEOFNL) { + while (!str[str.length - 1]) { + str.pop() + } + } else if (addEOFNL) { + str.push('') + } + return str.join('\n') + }, + + convertChangesToXML: function (changes) { + var ret = [] + for (var i = 0; i < changes.length; i++) { + var change = changes[i] + if (change.added) { + ret.push('') + } else if (change.removed) { + ret.push('') + } - ret.push(escapeHTML(change.value)); + ret.push(escapeHTML(change.value)) - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); + if (change.added) { + ret.push('') + } else if (change.removed) { + ret.push('') + } + } + return ret.join('') + }, + + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + convertChangesToDMP: function (changes) { + var ret = []; var change + for (var i = 0; i < changes.length; i++) { + change = changes[i] + ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]) + } + return ret } } - return ret.join(''); - }, - - // See: http://code.google.com/p/google-diff-match-patch/wiki/API - convertChangesToDMP: function(changes){ - var ret = [], change; - for ( var i = 0; i < changes.length; i++) { - change = changes[i]; - ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); - } - return ret; - } - }; -})(); + })() -if (typeof module !== 'undefined') { - module.exports = JsDiff; -} - -}); // module: browser/diff.js - -require.register("browser/events.js", function(module, exports, require){ + if (typeof module !== 'undefined') { + module.exports = JsDiff + } + }) // module: browser/diff.js -/** + require.register('browser/events.js', function (module, exports, require) { + /** * Module exports. */ -exports.EventEmitter = EventEmitter; + exports.EventEmitter = EventEmitter -/** + /** * Check if `obj` is an array. */ -function isArray(obj) { - return '[object Array]' == {}.toString.call(obj); -} + function isArray (obj) { + return {}.toString.call(obj) == '[object Array]' + } -/** + /** * Event emitter constructor. * * @api public */ -function EventEmitter(){}; + function EventEmitter () {}; -/** + /** * Adds a listener. * * @api public */ -EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } + EventEmitter.prototype.on = function (name, fn) { + if (!this.$events) { + this.$events = {} + } - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } + if (!this.$events[name]) { + this.$events[name] = fn + } else if (isArray(this.$events[name])) { + this.$events[name].push(fn) + } else { + this.$events[name] = [this.$events[name], fn] + } - return this; -}; + return this + } -EventEmitter.prototype.addListener = EventEmitter.prototype.on; + EventEmitter.prototype.addListener = EventEmitter.prototype.on -/** + /** * Adds a volatile listener. * * @api public */ -EventEmitter.prototype.once = function (name, fn) { - var self = this; + EventEmitter.prototype.once = function (name, fn) { + var self = this - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; + function on () { + self.removeListener(name, on) + fn.apply(this, arguments) + }; - on.listener = fn; - this.on(name, on); + on.listener = fn + this.on(name, on) - return this; -}; + return this + } -/** + /** * Removes a listener. * * @api public */ -EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; + EventEmitter.prototype.removeListener = function (name, fn) { + if (this.$events && this.$events[name]) { + var list = this.$events[name] - if (isArray(list)) { - var pos = -1; + if (isArray(list)) { + var pos = -1 - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } + for (var i = 0, l = list.length; i < l; i++) { + if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { + pos = i + break + } + } - if (pos < 0) { - return this; - } + if (pos < 0) { + return this + } - list.splice(pos, 1); + list.splice(pos, 1) - if (!list.length) { - delete this.$events[name]; + if (!list.length) { + delete this.$events[name] + } + } else if (list === fn || (list.listener && list.listener === fn)) { + delete this.$events[name] + } } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } - return this; -}; + return this + } -/** + /** * Removes all listeners for an event. * * @api public */ -EventEmitter.prototype.removeAllListeners = function (name) { - if (name === undefined) { - this.$events = {}; - return this; - } + EventEmitter.prototype.removeAllListeners = function (name) { + if (name === undefined) { + this.$events = {} + return this + } - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } + if (this.$events && this.$events[name]) { + this.$events[name] = null + } - return this; -}; + return this + } -/** + /** * Gets all listeners for a certain event. * * @api public */ -EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } + EventEmitter.prototype.listeners = function (name) { + if (!this.$events) { + this.$events = {} + } - if (!this.$events[name]) { - this.$events[name] = []; - } + if (!this.$events[name]) { + this.$events[name] = [] + } - if (!isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } + if (!isArray(this.$events[name])) { + this.$events[name] = [this.$events[name]] + } - return this.$events[name]; -}; + return this.$events[name] + } -/** + /** * Emits an event. * * @api public */ -EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } + EventEmitter.prototype.emit = function (name) { + if (!this.$events) { + return false + } - var handler = this.$events[name]; + var handler = this.$events[name] - if (!handler) { - return false; - } + if (!handler) { + return false + } - var args = [].slice.call(arguments, 1); + var args = [].slice.call(arguments, 1) - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (isArray(handler)) { - var listeners = handler.slice(); + if (typeof handler === 'function') { + handler.apply(this, args) + } else if (isArray(handler)) { + var listeners = handler.slice() - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } + for (var i = 0, l = listeners.length; i < l; i++) { + listeners[i].apply(this, args) + } + } else { + return false + } - return true; -}; -}); // module: browser/events.js + return true + } + }) // module: browser/events.js -require.register("browser/fs.js", function(module, exports, require){ + require.register('browser/fs.js', function (module, exports, require) { -}); // module: browser/fs.js + }) // module: browser/fs.js -require.register("browser/path.js", function(module, exports, require){ + require.register('browser/path.js', function (module, exports, require) { -}); // module: browser/path.js + }) // module: browser/path.js -require.register("browser/progress.js", function(module, exports, require){ -/** + require.register('browser/progress.js', function (module, exports, require) { + /** * Expose `Progress`. */ -module.exports = Progress; + module.exports = Progress -/** + /** * Initialize a new `Progress` indicator. */ -function Progress() { - this.percent = 0; - this.size(0); - this.fontSize(11); - this.font('helvetica, arial, sans-serif'); -} + function Progress () { + this.percent = 0 + this.size(0) + this.fontSize(11) + this.font('helvetica, arial, sans-serif') + } -/** + /** * Set progress size to `n`. * * @param {Number} n @@ -629,12 +623,12 @@ function Progress() { * @api public */ -Progress.prototype.size = function(n){ - this._size = n; - return this; -}; + Progress.prototype.size = function (n) { + this._size = n + return this + } -/** + /** * Set text to `str`. * * @param {String} str @@ -642,12 +636,12 @@ Progress.prototype.size = function(n){ * @api public */ -Progress.prototype.text = function(str){ - this._text = str; - return this; -}; + Progress.prototype.text = function (str) { + this._text = str + return this + } -/** + /** * Set font size to `n`. * * @param {Number} n @@ -655,117 +649,113 @@ Progress.prototype.text = function(str){ * @api public */ -Progress.prototype.fontSize = function(n){ - this._fontSize = n; - return this; -}; + Progress.prototype.fontSize = function (n) { + this._fontSize = n + return this + } -/** + /** * Set font `family`. * * @param {String} family * @return {Progress} for chaining */ -Progress.prototype.font = function(family){ - this._font = family; - return this; -}; + Progress.prototype.font = function (family) { + this._font = family + return this + } -/** + /** * Update percentage to `n`. * * @param {Number} n * @return {Progress} for chaining */ -Progress.prototype.update = function(n){ - this.percent = n; - return this; -}; + Progress.prototype.update = function (n) { + this.percent = n + return this + } -/** + /** * Draw on `ctx`. * * @param {CanvasRenderingContext2d} ctx * @return {Progress} for chaining */ -Progress.prototype.draw = function(ctx){ - try { - var percent = Math.min(this.percent, 100) - , size = this._size - , half = size / 2 - , x = half - , y = half - , rad = half - 1 - , fontSize = this._fontSize; - - ctx.font = fontSize + 'px ' + this._font; - - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); - - // outer circle - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); - - // inner circle - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); - - // text - var text = this._text || (percent | 0) + '%' - , w = ctx.measureText(text).width; - - ctx.fillText( - text - , x - w / 2 + 1 - , y + fontSize / 2 - 1); - } catch (ex) {} //don't fail if we can't render progress - return this; -}; - -}); // module: browser/progress.js - -require.register("browser/tty.js", function(module, exports, require){ - -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - if ('innerHeight' in global) { - return [global.innerHeight, global.innerWidth]; - } else { - // In a Web Worker, the DOM Window is not available. - return [640, 480]; - } -}; + Progress.prototype.draw = function (ctx) { + try { + var percent = Math.min(this.percent, 100) + var size = this._size + var half = size / 2 + var x = half + var y = half + var rad = half - 1 + var fontSize = this._fontSize + + ctx.font = fontSize + 'px ' + this._font + + var angle = Math.PI * 2 * (percent / 100) + ctx.clearRect(0, 0, size, size) + + // outer circle + ctx.strokeStyle = '#9f9f9f' + ctx.beginPath() + ctx.arc(x, y, rad, 0, angle, false) + ctx.stroke() + + // inner circle + ctx.strokeStyle = '#eee' + ctx.beginPath() + ctx.arc(x, y, rad - 1, 0, angle, true) + ctx.stroke() + + // text + var text = this._text || (percent | 0) + '%' + var w = ctx.measureText(text).width + + ctx.fillText( + text + , x - w / 2 + 1 + , y + fontSize / 2 - 1) + } catch (ex) {} // don't fail if we can't render progress + return this + } + }) // module: browser/progress.js -}); // module: browser/tty.js + require.register('browser/tty.js', function (module, exports, require) { + exports.isatty = function () { + return true + } -require.register("context.js", function(module, exports, require){ + exports.getWindowSize = function () { + if ('innerHeight' in global) { + return [global.innerHeight, global.innerWidth] + } else { + // In a Web Worker, the DOM Window is not available. + return [640, 480] + } + } + }) // module: browser/tty.js -/** + require.register('context.js', function (module, exports, require) { + /** * Expose `Context`. */ -module.exports = Context; + module.exports = Context -/** + /** * Initialize a new `Context`. * * @api private */ -function Context(){} + function Context () {} -/** + /** * Set or get the context `Runnable` to `runnable`. * * @param {Runnable} runnable @@ -773,13 +763,13 @@ function Context(){} * @api private */ -Context.prototype.runnable = function(runnable){ - if (0 == arguments.length) return this._runnable; - this.test = this._runnable = runnable; - return this; -}; + Context.prototype.runnable = function (runnable) { + if (arguments.length == 0) return this._runnable + this.test = this._runnable = runnable + return this + } -/** + /** * Set test timeout `ms`. * * @param {Number} ms @@ -787,12 +777,12 @@ Context.prototype.runnable = function(runnable){ * @api private */ -Context.prototype.timeout = function(ms){ - this.runnable().timeout(ms); - return this; -}; + Context.prototype.timeout = function (ms) { + this.runnable().timeout(ms) + return this + } -/** + /** * Set test slowness threshold `ms`. * * @param {Number} ms @@ -800,43 +790,41 @@ Context.prototype.timeout = function(ms){ * @api private */ -Context.prototype.slow = function(ms){ - this.runnable().slow(ms); - return this; -}; + Context.prototype.slow = function (ms) { + this.runnable().slow(ms) + return this + } -/** + /** * Inspect the context void of `._runnable`. * * @return {String} * @api private */ -Context.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_runnable' == key) return; - if ('test' == key) return; - return val; - }, 2); -}; - -}); // module: context.js - -require.register("hook.js", function(module, exports, require){ + Context.prototype.inspect = function () { + return JSON.stringify(this, function (key, val) { + if (key == '_runnable') return + if (key == 'test') return + return val + }, 2) + } + }) // module: context.js -/** + require.register('hook.js', function (module, exports, require) { + /** * Module dependencies. */ -var Runnable = require('./runnable'); + var Runnable = require('./runnable') -/** + /** * Expose `Hook`. */ -module.exports = Hook; + module.exports = Hook -/** + /** * Initialize a new `Hook` with the given `title` and callback `fn`. * * @param {String} title @@ -844,22 +832,21 @@ module.exports = Hook; * @api private */ -function Hook(title, fn) { - Runnable.call(this, title, fn); - this.type = 'hook'; -} + function Hook (title, fn) { + Runnable.call(this, title, fn) + this.type = 'hook' + } -/** + /** * Inherit from `Runnable.prototype`. */ -function F(){}; -F.prototype = Runnable.prototype; -Hook.prototype = new F; -Hook.prototype.constructor = Hook; + function F () {}; + F.prototype = Runnable.prototype + Hook.prototype = new F() + Hook.prototype.constructor = Hook - -/** + /** * Get or set the test `err`. * * @param {Error} err @@ -867,29 +854,27 @@ Hook.prototype.constructor = Hook; * @api public */ -Hook.prototype.error = function(err){ - if (0 == arguments.length) { - var err = this._error; - this._error = null; - return err; - } - - this._error = err; -}; - -}); // module: hook.js + Hook.prototype.error = function (err) { + if (arguments.length == 0) { + var err = this._error + this._error = null + return err + } -require.register("interfaces/bdd.js", function(module, exports, require){ + this._error = err + } + }) // module: hook.js -/** + require.register('interfaces/bdd.js', function (module, exports, require) { + /** * Module dependencies. */ -var Suite = require('../suite') - , Test = require('../test') - , utils = require('../utils'); + var Suite = require('../suite') + var Test = require('../test') + var utils = require('../utils') -/** + /** * BDD-style interface: * * describe('Array', function(){ @@ -906,130 +891,127 @@ var Suite = require('../suite') * */ -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ + module.exports = function (suite) { + var suites = [suite] - /** + suite.on('pre-require', function (context, file, mocha) { + /** * Execute before running tests. */ - context.before = function(name, fn){ - suites[0].beforeAll(name, fn); - }; + context.before = function (name, fn) { + suites[0].beforeAll(name, fn) + } - /** + /** * Execute after running tests. */ - context.after = function(name, fn){ - suites[0].afterAll(name, fn); - }; + context.after = function (name, fn) { + suites[0].afterAll(name, fn) + } - /** + /** * Execute before each test case. */ - context.beforeEach = function(name, fn){ - suites[0].beforeEach(name, fn); - }; + context.beforeEach = function (name, fn) { + suites[0].beforeEach(name, fn) + } - /** + /** * Execute after each test case. */ - context.afterEach = function(name, fn){ - suites[0].afterEach(name, fn); - }; + context.afterEach = function (name, fn) { + suites[0].afterEach(name, fn) + } - /** + /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ - context.describe = context.context = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; + context.describe = context.context = function (title, fn) { + var suite = Suite.create(suites[0], title) + suites.unshift(suite) + fn.call(suite) + suites.shift() + return suite + } - /** + /** * Pending describe. */ - context.xdescribe = + context.xdescribe = context.xcontext = - context.describe.skip = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; + context.describe.skip = function (title, fn) { + var suite = Suite.create(suites[0], title) + suite.pending = true + suites.unshift(suite) + fn.call(suite) + suites.shift() + } - /** + /** * Exclusive suite. */ - context.describe.only = function(title, fn){ - var suite = context.describe(title, fn); - mocha.grep(suite.fullTitle()); - return suite; - }; + context.describe.only = function (title, fn) { + var suite = context.describe(title, fn) + mocha.grep(suite.fullTitle()) + return suite + } - /** + /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ - context.it = context.specify = function(title, fn){ - var suite = suites[0]; - if (suite.pending) var fn = null; - var test = new Test(title, fn); - suite.addTest(test); - return test; - }; + context.it = context.specify = function (title, fn) { + var suite = suites[0] + if (suite.pending) var fn = null + var test = new Test(title, fn) + suite.addTest(test) + return test + } - /** + /** * Exclusive test-case. */ - context.it.only = function(title, fn){ - var test = context.it(title, fn); - var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - return test; - }; + context.it.only = function (title, fn) { + var test = context.it(title, fn) + var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$' + mocha.grep(new RegExp(reString)) + return test + } - /** + /** * Pending test case. */ - context.xit = + context.xit = context.xspecify = - context.it.skip = function(title){ - context.it(title); - }; - }); -}; - -}); // module: interfaces/bdd.js - -require.register("interfaces/exports.js", function(module, exports, require){ + context.it.skip = function (title) { + context.it(title) + } + }) + } + }) // module: interfaces/bdd.js -/** + require.register('interfaces/exports.js', function (module, exports, require) { + /** * Module dependencies. */ -var Suite = require('../suite') - , Test = require('../test'); + var Suite = require('../suite') + var Test = require('../test') -/** + /** * TDD-style interface: * * exports.Array = { @@ -1046,64 +1028,60 @@ var Suite = require('../suite') * */ -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - suites[0].addTest(new Test(key, fn)); + module.exports = function (suite) { + var suites = [suite] + + suite.on('require', visit) + + function visit (obj) { + var suite + for (var key in obj) { + if (typeof obj[key] === 'function') { + var fn = obj[key] + switch (key) { + case 'before': + suites[0].beforeAll(fn) + break + case 'after': + suites[0].afterAll(fn) + break + case 'beforeEach': + suites[0].beforeEach(fn) + break + case 'afterEach': + suites[0].afterEach(fn) + break + default: + suites[0].addTest(new Test(key, fn)) + } + } else { + var suite = Suite.create(suites[0], key) + suites.unshift(suite) + visit(obj[key]) + suites.shift() + } } - } else { - var suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); } } - } -}; - -}); // module: interfaces/exports.js - -require.register("interfaces/index.js", function(module, exports, require){ + }) // module: interfaces/exports.js -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.qunit = require('./qunit'); -exports.exports = require('./exports'); + require.register('interfaces/index.js', function (module, exports, require) { + exports.bdd = require('./bdd') + exports.tdd = require('./tdd') + exports.qunit = require('./qunit') + exports.exports = require('./exports') + }) // module: interfaces/index.js -}); // module: interfaces/index.js - -require.register("interfaces/qunit.js", function(module, exports, require){ - -/** + require.register('interfaces/qunit.js', function (module, exports, require) { + /** * Module dependencies. */ -var Suite = require('../suite') - , Test = require('../test') - , utils = require('../utils'); + var Suite = require('../suite') + var Test = require('../test') + var utils = require('../utils') -/** + /** * QUnit-style interface: * * suite('Array'); @@ -1128,108 +1106,105 @@ var Suite = require('../suite') * */ -module.exports = function(suite){ - var suites = [suite]; + module.exports = function (suite) { + var suites = [suite] - suite.on('pre-require', function(context, file, mocha){ - - /** + suite.on('pre-require', function (context, file, mocha) { + /** * Execute before running tests. */ - context.before = function(name, fn){ - suites[0].beforeAll(name, fn); - }; + context.before = function (name, fn) { + suites[0].beforeAll(name, fn) + } - /** + /** * Execute after running tests. */ - context.after = function(name, fn){ - suites[0].afterAll(name, fn); - }; + context.after = function (name, fn) { + suites[0].afterAll(name, fn) + } - /** + /** * Execute before each test case. */ - context.beforeEach = function(name, fn){ - suites[0].beforeEach(name, fn); - }; + context.beforeEach = function (name, fn) { + suites[0].beforeEach(name, fn) + } - /** + /** * Execute after each test case. */ - context.afterEach = function(name, fn){ - suites[0].afterEach(name, fn); - }; + context.afterEach = function (name, fn) { + suites[0].afterEach(name, fn) + } - /** + /** * Describe a "suite" with the given `title`. */ - context.suite = function(title){ - if (suites.length > 1) suites.shift(); - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - return suite; - }; + context.suite = function (title) { + if (suites.length > 1) suites.shift() + var suite = Suite.create(suites[0], title) + suites.unshift(suite) + return suite + } - /** + /** * Exclusive test-case. */ - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; + context.suite.only = function (title, fn) { + var suite = context.suite(title, fn) + mocha.grep(suite.fullTitle()) + } - /** + /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ - context.test = function(title, fn){ - var test = new Test(title, fn); - suites[0].addTest(test); - return test; - }; + context.test = function (title, fn) { + var test = new Test(title, fn) + suites[0].addTest(test) + return test + } - /** + /** * Exclusive test-case. */ - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; + context.test.only = function (title, fn) { + var test = context.test(title, fn) + var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$' + mocha.grep(new RegExp(reString)) + } - /** + /** * Pending test case. */ - context.test.skip = function(title){ - context.test(title); - }; - }); -}; - -}); // module: interfaces/qunit.js - -require.register("interfaces/tdd.js", function(module, exports, require){ + context.test.skip = function (title) { + context.test(title) + } + }) + } + }) // module: interfaces/qunit.js -/** + require.register('interfaces/tdd.js', function (module, exports, require) { + /** * Module dependencies. */ -var Suite = require('../suite') - , Test = require('../test') - , utils = require('../utils');; + var Suite = require('../suite') + var Test = require('../test') + var utils = require('../utils') -/** + /** * TDD-style interface: * * suite('Array', function(){ @@ -1254,148 +1229,146 @@ var Suite = require('../suite') * */ -module.exports = function(suite){ - var suites = [suite]; + module.exports = function (suite) { + var suites = [suite] - suite.on('pre-require', function(context, file, mocha){ - - /** + suite.on('pre-require', function (context, file, mocha) { + /** * Execute before each test case. */ - context.setup = function(name, fn){ - suites[0].beforeEach(name, fn); - }; + context.setup = function (name, fn) { + suites[0].beforeEach(name, fn) + } - /** + /** * Execute after each test case. */ - context.teardown = function(name, fn){ - suites[0].afterEach(name, fn); - }; + context.teardown = function (name, fn) { + suites[0].afterEach(name, fn) + } - /** + /** * Execute before the suite. */ - context.suiteSetup = function(name, fn){ - suites[0].beforeAll(name, fn); - }; + context.suiteSetup = function (name, fn) { + suites[0].beforeAll(name, fn) + } - /** + /** * Execute after the suite. */ - context.suiteTeardown = function(name, fn){ - suites[0].afterAll(name, fn); - }; + context.suiteTeardown = function (name, fn) { + suites[0].afterAll(name, fn) + } - /** + /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; + context.suite = function (title, fn) { + var suite = Suite.create(suites[0], title) + suites.unshift(suite) + fn.call(suite) + suites.shift() + return suite + } - /** + /** * Pending suite. */ - context.suite.skip = function(title, fn) { - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; + context.suite.skip = function (title, fn) { + var suite = Suite.create(suites[0], title) + suite.pending = true + suites.unshift(suite) + fn.call(suite) + suites.shift() + } - /** + /** * Exclusive test-case. */ - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; + context.suite.only = function (title, fn) { + var suite = context.suite(title, fn) + mocha.grep(suite.fullTitle()) + } - /** + /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ - context.test = function(title, fn){ - var suite = suites[0]; - if (suite.pending) var fn = null; - var test = new Test(title, fn); - suite.addTest(test); - return test; - }; + context.test = function (title, fn) { + var suite = suites[0] + if (suite.pending) var fn = null + var test = new Test(title, fn) + suite.addTest(test) + return test + } - /** + /** * Exclusive test-case. */ - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; + context.test.only = function (title, fn) { + var test = context.test(title, fn) + var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$' + mocha.grep(new RegExp(reString)) + } - /** + /** * Pending test case. */ - context.test.skip = function(title){ - context.test(title); - }; - }); -}; - -}); // module: interfaces/tdd.js + context.test.skip = function (title) { + context.test(title) + } + }) + } + }) // module: interfaces/tdd.js -require.register("mocha.js", function(module, exports, require){ -/*! + require.register('mocha.js', function (module, exports, require) { + /*! * mocha * Copyright(c) 2011 TJ Holowaychuk * MIT Licensed */ -/** + /** * Module dependencies. */ -var path = require('browser/path') - , utils = require('./utils'); + var path = require('browser/path') + var utils = require('./utils') -/** + /** * Expose `Mocha`. */ -exports = module.exports = Mocha; + exports = module.exports = Mocha -/** + /** * Expose internals. */ -exports.utils = utils; -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Context = require('./context'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); + exports.utils = utils + exports.interfaces = require('./interfaces') + exports.reporters = require('./reporters') + exports.Runnable = require('./runnable') + exports.Context = require('./context') + exports.Runner = require('./runner') + exports.Suite = require('./suite') + exports.Hook = require('./hook') + exports.Test = require('./test') -/** + /** * Return image `name` path. * * @param {String} name @@ -1403,11 +1376,11 @@ exports.Test = require('./test'); * @api private */ -function image(name) { - return __dirname + '/../images/' + name + '.png'; -} + function image (name) { + return __dirname + '/../images/' + name + '.png' + } -/** + /** * Setup mocha with `options`. * * Options: @@ -1425,145 +1398,146 @@ function image(name) { * @api public */ -function Mocha(options) { - options = options || {}; - this.files = []; - this.options = options; - this.grep(options.grep); - this.suite = new exports.Suite('', new exports.Context); - this.ui(options.ui); - this.bail(options.bail); - this.reporter(options.reporter); - if (null != options.timeout) this.timeout(options.timeout); - this.useColors(options.useColors) - if (options.slow) this.slow(options.slow); - - this.suite.on('pre-require', function (context) { - exports.afterEach = context.afterEach || context.teardown; - exports.after = context.after || context.suiteTeardown; - exports.beforeEach = context.beforeEach || context.setup; - exports.before = context.before || context.suiteSetup; - exports.describe = context.describe || context.suite; - exports.it = context.it || context.test; - exports.setup = context.setup || context.beforeEach; - exports.suiteSetup = context.suiteSetup || context.before; - exports.suiteTeardown = context.suiteTeardown || context.after; - exports.suite = context.suite || context.describe; - exports.teardown = context.teardown || context.afterEach; - exports.test = context.test || context.it; - }); -} - -/** + function Mocha (options) { + options = options || {} + this.files = [] + this.options = options + this.grep(options.grep) + this.suite = new exports.Suite('', new exports.Context()) + this.ui(options.ui) + this.bail(options.bail) + this.reporter(options.reporter) + if (options.timeout != null) this.timeout(options.timeout) + this.useColors(options.useColors) + if (options.slow) this.slow(options.slow) + + this.suite.on('pre-require', function (context) { + exports.afterEach = context.afterEach || context.teardown + exports.after = context.after || context.suiteTeardown + exports.beforeEach = context.beforeEach || context.setup + exports.before = context.before || context.suiteSetup + exports.describe = context.describe || context.suite + exports.it = context.it || context.test + exports.setup = context.setup || context.beforeEach + exports.suiteSetup = context.suiteSetup || context.before + exports.suiteTeardown = context.suiteTeardown || context.after + exports.suite = context.suite || context.describe + exports.teardown = context.teardown || context.afterEach + exports.test = context.test || context.it + }) + } + + /** * Enable or disable bailing on the first failure. * * @param {Boolean} [bail] * @api public */ -Mocha.prototype.bail = function(bail){ - if (0 == arguments.length) bail = true; - this.suite.bail(bail); - return this; -}; + Mocha.prototype.bail = function (bail) { + if (arguments.length == 0) bail = true + this.suite.bail(bail) + return this + } -/** + /** * Add test `file`. * * @param {String} file * @api public */ -Mocha.prototype.addFile = function(file){ - this.files.push(file); - return this; -}; + Mocha.prototype.addFile = function (file) { + this.files.push(file) + return this + } -/** + /** * Set reporter to `reporter`, defaults to "dot". * * @param {String|Function} reporter name or constructor * @api public */ -Mocha.prototype.reporter = function(reporter){ - if ('function' == typeof reporter) { - this._reporter = reporter; - } else { - reporter = reporter || 'dot'; - var _reporter; - try { _reporter = require('./reporters/' + reporter); } catch (err) {}; - if (!_reporter) try { _reporter = require(reporter); } catch (err) {}; - if (!_reporter && reporter === 'teamcity') - console.warn('The Teamcity reporter was moved to a package named ' + + Mocha.prototype.reporter = function (reporter) { + if (typeof reporter === 'function') { + this._reporter = reporter + } else { + reporter = reporter || 'dot' + var _reporter + try { _reporter = require('./reporters/' + reporter) } catch (err) {}; + if (!_reporter) try { _reporter = require(reporter) } catch (err) {}; + if (!_reporter && reporter === 'teamcity') { + console.warn('The Teamcity reporter was moved to a package named ' + 'mocha-teamcity-reporter ' + - '(https://npmjs.org/package/mocha-teamcity-reporter).'); - if (!_reporter) throw new Error('invalid reporter "' + reporter + '"'); - this._reporter = _reporter; - } - return this; -}; + '(https://npmjs.org/package/mocha-teamcity-reporter).') + } + if (!_reporter) throw new Error('invalid reporter "' + reporter + '"') + this._reporter = _reporter + } + return this + } -/** + /** * Set test UI `name`, defaults to "bdd". * * @param {String} bdd * @api public */ -Mocha.prototype.ui = function(name){ - name = name || 'bdd'; - this._ui = exports.interfaces[name]; - if (!this._ui) try { this._ui = require(name); } catch (err) {}; - if (!this._ui) throw new Error('invalid interface "' + name + '"'); - this._ui = this._ui(this.suite); - return this; -}; + Mocha.prototype.ui = function (name) { + name = name || 'bdd' + this._ui = exports.interfaces[name] + if (!this._ui) try { this._ui = require(name) } catch (err) {}; + if (!this._ui) throw new Error('invalid interface "' + name + '"') + this._ui = this._ui(this.suite) + return this + } -/** + /** * Load registered files. * * @api private */ -Mocha.prototype.loadFiles = function(fn){ - var self = this; - var suite = this.suite; - var pending = this.files.length; - this.files.forEach(function(file){ - file = path.resolve(file); - suite.emit('pre-require', global, file, self); - suite.emit('require', require(file), file, self); - suite.emit('post-require', global, file, self); - --pending || (fn && fn()); - }); -}; - -/** + Mocha.prototype.loadFiles = function (fn) { + var self = this + var suite = this.suite + var pending = this.files.length + this.files.forEach(function (file) { + file = path.resolve(file) + suite.emit('pre-require', global, file, self) + suite.emit('require', require(file), file, self) + suite.emit('post-require', global, file, self) + --pending || (fn && fn()) + }) + } + + /** * Enable growl support. * * @api private */ -Mocha.prototype._growl = function(runner, reporter) { - var notify = require('growl'); + Mocha.prototype._growl = function (runner, reporter) { + var notify = require('growl') - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + runner.total + ' tests failed'; - notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: image('ok') - }); + runner.on('end', function () { + var stats = reporter.stats + if (stats.failures) { + var msg = stats.failures + ' of ' + runner.total + ' tests failed' + notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }) + } else { + notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { + name: 'mocha', + title: 'Passed', + image: image('ok') + }) + } + }) } - }); -}; -/** + /** * Add regexp to grep, if `re` is a string it is escaped. * * @param {RegExp|String} re @@ -1571,26 +1545,26 @@ Mocha.prototype._growl = function(runner, reporter) { * @api public */ -Mocha.prototype.grep = function(re){ - this.options.grep = 'string' == typeof re - ? new RegExp(utils.escapeRegexp(re)) - : re; - return this; -}; + Mocha.prototype.grep = function (re) { + this.options.grep = typeof re === 'string' + ? new RegExp(utils.escapeRegexp(re)) + : re + return this + } -/** + /** * Invert `.grep()` matches. * * @return {Mocha} * @api public */ -Mocha.prototype.invert = function(){ - this.options.invert = true; - return this; -}; + Mocha.prototype.invert = function () { + this.options.invert = true + return this + } -/** + /** * Ignore global leaks. * * @param {Boolean} ignore @@ -1598,36 +1572,36 @@ Mocha.prototype.invert = function(){ * @api public */ -Mocha.prototype.ignoreLeaks = function(ignore){ - this.options.ignoreLeaks = !!ignore; - return this; -}; + Mocha.prototype.ignoreLeaks = function (ignore) { + this.options.ignoreLeaks = !!ignore + return this + } -/** + /** * Enable global leak checking. * * @return {Mocha} * @api public */ -Mocha.prototype.checkLeaks = function(){ - this.options.ignoreLeaks = false; - return this; -}; + Mocha.prototype.checkLeaks = function () { + this.options.ignoreLeaks = false + return this + } -/** + /** * Enable growl support. * * @return {Mocha} * @api public */ -Mocha.prototype.growl = function(){ - this.options.growl = true; - return this; -}; + Mocha.prototype.growl = function () { + this.options.growl = true + return this + } -/** + /** * Ignore `globals` array or string. * * @param {Array|String} globals @@ -1635,12 +1609,12 @@ Mocha.prototype.growl = function(){ * @api public */ -Mocha.prototype.globals = function(globals){ - this.options.globals = (this.options.globals || []).concat(globals); - return this; -}; + Mocha.prototype.globals = function (globals) { + this.options.globals = (this.options.globals || []).concat(globals) + return this + } -/** + /** * Emit color output. * * @param {Boolean} colors @@ -1648,14 +1622,14 @@ Mocha.prototype.globals = function(globals){ * @api public */ -Mocha.prototype.useColors = function(colors){ - this.options.useColors = arguments.length && colors != undefined - ? colors - : true; - return this; -}; + Mocha.prototype.useColors = function (colors) { + this.options.useColors = arguments.length && colors != undefined + ? colors + : true + return this + } -/** + /** * Use inline diffs rather than +/-. * * @param {Boolean} inlineDiffs @@ -1663,14 +1637,14 @@ Mocha.prototype.useColors = function(colors){ * @api public */ -Mocha.prototype.useInlineDiffs = function(inlineDiffs) { - this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined - ? inlineDiffs - : false; - return this; -}; + Mocha.prototype.useInlineDiffs = function (inlineDiffs) { + this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined + ? inlineDiffs + : false + return this + } -/** + /** * Set the timeout in milliseconds. * * @param {Number} timeout @@ -1678,12 +1652,12 @@ Mocha.prototype.useInlineDiffs = function(inlineDiffs) { * @api public */ -Mocha.prototype.timeout = function(timeout){ - this.suite.timeout(timeout); - return this; -}; + Mocha.prototype.timeout = function (timeout) { + this.suite.timeout(timeout) + return this + } -/** + /** * Set slowness threshold in milliseconds. * * @param {Number} slow @@ -1691,24 +1665,24 @@ Mocha.prototype.timeout = function(timeout){ * @api public */ -Mocha.prototype.slow = function(slow){ - this.suite.slow(slow); - return this; -}; + Mocha.prototype.slow = function (slow) { + this.suite.slow(slow) + return this + } -/** + /** * Makes all tests async (accepting a callback) * * @return {Mocha} * @api public */ -Mocha.prototype.asyncOnly = function(){ - this.options.asyncOnly = true; - return this; -}; + Mocha.prototype.asyncOnly = function () { + this.options.asyncOnly = true + return this + } -/** + /** * Run tests and invoke `fn()` when complete. * * @param {Function} fn @@ -1716,37 +1690,36 @@ Mocha.prototype.asyncOnly = function(){ * @api public */ -Mocha.prototype.run = function(fn){ - if (this.files.length) this.loadFiles(); - var suite = this.suite; - var options = this.options; - options.files = this.files; - var runner = new exports.Runner(suite); - var reporter = new this._reporter(runner, options); - runner.ignoreLeaks = false !== options.ignoreLeaks; - runner.asyncOnly = options.asyncOnly; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - exports.reporters.Base.useColors = options.useColors; - exports.reporters.Base.inlineDiffs = options.useInlineDiffs; - return runner.run(fn); -}; - -}); // module: mocha.js - -require.register("ms.js", function(module, exports, require){ -/** + Mocha.prototype.run = function (fn) { + if (this.files.length) this.loadFiles() + var suite = this.suite + var options = this.options + options.files = this.files + var runner = new exports.Runner(suite) + var reporter = new this._reporter(runner, options) + runner.ignoreLeaks = options.ignoreLeaks !== false + runner.asyncOnly = options.asyncOnly + if (options.grep) runner.grep(options.grep, options.invert) + if (options.globals) runner.globals(options.globals) + if (options.growl) this._growl(runner, reporter) + exports.reporters.Base.useColors = options.useColors + exports.reporters.Base.inlineDiffs = options.useInlineDiffs + return runner.run(fn) + } + }) // module: mocha.js + + require.register('ms.js', function (module, exports, require) { + /** * Helpers. */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; + var s = 1000 + var m = s * 60 + var h = m * 60 + var d = h * 24 + var y = d * 365.25 -/** + /** * Parse or format the given `val`. * * Options: @@ -1759,13 +1732,13 @@ var y = d * 365.25; * @api public */ -module.exports = function(val, options){ - options = options || {}; - if ('string' == typeof val) return parse(val); - return options.long ? longFormat(val) : shortFormat(val); -}; + module.exports = function (val, options) { + options = options || {} + if (typeof val === 'string') return parse(val) + return options.long ? longFormat(val) : shortFormat(val) + } -/** + /** * Parse the given `str` and return milliseconds. * * @param {String} str @@ -1773,38 +1746,38 @@ module.exports = function(val, options){ * @api private */ -function parse(str) { - var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!match) return; - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 's': - return n * s; - case 'ms': - return n; - } -} + function parse (str) { + var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str) + if (!match) return + var n = parseFloat(match[1]) + var type = (match[2] || 'ms').toLowerCase() + switch (type) { + case 'years': + case 'year': + case 'y': + return n * y + case 'days': + case 'day': + case 'd': + return n * d + case 'hours': + case 'hour': + case 'h': + return n * h + case 'minutes': + case 'minute': + case 'm': + return n * m + case 'seconds': + case 'second': + case 's': + return n * s + case 'ms': + return n + } + } -/** + /** * Short format for `ms`. * * @param {Number} ms @@ -1812,15 +1785,15 @@ function parse(str) { * @api private */ -function shortFormat(ms) { - if (ms >= d) return Math.round(ms / d) + 'd'; - if (ms >= h) return Math.round(ms / h) + 'h'; - if (ms >= m) return Math.round(ms / m) + 'm'; - if (ms >= s) return Math.round(ms / s) + 's'; - return ms + 'ms'; -} + function shortFormat (ms) { + if (ms >= d) return Math.round(ms / d) + 'd' + if (ms >= h) return Math.round(ms / h) + 'h' + if (ms >= m) return Math.round(ms / m) + 'm' + if (ms >= s) return Math.round(ms / s) + 's' + return ms + 'ms' + } -/** + /** * Long format for `ms`. * * @param {Number} ms @@ -1828,115 +1801,113 @@ function shortFormat(ms) { * @api private */ -function longFormat(ms) { - return plural(ms, d, 'day') - || plural(ms, h, 'hour') - || plural(ms, m, 'minute') - || plural(ms, s, 'second') - || ms + ' ms'; -} + function longFormat (ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms' + } -/** + /** * Pluralization helper. */ -function plural(ms, n, name) { - if (ms < n) return; - if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; - return Math.ceil(ms / n) + ' ' + name + 's'; -} - -}); // module: ms.js - -require.register("reporters/base.js", function(module, exports, require){ + function plural (ms, n, name) { + if (ms < n) return + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name + return Math.ceil(ms / n) + ' ' + name + 's' + } + }) // module: ms.js -/** + require.register('reporters/base.js', function (module, exports, require) { + /** * Module dependencies. */ -var tty = require('browser/tty') - , diff = require('browser/diff') - , ms = require('../ms') - , utils = require('../utils'); + var tty = require('browser/tty') + var diff = require('browser/diff') + var ms = require('../ms') + var utils = require('../utils') -/** + /** * Save timer references to avoid Sinon interfering (see GH-237). */ -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; + var Date = global.Date + var setTimeout = global.setTimeout + var setInterval = global.setInterval + var clearTimeout = global.clearTimeout + var clearInterval = global.clearInterval -/** + /** * Check if both stdio streams are associated with a tty. */ -var isatty = tty.isatty(1) && tty.isatty(2); + var isatty = tty.isatty(1) && tty.isatty(2) -/** + /** * Expose `Base`. */ -exports = module.exports = Base; + exports = module.exports = Base -/** + /** * Enable coloring by default. */ -exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined); + exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined) -/** + /** * Inline diffs instead of +/- */ -exports.inlineDiffs = false; + exports.inlineDiffs = false -/** + /** * Default color map. */ -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': 0 - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 - , 'diff gutter': 90 - , 'diff added': 42 - , 'diff removed': 41 -}; - -/** + exports.colors = { + pass: 90, + fail: 31, + 'bright pass': 92, + 'bright fail': 91, + 'bright yellow': 93, + pending: 36, + suite: 0, + 'error title': 0, + 'error message': 31, + 'error stack': 90, + checkmark: 32, + fast: 90, + medium: 33, + slow: 31, + green: 32, + light: 90, + 'diff gutter': 90, + 'diff added': 42, + 'diff removed': 41 + } + + /** * Default symbol map. */ -exports.symbols = { - ok: '✓', - err: '✖', - dot: '․' -}; + exports.symbols = { + ok: '✓', + err: '✖', + dot: '․' + } -// With node.js on Windows: use symbols available in terminal default fonts -if ('win32' == process.platform) { - exports.symbols.ok = '\u221A'; - exports.symbols.err = '\u00D7'; - exports.symbols.dot = '.'; -} + // With node.js on Windows: use symbols available in terminal default fonts + if (process.platform == 'win32') { + exports.symbols.ok = '\u221A' + exports.symbols.err = '\u00D7' + exports.symbols.dot = '.' + } -/** + /** * Color `str` with the given `type`, * allowing colors to be disabled, * as well as user-defined color @@ -1948,115 +1919,115 @@ if ('win32' == process.platform) { * @api private */ -var color = exports.color = function(type, str) { - if (!exports.useColors) return str; - return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; -}; + var color = exports.color = function (type, str) { + if (!exports.useColors) return str + return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m' + } -/** + /** * Expose term window size, with some * defaults for when stderr is not a tty. */ -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; + exports.window = { + width: isatty + ? process.stdout.getWindowSize + ? process.stdout.getWindowSize(1)[0] + : tty.getWindowSize()[1] + : 75 + } -/** + /** * Expose some basic cursor interactions * that are common among reporters. */ -exports.cursor = { - hide: function(){ - isatty && process.stdout.write('\u001b[?25l'); - }, + exports.cursor = { + hide: function () { + isatty && process.stdout.write('\u001b[?25l') + }, - show: function(){ - isatty && process.stdout.write('\u001b[?25h'); - }, + show: function () { + isatty && process.stdout.write('\u001b[?25h') + }, - deleteLine: function(){ - isatty && process.stdout.write('\u001b[2K'); - }, + deleteLine: function () { + isatty && process.stdout.write('\u001b[2K') + }, - beginningOfLine: function(){ - isatty && process.stdout.write('\u001b[0G'); - }, + beginningOfLine: function () { + isatty && process.stdout.write('\u001b[0G') + }, - CR: function(){ - if (isatty) { - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); - } else { - process.stdout.write('\r'); + CR: function () { + if (isatty) { + exports.cursor.deleteLine() + exports.cursor.beginningOfLine() + } else { + process.stdout.write('\r') + } + } } - } -}; -/** + /** * Outut the given `failures` as a list. * * @param {Array} failures * @api public */ -exports.list = function(failures){ - console.error(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var err = test.err - , message = err.message || '' - , stack = err.stack || message - , index = stack.indexOf(message) + message.length - , msg = stack.slice(0, index) - , actual = err.actual - , expected = err.expected - , escape = true; - - // uncaught - if (err.uncaught) { - msg = 'Uncaught ' + msg; - } - - // explicitly show diff - if (err.showDiff && sameType(actual, expected)) { - escape = false; - err.actual = actual = stringify(canonicalize(actual)); - err.expected = expected = stringify(canonicalize(expected)); - } - - // actual / expected diff - if ('string' == typeof actual && 'string' == typeof expected) { - fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); - var match = message.match(/^([^:]+): expected/); - msg = '\n ' + color('error message', match ? match[1] : msg); - - if (exports.inlineDiffs) { - msg += inlineDiff(err, escape); - } else { - msg += unifiedDiff(err, escape); - } - } + exports.list = function (failures) { + console.error() + failures.forEach(function (test, i) { + // format + var fmt = color('error title', ' %s) %s:\n') + + color('error message', ' %s') + + color('error stack', '\n%s\n') + + // msg + var err = test.err + var message = err.message || '' + var stack = err.stack || message + var index = stack.indexOf(message) + message.length + var msg = stack.slice(0, index) + var actual = err.actual + var expected = err.expected + var escape = true + + // uncaught + if (err.uncaught) { + msg = 'Uncaught ' + msg + } + + // explicitly show diff + if (err.showDiff && sameType(actual, expected)) { + escape = false + err.actual = actual = stringify(canonicalize(actual)) + err.expected = expected = stringify(canonicalize(expected)) + } + + // actual / expected diff + if (typeof actual === 'string' && typeof expected === 'string') { + fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n') + var match = message.match(/^([^:]+): expected/) + msg = '\n ' + color('error message', match ? match[1] : msg) + + if (exports.inlineDiffs) { + msg += inlineDiff(err, escape) + } else { + msg += unifiedDiff(err, escape) + } + } - // indent stack trace without msg - stack = stack.slice(index ? index + 1 : index) - .replace(/^/gm, ' '); + // indent stack trace without msg + stack = stack.slice(index ? index + 1 : index) + .replace(/^/gm, ' ') - console.error(fmt, (i + 1), test.fullTitle(), msg, stack); - }); -}; + console.error(fmt, (i + 1), test.fullTitle(), msg, stack) + }) + } -/** + /** * Initialize a new `Base` reporter. * * All other reporters generally @@ -2068,106 +2039,106 @@ exports.list = function(failures){ * @api public */ -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } - , failures = this.failures = []; + function Base (runner) { + var self = this + var stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } + var failures = this.failures = [] - if (!runner) return; - this.runner = runner; + if (!runner) return + this.runner = runner - runner.stats = stats; + runner.stats = stats - runner.on('start', function(){ - stats.start = new Date; - }); + runner.on('start', function () { + stats.start = new Date() + }) - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - suite.root || stats.suites++; - }); + runner.on('suite', function (suite) { + stats.suites = stats.suites || 0 + suite.root || stats.suites++ + }) - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); + runner.on('test end', function (test) { + stats.tests = stats.tests || 0 + stats.tests++ + }) - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; + runner.on('pass', function (test) { + stats.passes = stats.passes || 0 - var medium = test.slow() / 2; - test.speed = test.duration > test.slow() - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; + var medium = test.slow() / 2 + test.speed = test.duration > test.slow() + ? 'slow' + : test.duration > medium + ? 'medium' + : 'fast' - stats.passes++; - }); + stats.passes++ + }) - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); + runner.on('fail', function (test, err) { + stats.failures = stats.failures || 0 + stats.failures++ + test.err = err + failures.push(test) + }) - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); + runner.on('end', function () { + stats.end = new Date() + stats.duration = new Date() - stats.start + }) - runner.on('pending', function(){ - stats.pending++; - }); -} + runner.on('pending', function () { + stats.pending++ + }) + } -/** + /** * Output common epilogue used by many of * the bundled reporters. * * @api public */ -Base.prototype.epilogue = function(){ - var stats = this.stats; - var tests; - var fmt; + Base.prototype.epilogue = function () { + var stats = this.stats + var tests + var fmt - console.log(); + console.log() - // passes - fmt = color('bright pass', ' ') - + color('green', ' %d passing') - + color('light', ' (%s)'); + // passes + fmt = color('bright pass', ' ') + + color('green', ' %d passing') + + color('light', ' (%s)') - console.log(fmt, - stats.passes || 0, - ms(stats.duration)); + console.log(fmt, + stats.passes || 0, + ms(stats.duration)) - // pending - if (stats.pending) { - fmt = color('pending', ' ') - + color('pending', ' %d pending'); + // pending + if (stats.pending) { + fmt = color('pending', ' ') + + color('pending', ' %d pending') - console.log(fmt, stats.pending); - } + console.log(fmt, stats.pending) + } - // failures - if (stats.failures) { - fmt = color('fail', ' %d failing'); + // failures + if (stats.failures) { + fmt = color('fail', ' %d failing') - console.error(fmt, - stats.failures); + console.error(fmt, + stats.failures) - Base.list(this.failures); - console.error(); - } + Base.list(this.failures) + console.error() + } - console.log(); -}; + console.log() + } -/** + /** * Pad the given `str` to `len`. * * @param {String} str @@ -2176,13 +2147,12 @@ Base.prototype.epilogue = function(){ * @api private */ -function pad(str, len) { - str = String(str); - return Array(len - str.length + 1).join(' ') + str; -} - + function pad (str, len) { + str = String(str) + return Array(len - str.length + 1).join(' ') + str + } -/** + /** * Returns an inline diff between 2 strings with coloured ANSI output * * @param {Error} Error with actual/expected @@ -2190,33 +2160,33 @@ function pad(str, len) { * @api private */ -function inlineDiff(err, escape) { - var msg = errorDiff(err, 'WordsWithSpace', escape); + function inlineDiff (err, escape) { + var msg = errorDiff(err, 'WordsWithSpace', escape) - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } + // linenos + var lines = msg.split('\n') + if (lines.length > 4) { + var width = String(lines.length).length + msg = lines.map(function (str, i) { + return pad(++i, width) + ' |' + ' ' + str + }).join('\n') + } + + // legend + msg = '\n' + + color('diff removed', 'actual') + + ' ' + + color('diff added', 'expected') + + '\n\n' + + msg + + '\n' + + // indent + msg = msg.replace(/^/gm, ' ') + return msg + } - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; - - // indent - msg = msg.replace(/^/gm, ' '); - return msg; -} - -/** + /** * Returns a unified diff between 2 strings * * @param {Error} Error with actual/expected @@ -2224,31 +2194,31 @@ function inlineDiff(err, escape) { * @api private */ -function unifiedDiff(err, escape) { - var indent = ' '; - function cleanUp(line) { - if (escape) { - line = escapeInvisibles(line); + function unifiedDiff (err, escape) { + var indent = ' ' + function cleanUp (line) { + if (escape) { + line = escapeInvisibles(line) + } + if (line[0] === '+') return indent + colorLines('diff added', line) + if (line[0] === '-') return indent + colorLines('diff removed', line) + if (line.match(/\@\@/)) return null + if (line.match(/\\ No newline/)) return null + else return indent + line + } + function notBlank (line) { + return line != null + } + msg = diff.createPatch('string', err.actual, err.expected) + var lines = msg.split('\n').splice(4) + return '\n ' + + colorLines('diff added', '+ expected') + ' ' + + colorLines('diff removed', '- actual') + + '\n\n' + + lines.map(cleanUp).filter(notBlank).join('\n') } - if (line[0] === '+') return indent + colorLines('diff added', line); - if (line[0] === '-') return indent + colorLines('diff removed', line); - if (line.match(/\@\@/)) return null; - if (line.match(/\\ No newline/)) return null; - else return indent + line; - } - function notBlank(line) { - return line != null; - } - msg = diff.createPatch('string', err.actual, err.expected); - var lines = msg.split('\n').splice(4); - return '\n ' - + colorLines('diff added', '+ expected') + ' ' - + colorLines('diff removed', '- actual') - + '\n\n' - + lines.map(cleanUp).filter(notBlank).join('\n'); -} - -/** + + /** * Return a character diff for `err`. * * @param {Error} err @@ -2256,30 +2226,30 @@ function unifiedDiff(err, escape) { * @api private */ -function errorDiff(err, type, escape) { - var actual = escape ? escapeInvisibles(err.actual) : err.actual; - var expected = escape ? escapeInvisibles(err.expected) : err.expected; - return diff['diff' + type](actual, expected).map(function(str){ - if (str.added) return colorLines('diff added', str.value); - if (str.removed) return colorLines('diff removed', str.value); - return str.value; - }).join(''); -} + function errorDiff (err, type, escape) { + var actual = escape ? escapeInvisibles(err.actual) : err.actual + var expected = escape ? escapeInvisibles(err.expected) : err.expected + return diff['diff' + type](actual, expected).map(function (str) { + if (str.added) return colorLines('diff added', str.value) + if (str.removed) return colorLines('diff removed', str.value) + return str.value + }).join('') + } -/** + /** * Returns a string with all invisible characters in plain text * * @param {String} line * @return {String} * @api private */ -function escapeInvisibles(line) { - return line.replace(/\t/g, '') - .replace(/\r/g, '') - .replace(/\n/g, '\n'); -} + function escapeInvisibles (line) { + return line.replace(/\t/g, '') + .replace(/\r/g, '') + .replace(/\n/g, '\n') + } -/** + /** * Color lines for `str`, using the color `name`. * * @param {String} name @@ -2288,13 +2258,13 @@ function escapeInvisibles(line) { * @api private */ -function colorLines(name, str) { - return str.split('\n').map(function(str){ - return color(name, str); - }).join('\n'); -} + function colorLines (name, str) { + return str.split('\n').map(function (str) { + return color(name, str) + }).join('\n') + } -/** + /** * Stringify `obj`. * * @param {Object} obj @@ -2302,46 +2272,46 @@ function colorLines(name, str) { * @api private */ -function stringify(obj) { - if (obj instanceof RegExp) return obj.toString(); - return JSON.stringify(obj, null, 2); -} + function stringify (obj) { + if (obj instanceof RegExp) return obj.toString() + return JSON.stringify(obj, null, 2) + } -/** + /** * Return a new object that has the keys in sorted order. * @param {Object} obj * @return {Object} * @api private */ - function canonicalize(obj, stack) { - stack = stack || []; + function canonicalize (obj, stack) { + stack = stack || [] - if (utils.indexOf(stack, obj) !== -1) return obj; + if (utils.indexOf(stack, obj) !== -1) return obj - var canonicalizedObj; + var canonicalizedObj - if ('[object Array]' == {}.toString.call(obj)) { - stack.push(obj); - canonicalizedObj = utils.map(obj, function(item) { - return canonicalize(item, stack); - }); - stack.pop(); - } else if (typeof obj === 'object' && obj !== null) { - stack.push(obj); - canonicalizedObj = {}; - utils.forEach(utils.keys(obj).sort(), function(key) { - canonicalizedObj[key] = canonicalize(obj[key], stack); - }); - stack.pop(); - } else { - canonicalizedObj = obj; - } + if ({}.toString.call(obj) == '[object Array]') { + stack.push(obj) + canonicalizedObj = utils.map(obj, function (item) { + return canonicalize(item, stack) + }) + stack.pop() + } else if (typeof obj === 'object' && obj !== null) { + stack.push(obj) + canonicalizedObj = {} + utils.forEach(utils.keys(obj).sort(), function (key) { + canonicalizedObj[key] = canonicalize(obj[key], stack) + }) + stack.pop() + } else { + canonicalizedObj = obj + } - return canonicalizedObj; - } + return canonicalizedObj + } -/** + /** * Check that a / b have the same type. * * @param {Object} a @@ -2350,512 +2320,500 @@ function stringify(obj) { * @api private */ -function sameType(a, b) { - a = Object.prototype.toString.call(a); - b = Object.prototype.toString.call(b); - return a == b; -} - - -}); // module: reporters/base.js - -require.register("reporters/doc.js", function(module, exports, require){ + function sameType (a, b) { + a = Object.prototype.toString.call(a) + b = Object.prototype.toString.call(b) + return a == b + } + }) // module: reporters/base.js -/** + require.register('reporters/doc.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , utils = require('../utils'); + var Base = require('./base') + var utils = require('../utils') -/** + /** * Expose `Doc`. */ -exports = module.exports = Doc; + exports = module.exports = Doc -/** + /** * Initialize a new `Doc` reporter. * * @param {Runner} runner * @api public */ -function Doc(runner) { - Base.call(this, runner); + function Doc (runner) { + Base.call(this, runner) - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; + var self = this + var stats = this.stats + var total = runner.total + var indents = 2 - function indent() { - return Array(indents).join(' '); - } + function indent () { + return Array(indents).join(' ') + } - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
', indent()); - ++indents; - console.log('%s

%s

', indent(), utils.escape(suite.title)); - console.log('%s
', indent()); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - console.log('%s
', indent()); - --indents; - console.log('%s
', indent()); - --indents; - }); - - runner.on('pass', function(test){ - console.log('%s
%s
', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
%s
', indent(), code); - }); -} - -}); // module: reporters/doc.js - -require.register("reporters/dot.js", function(module, exports, require){ - -/** + runner.on('suite', function (suite) { + if (suite.root) return + ++indents + console.log('%s
', indent()) + ++indents + console.log('%s

%s

', indent(), utils.escape(suite.title)) + console.log('%s
', indent()) + }) + + runner.on('suite end', function (suite) { + if (suite.root) return + console.log('%s
', indent()) + --indents + console.log('%s
', indent()) + --indents + }) + + runner.on('pass', function (test) { + console.log('%s
%s
', indent(), utils.escape(test.title)) + var code = utils.escape(utils.clean(test.fn.toString())) + console.log('%s
%s
', indent(), code) + }) + } + }) // module: reporters/doc.js + + require.register('reporters/dot.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , color = Base.color; + var Base = require('./base') + var color = Base.color -/** + /** * Expose `Dot`. */ -exports = module.exports = Dot; + exports = module.exports = Dot -/** + /** * Initialize a new `Dot` matrix test reporter. * * @param {Runner} runner * @api public */ -function Dot(runner) { - Base.call(this, runner); + function Dot (runner) { + Base.call(this, runner) - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , n = 0; + var self = this + var stats = this.stats + var width = Base.window.width * 0.75 | 0 + var n = 0 - runner.on('start', function(){ - process.stdout.write('\n '); - }); + runner.on('start', function () { + process.stdout.write('\n ') + }) - runner.on('pending', function(test){ - process.stdout.write(color('pending', Base.symbols.dot)); - }); + runner.on('pending', function (test) { + process.stdout.write(color('pending', Base.symbols.dot)) + }) - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', Base.symbols.dot)); - } else { - process.stdout.write(color(test.speed, Base.symbols.dot)); - } - }); + runner.on('pass', function (test) { + if (++n % width == 0) process.stdout.write('\n ') + if (test.speed == 'slow') { + process.stdout.write(color('bright yellow', Base.symbols.dot)) + } else { + process.stdout.write(color(test.speed, Base.symbols.dot)) + } + }) - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', Base.symbols.dot)); - }); + runner.on('fail', function (test, err) { + if (++n % width == 0) process.stdout.write('\n ') + process.stdout.write(color('fail', Base.symbols.dot)) + }) - runner.on('end', function(){ - console.log(); - self.epilogue(); - }); -} + runner.on('end', function () { + console.log() + self.epilogue() + }) + } -/** + /** * Inherit from `Base.prototype`. */ -function F(){}; -F.prototype = Base.prototype; -Dot.prototype = new F; -Dot.prototype.constructor = Dot; + function F () {}; + F.prototype = Base.prototype + Dot.prototype = new F() + Dot.prototype.constructor = Dot + }) // module: reporters/dot.js -}); // module: reporters/dot.js - -require.register("reporters/html-cov.js", function(module, exports, require){ - -/** + require.register('reporters/html-cov.js', function (module, exports, require) { + /** * Module dependencies. */ -var JSONCov = require('./json-cov') - , fs = require('browser/fs'); + var JSONCov = require('./json-cov') + var fs = require('browser/fs') -/** + /** * Expose `HTMLCov`. */ -exports = module.exports = HTMLCov; + exports = module.exports = HTMLCov -/** + /** * Initialize a new `JsCoverage` reporter. * * @param {Runner} runner * @api public */ -function HTMLCov(runner) { - var jade = require('jade') - , file = __dirname + '/templates/coverage.jade' - , str = fs.readFileSync(file, 'utf8') - , fn = jade.compile(str, { filename: file }) - , self = this; + function HTMLCov (runner) { + var jade = require('jade') + var file = __dirname + '/templates/coverage.jade' + var str = fs.readFileSync(file, 'utf8') + var fn = jade.compile(str, { filename: file }) + var self = this - JSONCov.call(this, runner, false); + JSONCov.call(this, runner, false) - runner.on('end', function(){ - process.stdout.write(fn({ - cov: self.cov - , coverageClass: coverageClass - })); - }); -} + runner.on('end', function () { + process.stdout.write(fn({ + cov: self.cov, + coverageClass: coverageClass + })) + }) + } -/** + /** * Return coverage class for `n`. * * @return {String} * @api private */ -function coverageClass(n) { - if (n >= 75) return 'high'; - if (n >= 50) return 'medium'; - if (n >= 25) return 'low'; - return 'terrible'; -} -}); // module: reporters/html-cov.js - -require.register("reporters/html.js", function(module, exports, require){ + function coverageClass (n) { + if (n >= 75) return 'high' + if (n >= 50) return 'medium' + if (n >= 25) return 'low' + return 'terrible' + } + }) // module: reporters/html-cov.js -/** + require.register('reporters/html.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , utils = require('../utils') - , Progress = require('../browser/progress') - , escape = utils.escape; + var Base = require('./base') + var utils = require('../utils') + var Progress = require('../browser/progress') + var escape = utils.escape -/** + /** * Save timer references to avoid Sinon interfering (see GH-237). */ -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; + var Date = global.Date + var setTimeout = global.setTimeout + var setInterval = global.setInterval + var clearTimeout = global.clearTimeout + var clearInterval = global.clearInterval -/** + /** * Expose `HTML`. */ -exports = module.exports = HTML; + exports = module.exports = HTML -/** + /** * Stats template. */ -var statsTemplate = ''; + var statsTemplate = '' -/** + /** * Initialize a new `HTML` reporter. * * @param {Runner} runner * @api public */ -function HTML(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , stat = fragment(statsTemplate) - , items = stat.getElementsByTagName('li') - , passes = items[1].getElementsByTagName('em')[0] - , passesLink = items[1].getElementsByTagName('a')[0] - , failures = items[2].getElementsByTagName('em')[0] - , failuresLink = items[2].getElementsByTagName('a')[0] - , duration = items[3].getElementsByTagName('em')[0] - , canvas = stat.getElementsByTagName('canvas')[0] - , report = fragment('
    ') - , stack = [report] - , progress - , ctx - , root = document.getElementById('mocha'); - - if (canvas.getContext) { - var ratio = window.devicePixelRatio || 1; - canvas.style.width = canvas.width; - canvas.style.height = canvas.height; - canvas.width *= ratio; - canvas.height *= ratio; - ctx = canvas.getContext('2d'); - ctx.scale(ratio, ratio); - progress = new Progress; - } + function HTML (runner) { + Base.call(this, runner) + + var self = this + var stats = this.stats + var total = runner.total + var stat = fragment(statsTemplate) + var items = stat.getElementsByTagName('li') + var passes = items[1].getElementsByTagName('em')[0] + var passesLink = items[1].getElementsByTagName('a')[0] + var failures = items[2].getElementsByTagName('em')[0] + var failuresLink = items[2].getElementsByTagName('a')[0] + var duration = items[3].getElementsByTagName('em')[0] + var canvas = stat.getElementsByTagName('canvas')[0] + var report = fragment('
      ') + var stack = [report] + var progress + var ctx + var root = document.getElementById('mocha') + + if (canvas.getContext) { + var ratio = window.devicePixelRatio || 1 + canvas.style.width = canvas.width + canvas.style.height = canvas.height + canvas.width *= ratio + canvas.height *= ratio + ctx = canvas.getContext('2d') + ctx.scale(ratio, ratio) + progress = new Progress() + } - if (!root) return error('#mocha div missing, add it to your document'); - - // pass toggle - on(passesLink, 'click', function(){ - unhide(); - var name = /pass/.test(report.className) ? '' : ' pass'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test pass'); - }); - - // failure toggle - on(failuresLink, 'click', function(){ - unhide(); - var name = /fail/.test(report.className) ? '' : ' fail'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test fail'); - }); - - root.appendChild(stat); - root.appendChild(report); - - if (progress) progress.size(40); - - runner.on('suite', function(suite){ - if (suite.root) return; - - // suite - var url = self.suiteURL(suite); - var el = fragment('
    • %s

    • ', url, escape(suite.title)); - - // container - stack[0].appendChild(el); - stack.unshift(document.createElement('ul')); - el.appendChild(stack[0]); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - stack.shift(); - }); - - runner.on('fail', function(test, err){ - if ('hook' == test.type) runner.emit('test end', test); - }); - - runner.on('test end', function(test){ - // TODO: add to stats - var percent = stats.tests / this.total * 100 | 0; - if (progress) progress.update(percent).draw(ctx); - - // update stats - var ms = new Date - stats.start; - text(passes, stats.passes); - text(failures, stats.failures); - text(duration, (ms / 1000).toFixed(2)); - - // test - if ('passed' == test.state) { - var url = self.testURL(test); - var el = fragment('
    • %e%ems

    • ', test.speed, test.title, test.duration, url); - } else if (test.pending) { - var el = fragment('
    • %e

    • ', test.title); - } else { - var el = fragment('
    • %e

    • ', test.title, encodeURIComponent(test.fullTitle())); - var str = test.err.stack || test.err.toString(); + if (!root) return error('#mocha div missing, add it to your document') + + // pass toggle + on(passesLink, 'click', function () { + unhide() + var name = /pass/.test(report.className) ? '' : ' pass' + report.className = report.className.replace(/fail|pass/g, '') + name + if (report.className.trim()) hideSuitesWithout('test pass') + }) + + // failure toggle + on(failuresLink, 'click', function () { + unhide() + var name = /fail/.test(report.className) ? '' : ' fail' + report.className = report.className.replace(/fail|pass/g, '') + name + if (report.className.trim()) hideSuitesWithout('test fail') + }) + + root.appendChild(stat) + root.appendChild(report) + + if (progress) progress.size(40) + + runner.on('suite', function (suite) { + if (suite.root) return + + // suite + var url = self.suiteURL(suite) + var el = fragment('
    • %s

    • ', url, escape(suite.title)) + + // container + stack[0].appendChild(el) + stack.unshift(document.createElement('ul')) + el.appendChild(stack[0]) + }) + + runner.on('suite end', function (suite) { + if (suite.root) return + stack.shift() + }) + + runner.on('fail', function (test, err) { + if (test.type == 'hook') runner.emit('test end', test) + }) + + runner.on('test end', function (test) { + // TODO: add to stats + var percent = stats.tests / this.total * 100 | 0 + if (progress) progress.update(percent).draw(ctx) + + // update stats + var ms = new Date() - stats.start + text(passes, stats.passes) + text(failures, stats.failures) + text(duration, (ms / 1000).toFixed(2)) + + // test + if (test.state == 'passed') { + var url = self.testURL(test) + var el = fragment('
    • %e%ems

    • ', test.speed, test.title, test.duration, url) + } else if (test.pending) { + var el = fragment('
    • %e

    • ', test.title) + } else { + var el = fragment('
    • %e

    • ', test.title, encodeURIComponent(test.fullTitle())) + var str = test.err.stack || test.err.toString() - // FF / Opera do not add the message - if (!~str.indexOf(test.err.message)) { - str = test.err.message + '\n' + str; - } + // FF / Opera do not add the message + if (!~str.indexOf(test.err.message)) { + str = test.err.message + '\n' + str + } - // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - if ('[object Error]' == str) str = test.err.message; + // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we + // check for the result of the stringifying. + if (str == '[object Error]') str = test.err.message - // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { - str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; - } + // Safari doesn't give you a stack. Let's at least provide a source line. + if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { + str += '\n(' + test.err.sourceURL + ':' + test.err.line + ')' + } - el.appendChild(fragment('
      %e
      ', str)); - } + el.appendChild(fragment('
      %e
      ', str)) + } - // toggle code - // TODO: defer - if (!test.pending) { - var h2 = el.getElementsByTagName('h2')[0]; + // toggle code + // TODO: defer + if (!test.pending) { + var h2 = el.getElementsByTagName('h2')[0] - on(h2, 'click', function(){ - pre.style.display = 'none' == pre.style.display - ? 'block' - : 'none'; - }); + on(h2, 'click', function () { + pre.style.display = pre.style.display == 'none' + ? 'block' + : 'none' + }) - var pre = fragment('
      %e
      ', utils.clean(test.fn.toString())); - el.appendChild(pre); - pre.style.display = 'none'; - } + var pre = fragment('
      %e
      ', utils.clean(test.fn.toString())) + el.appendChild(pre) + pre.style.display = 'none' + } - // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. - if (stack[0]) stack[0].appendChild(el); - }); -} + // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. + if (stack[0]) stack[0].appendChild(el) + }) + } -/** + /** * Provide suite URL * * @param {Object} [suite] */ -HTML.prototype.suiteURL = function(suite){ - return '?grep=' + encodeURIComponent(suite.fullTitle()); -}; + HTML.prototype.suiteURL = function (suite) { + return '?grep=' + encodeURIComponent(suite.fullTitle()) + } -/** + /** * Provide test URL * * @param {Object} [test] */ -HTML.prototype.testURL = function(test){ - return '?grep=' + encodeURIComponent(test.fullTitle()); -}; + HTML.prototype.testURL = function (test) { + return '?grep=' + encodeURIComponent(test.fullTitle()) + } -/** + /** * Display error `msg`. */ -function error(msg) { - document.body.appendChild(fragment('
      %s
      ', msg)); -} + function error (msg) { + document.body.appendChild(fragment('
      %s
      ', msg)) + } -/** + /** * Return a DOM fragment from `html`. */ -function fragment(html) { - var args = arguments - , div = document.createElement('div') - , i = 1; + function fragment (html) { + var args = arguments + var div = document.createElement('div') + var i = 1 - div.innerHTML = html.replace(/%([se])/g, function(_, type){ - switch (type) { - case 's': return String(args[i++]); - case 'e': return escape(args[i++]); - } - }); + div.innerHTML = html.replace(/%([se])/g, function (_, type) { + switch (type) { + case 's': return String(args[i++]) + case 'e': return escape(args[i++]) + } + }) - return div.firstChild; -} + return div.firstChild + } -/** + /** * Check for suites that do not have elements * with `classname`, and hide them. */ -function hideSuitesWithout(classname) { - var suites = document.getElementsByClassName('suite'); - for (var i = 0; i < suites.length; i++) { - var els = suites[i].getElementsByClassName(classname); - if (0 == els.length) suites[i].className += ' hidden'; - } -} + function hideSuitesWithout (classname) { + var suites = document.getElementsByClassName('suite') + for (var i = 0; i < suites.length; i++) { + var els = suites[i].getElementsByClassName(classname) + if (els.length == 0) suites[i].className += ' hidden' + } + } -/** + /** * Unhide .hidden suites. */ -function unhide() { - var els = document.getElementsByClassName('suite hidden'); - for (var i = 0; i < els.length; ++i) { - els[i].className = els[i].className.replace('suite hidden', 'suite'); - } -} + function unhide () { + var els = document.getElementsByClassName('suite hidden') + for (var i = 0; i < els.length; ++i) { + els[i].className = els[i].className.replace('suite hidden', 'suite') + } + } -/** + /** * Set `el` text to `str`. */ -function text(el, str) { - if (el.textContent) { - el.textContent = str; - } else { - el.innerText = str; - } -} + function text (el, str) { + if (el.textContent) { + el.textContent = str + } else { + el.innerText = str + } + } -/** + /** * Listen on `event` with callback `fn`. */ -function on(el, event, fn) { - if (el.addEventListener) { - el.addEventListener(event, fn, false); - } else { - el.attachEvent('on' + event, fn); - } -} - -}); // module: reporters/html.js - -require.register("reporters/index.js", function(module, exports, require){ - -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Min = require('./min'); -exports.Spec = require('./spec'); -exports.Nyan = require('./nyan'); -exports.XUnit = require('./xunit'); -exports.Markdown = require('./markdown'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONCov = require('./json-cov'); -exports.HTMLCov = require('./html-cov'); -exports.JSONStream = require('./json-stream'); - -}); // module: reporters/index.js - -require.register("reporters/json-cov.js", function(module, exports, require){ - -/** + function on (el, event, fn) { + if (el.addEventListener) { + el.addEventListener(event, fn, false) + } else { + el.attachEvent('on' + event, fn) + } + } + }) // module: reporters/html.js + + require.register('reporters/index.js', function (module, exports, require) { + exports.Base = require('./base') + exports.Dot = require('./dot') + exports.Doc = require('./doc') + exports.TAP = require('./tap') + exports.JSON = require('./json') + exports.HTML = require('./html') + exports.List = require('./list') + exports.Min = require('./min') + exports.Spec = require('./spec') + exports.Nyan = require('./nyan') + exports.XUnit = require('./xunit') + exports.Markdown = require('./markdown') + exports.Progress = require('./progress') + exports.Landing = require('./landing') + exports.JSONCov = require('./json-cov') + exports.HTMLCov = require('./html-cov') + exports.JSONStream = require('./json-stream') + }) // module: reporters/index.js + + require.register('reporters/json-cov.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base'); + var Base = require('./base') -/** + /** * Expose `JSONCov`. */ -exports = module.exports = JSONCov; + exports = module.exports = JSONCov -/** + /** * Initialize a new `JsCoverage` reporter. * * @param {Runner} runner @@ -2863,41 +2821,41 @@ exports = module.exports = JSONCov; * @api public */ -function JSONCov(runner, output) { - var self = this - , output = 1 == arguments.length ? true : output; + function JSONCov (runner, output) { + var self = this + var output = arguments.length == 1 ? true : output - Base.call(this, runner); + Base.call(this, runner) - var tests = [] - , failures = [] - , passes = []; + var tests = [] + var failures = [] + var passes = [] - runner.on('test end', function(test){ - tests.push(test); - }); + runner.on('test end', function (test) { + tests.push(test) + }) - runner.on('pass', function(test){ - passes.push(test); - }); + runner.on('pass', function (test) { + passes.push(test) + }) - runner.on('fail', function(test){ - failures.push(test); - }); + runner.on('fail', function (test) { + failures.push(test) + }) - runner.on('end', function(){ - var cov = global._$jscoverage || {}; - var result = self.cov = map(cov); - result.stats = self.stats; - result.tests = tests.map(clean); - result.failures = failures.map(clean); - result.passes = passes.map(clean); - if (!output) return; - process.stdout.write(JSON.stringify(result, null, 2 )); - }); -} + runner.on('end', function () { + var cov = global._$jscoverage || {} + var result = self.cov = map(cov) + result.stats = self.stats + result.tests = tests.map(clean) + result.failures = failures.map(clean) + result.passes = passes.map(clean) + if (!output) return + process.stdout.write(JSON.stringify(result, null, 2)) + }) + } -/** + /** * Map jscoverage data to a JSON structure * suitable for reporting. * @@ -2906,36 +2864,36 @@ function JSONCov(runner, output) { * @api private */ -function map(cov) { - var ret = { - instrumentation: 'node-jscoverage' - , sloc: 0 - , hits: 0 - , misses: 0 - , coverage: 0 - , files: [] - }; - - for (var filename in cov) { - var data = coverage(filename, cov[filename]); - ret.files.push(data); - ret.hits += data.hits; - ret.misses += data.misses; - ret.sloc += data.sloc; - } + function map (cov) { + var ret = { + instrumentation: 'node-jscoverage', + sloc: 0, + hits: 0, + misses: 0, + coverage: 0, + files: [] + } - ret.files.sort(function(a, b) { - return a.filename.localeCompare(b.filename); - }); + for (var filename in cov) { + var data = coverage(filename, cov[filename]) + ret.files.push(data) + ret.hits += data.hits + ret.misses += data.misses + ret.sloc += data.sloc + } - if (ret.sloc > 0) { - ret.coverage = (ret.hits / ret.sloc) * 100; - } + ret.files.sort(function (a, b) { + return a.filename.localeCompare(b.filename) + }) + + if (ret.sloc > 0) { + ret.coverage = (ret.hits / ret.sloc) * 100 + } - return ret; -}; + return ret + }; -/** + /** * Map jscoverage data for a single source file * to a JSON structure suitable for reporting. * @@ -2945,41 +2903,41 @@ function map(cov) { * @api private */ -function coverage(filename, data) { - var ret = { - filename: filename, - coverage: 0, - hits: 0, - misses: 0, - sloc: 0, - source: {} - }; - - data.source.forEach(function(line, num){ - num++; - - if (data[num] === 0) { - ret.misses++; - ret.sloc++; - } else if (data[num] !== undefined) { - ret.hits++; - ret.sloc++; - } - - ret.source[num] = { - source: line - , coverage: data[num] === undefined - ? '' - : data[num] - }; - }); + function coverage (filename, data) { + var ret = { + filename: filename, + coverage: 0, + hits: 0, + misses: 0, + sloc: 0, + source: {} + } - ret.coverage = ret.hits / ret.sloc * 100; + data.source.forEach(function (line, num) { + num++ - return ret; -} + if (data[num] === 0) { + ret.misses++ + ret.sloc++ + } else if (data[num] !== undefined) { + ret.hits++ + ret.sloc++ + } + + ret.source[num] = { + source: line, + coverage: data[num] === undefined + ? '' + : data[num] + } + }) + + ret.coverage = ret.hits / ret.sloc * 100 -/** + return ret + } + + /** * Return a plain-object representation of `test` * free of cyclic properties etc. * @@ -2988,63 +2946,61 @@ function coverage(filename, data) { * @api private */ -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} - -}); // module: reporters/json-cov.js - -require.register("reporters/json-stream.js", function(module, exports, require){ + function clean (test) { + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration + } + } + }) // module: reporters/json-cov.js -/** + require.register('reporters/json-stream.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , color = Base.color; + var Base = require('./base') + var color = Base.color -/** + /** * Expose `List`. */ -exports = module.exports = List; + exports = module.exports = List -/** + /** * Initialize a new `List` test reporter. * * @param {Runner} runner * @api public */ -function List(runner) { - Base.call(this, runner); + function List (runner) { + Base.call(this, runner) - var self = this - , stats = this.stats - , total = runner.total; + var self = this + var stats = this.stats + var total = runner.total - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); + runner.on('start', function () { + console.log(JSON.stringify(['start', { total: total }])) + }) - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); + runner.on('pass', function (test) { + console.log(JSON.stringify(['pass', clean(test)])) + }) - runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); - }); + runner.on('fail', function (test, err) { + console.log(JSON.stringify(['fail', clean(test)])) + }) - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats])); - }); -} + runner.on('end', function () { + process.stdout.write(JSON.stringify(['end', self.stats])) + }) + } -/** + /** * Return a plain-object representation of `test` * free of cyclic properties etc. * @@ -3053,71 +3009,70 @@ function List(runner) { * @api private */ -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json-stream.js - -require.register("reporters/json.js", function(module, exports, require){ + function clean (test) { + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration + } + } + }) // module: reporters/json-stream.js -/** + require.register('reporters/json.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; + var Base = require('./base') + var cursor = Base.cursor + var color = Base.color -/** + /** * Expose `JSON`. */ -exports = module.exports = JSONReporter; + exports = module.exports = JSONReporter -/** + /** * Initialize a new `JSON` reporter. * * @param {Runner} runner * @api public */ -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); + function JSONReporter (runner) { + var self = this + Base.call(this, runner) - var tests = [] - , failures = [] - , passes = []; + var tests = [] + var failures = [] + var passes = [] - runner.on('test end', function(test){ - tests.push(test); - }); + runner.on('test end', function (test) { + tests.push(test) + }) - runner.on('pass', function(test){ - passes.push(test); - }); + runner.on('pass', function (test) { + passes.push(test) + }) - runner.on('fail', function(test){ - failures.push(test); - }); + runner.on('fail', function (test) { + failures.push(test) + }) - runner.on('end', function(){ - var obj = { - stats: self.stats - , tests: tests.map(clean) - , failures: failures.map(clean) - , passes: passes.map(clean) - }; + runner.on('end', function () { + var obj = { + stats: self.stats, + tests: tests.map(clean), + failures: failures.map(clean), + passes: passes.map(clean) + } - process.stdout.write(JSON.stringify(obj, null, 2)); - }); -} + process.stdout.write(JSON.stringify(obj, null, 2)) + }) + } -/** + /** * Return a plain-object representation of `test` * free of cyclic properties etc. * @@ -3126,566 +3081,558 @@ function JSONReporter(runner) { * @api private */ -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json.js - -require.register("reporters/landing.js", function(module, exports, require){ + function clean (test) { + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration + } + } + }) // module: reporters/json.js -/** + require.register('reporters/landing.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; + var Base = require('./base') + var cursor = Base.cursor + var color = Base.color -/** + /** * Expose `Landing`. */ -exports = module.exports = Landing; + exports = module.exports = Landing -/** + /** * Airplane color. */ -Base.colors.plane = 0; + Base.colors.plane = 0 -/** + /** * Airplane crash color. */ -Base.colors['plane crash'] = 31; + Base.colors['plane crash'] = 31 -/** + /** * Runway color. */ -Base.colors.runway = 90; + Base.colors.runway = 90 -/** + /** * Initialize a new `Landing` reporter. * * @param {Runner} runner * @api public */ -function Landing(runner) { - Base.call(this, runner); + function Landing (runner) { + Base.call(this, runner) - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; + var self = this + var stats = this.stats + var width = Base.window.width * 0.75 | 0 + var total = runner.total + var stream = process.stdout + var plane = color('plane', '✈') + var crashed = -1 + var n = 0 - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } + function runway () { + var buf = Array(width).join('-') + return ' ' + color('runway', buf) + } - runner.on('start', function(){ - stream.write('\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if ('failed' == test.state) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\u001b[4F\n\n'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\u001b[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ + runner.on('start', function () { + stream.write('\n ') + cursor.hide() + }) + + runner.on('test end', function (test) { + // check if the plane crashed + var col = crashed == -1 + ? width * ++n / total | 0 + : crashed + + // show the crash + if (test.state == 'failed') { + plane = color('plane crash', '✈') + crashed = col + } -function F(){}; -F.prototype = Base.prototype; -Landing.prototype = new F; -Landing.prototype.constructor = Landing; + // render landing strip + stream.write('\u001b[4F\n\n') + stream.write(runway()) + stream.write('\n ') + stream.write(color('runway', Array(col).join('⋅'))) + stream.write(plane) + stream.write(color('runway', Array(width - col).join('⋅') + '\n')) + stream.write(runway()) + stream.write('\u001b[0m') + }) + + runner.on('end', function () { + cursor.show() + console.log() + self.epilogue() + }) + } -}); // module: reporters/landing.js + /** + * Inherit from `Base.prototype`. + */ -require.register("reporters/list.js", function(module, exports, require){ + function F () {}; + F.prototype = Base.prototype + Landing.prototype = new F() + Landing.prototype.constructor = Landing + }) // module: reporters/landing.js -/** + require.register('reporters/list.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; + var Base = require('./base') + var cursor = Base.cursor + var color = Base.color -/** + /** * Expose `List`. */ -exports = module.exports = List; + exports = module.exports = List -/** + /** * Initialize a new `List` test reporter. * * @param {Runner} runner * @api public */ -function List(runner) { - Base.call(this, runner); + function List (runner) { + Base.call(this, runner) - var self = this - , stats = this.stats - , n = 0; + var self = this + var stats = this.stats + var n = 0 - runner.on('start', function(){ - console.log(); - }); + runner.on('start', function () { + console.log() + }) - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); + runner.on('test', function (test) { + process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')) + }) - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); + runner.on('pending', function (test) { + var fmt = color('checkmark', ' -') + + color('pending', ' %s') + console.log(fmt, test.fullTitle()) + }) - runner.on('pass', function(test){ - var fmt = color('checkmark', ' '+Base.symbols.dot) - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - cursor.CR(); - console.log(fmt, test.fullTitle(), test.duration); - }); + runner.on('pass', function (test) { + var fmt = color('checkmark', ' ' + Base.symbols.dot) + + color('pass', ' %s: ') + + color(test.speed, '%dms') + cursor.CR() + console.log(fmt, test.fullTitle(), test.duration) + }) - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); - }); + runner.on('fail', function (test, err) { + cursor.CR() + console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()) + }) - runner.on('end', self.epilogue.bind(self)); -} + runner.on('end', self.epilogue.bind(self)) + } -/** + /** * Inherit from `Base.prototype`. */ -function F(){}; -F.prototype = Base.prototype; -List.prototype = new F; -List.prototype.constructor = List; + function F () {}; + F.prototype = Base.prototype + List.prototype = new F() + List.prototype.constructor = List + }) // module: reporters/list.js - -}); // module: reporters/list.js - -require.register("reporters/markdown.js", function(module, exports, require){ -/** + require.register('reporters/markdown.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , utils = require('../utils'); + var Base = require('./base') + var utils = require('../utils') -/** + /** * Expose `Markdown`. */ -exports = module.exports = Markdown; + exports = module.exports = Markdown -/** + /** * Initialize a new `Markdown` reporter. * * @param {Runner} runner * @api public */ -function Markdown(runner) { - Base.call(this, runner); + function Markdown (runner) { + Base.call(this, runner) - var self = this - , stats = this.stats - , level = 0 - , buf = ''; + var self = this + var stats = this.stats + var level = 0 + var buf = '' - function title(str) { - return Array(level).join('#') + ' ' + str; - } + function title (str) { + return Array(level).join('#') + ' ' + str + } - function indent() { - return Array(level).join(' '); - } + function indent () { + return Array(level).join(' ') + } - function mapTOC(suite, obj) { - var ret = obj; - obj = obj[suite.title] = obj[suite.title] || { suite: suite }; - suite.suites.forEach(function(suite){ - mapTOC(suite, obj); - }); - return ret; - } + function mapTOC (suite, obj) { + var ret = obj + obj = obj[suite.title] = obj[suite.title] || { suite: suite } + suite.suites.forEach(function (suite) { + mapTOC(suite, obj) + }) + return ret + } - function stringifyTOC(obj, level) { - ++level; - var buf = ''; - var link; - for (var key in obj) { - if ('suite' == key) continue; - if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; - if (key) buf += Array(level).join(' ') + link; - buf += stringifyTOC(obj[key], level); - } - --level; - return buf; - } + function stringifyTOC (obj, level) { + ++level + var buf = '' + var link + for (var key in obj) { + if (key == 'suite') continue + if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n' + if (key) buf += Array(level).join(' ') + link + buf += stringifyTOC(obj[key], level) + } + --level + return buf + } - function generateTOC(suite) { - var obj = mapTOC(suite, {}); - return stringifyTOC(obj, 0); - } + function generateTOC (suite) { + var obj = mapTOC(suite, {}) + return stringifyTOC(obj, 0) + } - generateTOC(runner.suite); - - runner.on('suite', function(suite){ - ++level; - var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; - buf += title(suite.title) + '\n'; - }); - - runner.on('suite end', function(suite){ - --level; - }); - - runner.on('pass', function(test){ - var code = utils.clean(test.fn.toString()); - buf += test.title + '.\n'; - buf += '\n```js\n'; - buf += code + '\n'; - buf += '```\n\n'; - }); - - runner.on('end', function(){ - process.stdout.write('# TOC\n'); - process.stdout.write(generateTOC(runner.suite)); - process.stdout.write(buf); - }); -} -}); // module: reporters/markdown.js - -require.register("reporters/min.js", function(module, exports, require){ - -/** + generateTOC(runner.suite) + + runner.on('suite', function (suite) { + ++level + var slug = utils.slug(suite.fullTitle()) + buf += '' + '\n' + buf += title(suite.title) + '\n' + }) + + runner.on('suite end', function (suite) { + --level + }) + + runner.on('pass', function (test) { + var code = utils.clean(test.fn.toString()) + buf += test.title + '.\n' + buf += '\n```js\n' + buf += code + '\n' + buf += '```\n\n' + }) + + runner.on('end', function () { + process.stdout.write('# TOC\n') + process.stdout.write(generateTOC(runner.suite)) + process.stdout.write(buf) + }) + } + }) // module: reporters/markdown.js + + require.register('reporters/min.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base'); + var Base = require('./base') -/** + /** * Expose `Min`. */ -exports = module.exports = Min; + exports = module.exports = Min -/** + /** * Initialize a new `Min` minimal test reporter (best used with --watch). * * @param {Runner} runner * @api public */ -function Min(runner) { - Base.call(this, runner); + function Min (runner) { + Base.call(this, runner) - runner.on('start', function(){ - // clear screen - process.stdout.write('\u001b[2J'); - // set cursor position - process.stdout.write('\u001b[1;3H'); - }); + runner.on('start', function () { + // clear screen + process.stdout.write('\u001b[2J') + // set cursor position + process.stdout.write('\u001b[1;3H') + }) - runner.on('end', this.epilogue.bind(this)); -} + runner.on('end', this.epilogue.bind(this)) + } -/** + /** * Inherit from `Base.prototype`. */ -function F(){}; -F.prototype = Base.prototype; -Min.prototype = new F; -Min.prototype.constructor = Min; - + function F () {}; + F.prototype = Base.prototype + Min.prototype = new F() + Min.prototype.constructor = Min + }) // module: reporters/min.js -}); // module: reporters/min.js - -require.register("reporters/nyan.js", function(module, exports, require){ -/** + require.register('reporters/nyan.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , color = Base.color; + var Base = require('./base') + var color = Base.color -/** + /** * Expose `Dot`. */ -exports = module.exports = NyanCat; + exports = module.exports = NyanCat -/** + /** * Initialize a new `Dot` matrix test reporter. * * @param {Runner} runner * @api public */ -function NyanCat(runner) { - Base.call(this, runner); - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , rainbowColors = this.rainbowColors = self.generateColors() - , colorIndex = this.colorIndex = 0 - , numerOfLines = this.numberOfLines = 4 - , trajectories = this.trajectories = [[], [], [], []] - , nyanCatWidth = this.nyanCatWidth = 11 - , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) - , scoreboardWidth = this.scoreboardWidth = 5 - , tick = this.tick = 0 - , n = 0; - - runner.on('start', function(){ - Base.cursor.hide(); - self.draw(); - }); - - runner.on('pending', function(test){ - self.draw(); - }); - - runner.on('pass', function(test){ - self.draw(); - }); - - runner.on('fail', function(test, err){ - self.draw(); - }); - - runner.on('end', function(){ - Base.cursor.show(); - for (var i = 0; i < self.numberOfLines; i++) write('\n'); - self.epilogue(); - }); -} - -/** + function NyanCat (runner) { + Base.call(this, runner) + var self = this + var stats = this.stats + var width = Base.window.width * 0.75 | 0 + var rainbowColors = this.rainbowColors = self.generateColors() + var colorIndex = this.colorIndex = 0 + var numerOfLines = this.numberOfLines = 4 + var trajectories = this.trajectories = [[], [], [], []] + var nyanCatWidth = this.nyanCatWidth = 11 + var trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) + var scoreboardWidth = this.scoreboardWidth = 5 + var tick = this.tick = 0 + var n = 0 + + runner.on('start', function () { + Base.cursor.hide() + self.draw() + }) + + runner.on('pending', function (test) { + self.draw() + }) + + runner.on('pass', function (test) { + self.draw() + }) + + runner.on('fail', function (test, err) { + self.draw() + }) + + runner.on('end', function () { + Base.cursor.show() + for (var i = 0; i < self.numberOfLines; i++) write('\n') + self.epilogue() + }) + } + + /** * Draw the nyan cat * * @api private */ -NyanCat.prototype.draw = function(){ - this.appendRainbow(); - this.drawScoreboard(); - this.drawRainbow(); - this.drawNyanCat(); - this.tick = !this.tick; -}; + NyanCat.prototype.draw = function () { + this.appendRainbow() + this.drawScoreboard() + this.drawRainbow() + this.drawNyanCat() + this.tick = !this.tick + } -/** + /** * Draw the "scoreboard" showing the number * of passes, failures and pending tests. * * @api private */ -NyanCat.prototype.drawScoreboard = function(){ - var stats = this.stats; - var colors = Base.colors; + NyanCat.prototype.drawScoreboard = function () { + var stats = this.stats + var colors = Base.colors - function draw(color, n) { - write(' '); - write('\u001b[' + color + 'm' + n + '\u001b[0m'); - write('\n'); - } + function draw (color, n) { + write(' ') + write('\u001b[' + color + 'm' + n + '\u001b[0m') + write('\n') + } - draw(colors.green, stats.passes); - draw(colors.fail, stats.failures); - draw(colors.pending, stats.pending); - write('\n'); + draw(colors.green, stats.passes) + draw(colors.fail, stats.failures) + draw(colors.pending, stats.pending) + write('\n') - this.cursorUp(this.numberOfLines); -}; + this.cursorUp(this.numberOfLines) + } -/** + /** * Append the rainbow. * * @api private */ -NyanCat.prototype.appendRainbow = function(){ - var segment = this.tick ? '_' : '-'; - var rainbowified = this.rainbowify(segment); + NyanCat.prototype.appendRainbow = function () { + var segment = this.tick ? '_' : '-' + var rainbowified = this.rainbowify(segment) - for (var index = 0; index < this.numberOfLines; index++) { - var trajectory = this.trajectories[index]; - if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); - trajectory.push(rainbowified); - } -}; + for (var index = 0; index < this.numberOfLines; index++) { + var trajectory = this.trajectories[index] + if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift() + trajectory.push(rainbowified) + } + } -/** + /** * Draw the rainbow. * * @api private */ -NyanCat.prototype.drawRainbow = function(){ - var self = this; + NyanCat.prototype.drawRainbow = function () { + var self = this - this.trajectories.forEach(function(line, index) { - write('\u001b[' + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); - }); + this.trajectories.forEach(function (line, index) { + write('\u001b[' + self.scoreboardWidth + 'C') + write(line.join('')) + write('\n') + }) - this.cursorUp(this.numberOfLines); -}; + this.cursorUp(this.numberOfLines) + } -/** + /** * Draw the nyan cat * * @api private */ -NyanCat.prototype.drawNyanCat = function() { - var self = this; - var startWidth = this.scoreboardWidth + this.trajectories[0].length; - var color = '\u001b[' + startWidth + 'C'; - var padding = ''; + NyanCat.prototype.drawNyanCat = function () { + var self = this + var startWidth = this.scoreboardWidth + this.trajectories[0].length + var color = '\u001b[' + startWidth + 'C' + var padding = '' - write(color); - write('_,------,'); - write('\n'); + write(color) + write('_,------,') + write('\n') - write(color); - padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); + write(color) + padding = self.tick ? ' ' : ' ' + write('_|' + padding + '/\\_/\\ ') + write('\n') - write(color); - padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - write(tail + '|' + padding + this.face() + ' '); - write('\n'); + write(color) + padding = self.tick ? '_' : '__' + var tail = self.tick ? '~' : '^' + var face + write(tail + '|' + padding + this.face() + ' ') + write('\n') - write(color); - padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); + write(color) + padding = self.tick ? ' ' : ' ' + write(padding + '"" "" ') + write('\n') - this.cursorUp(this.numberOfLines); -}; + this.cursorUp(this.numberOfLines) + } -/** + /** * Draw nyan cat face. * * @return {String} * @api private */ -NyanCat.prototype.face = function() { - var stats = this.stats; - if (stats.failures) { - return '( x .x)'; - } else if (stats.pending) { - return '( o .o)'; - } else if(stats.passes) { - return '( ^ .^)'; - } else { - return '( - .-)'; - } -} + NyanCat.prototype.face = function () { + var stats = this.stats + if (stats.failures) { + return '( x .x)' + } else if (stats.pending) { + return '( o .o)' + } else if (stats.passes) { + return '( ^ .^)' + } else { + return '( - .-)' + } + } -/** + /** * Move cursor up `n`. * * @param {Number} n * @api private */ -NyanCat.prototype.cursorUp = function(n) { - write('\u001b[' + n + 'A'); -}; + NyanCat.prototype.cursorUp = function (n) { + write('\u001b[' + n + 'A') + } -/** + /** * Move cursor down `n`. * * @param {Number} n * @api private */ -NyanCat.prototype.cursorDown = function(n) { - write('\u001b[' + n + 'B'); -}; + NyanCat.prototype.cursorDown = function (n) { + write('\u001b[' + n + 'B') + } -/** + /** * Generate rainbow colors. * * @return {Array} * @api private */ -NyanCat.prototype.generateColors = function(){ - var colors = []; + NyanCat.prototype.generateColors = function () { + var colors = [] - for (var i = 0; i < (6 * 7); i++) { - var pi3 = Math.floor(Math.PI / 3); - var n = (i * (1.0 / 6)); - var r = Math.floor(3 * Math.sin(n) + 3); - var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); - var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); - colors.push(36 * r + 6 * g + b + 16); - } + for (var i = 0; i < (6 * 7); i++) { + var pi3 = Math.floor(Math.PI / 3) + var n = (i * (1.0 / 6)) + var r = Math.floor(3 * Math.sin(n) + 3) + var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3) + var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3) + colors.push(36 * r + 6 * g + b + 16) + } - return colors; -}; + return colors + } -/** + /** * Apply rainbow to the given `str`. * * @param {String} str @@ -3693,55 +3640,52 @@ NyanCat.prototype.generateColors = function(){ * @api private */ -NyanCat.prototype.rainbowify = function(str){ - var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; - this.colorIndex += 1; - return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; -}; + NyanCat.prototype.rainbowify = function (str) { + var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length] + this.colorIndex += 1 + return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m' + } -/** + /** * Stdout helper. */ -function write(string) { - process.stdout.write(string); -} + function write (string) { + process.stdout.write(string) + } -/** + /** * Inherit from `Base.prototype`. */ -function F(){}; -F.prototype = Base.prototype; -NyanCat.prototype = new F; -NyanCat.prototype.constructor = NyanCat; - - -}); // module: reporters/nyan.js + function F () {}; + F.prototype = Base.prototype + NyanCat.prototype = new F() + NyanCat.prototype.constructor = NyanCat + }) // module: reporters/nyan.js -require.register("reporters/progress.js", function(module, exports, require){ - -/** + require.register('reporters/progress.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; + var Base = require('./base') + var cursor = Base.cursor + var color = Base.color -/** + /** * Expose `Progress`. */ -exports = module.exports = Progress; + exports = module.exports = Progress -/** + /** * General progress bar color. */ -Base.colors.progress = 90; + Base.colors.progress = 90 -/** + /** * Initialize a new `Progress` bar test reporter. * * @param {Runner} runner @@ -3749,225 +3693,219 @@ Base.colors.progress = 90; * @api public */ -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || Base.symbols.dot; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - complete++; - var incomplete = total - complete - , percent = complete / total - , n = width * percent | 0 - , i = width - n; - - cursor.CR(); - process.stdout.write('\u001b[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** + function Progress (runner, options) { + Base.call(this, runner) + + var self = this + var options = options || {} + var stats = this.stats + var width = Base.window.width * 0.50 | 0 + var total = runner.total + var complete = 0 + var max = Math.max + + // default chars + options.open = options.open || '[' + options.complete = options.complete || '▬' + options.incomplete = options.incomplete || Base.symbols.dot + options.close = options.close || ']' + options.verbose = false + + // tests started + runner.on('start', function () { + console.log() + cursor.hide() + }) + + // tests complete + runner.on('test end', function () { + complete++ + var incomplete = total - complete + var percent = complete / total + var n = width * percent | 0 + var i = width - n + + cursor.CR() + process.stdout.write('\u001b[J') + process.stdout.write(color('progress', ' ' + options.open)) + process.stdout.write(Array(n).join(options.complete)) + process.stdout.write(Array(i).join(options.incomplete)) + process.stdout.write(color('progress', options.close)) + if (options.verbose) { + process.stdout.write(color('progress', ' ' + complete + ' of ' + total)) + } + }) + + // tests are complete, output some stats + // and the failures if any + runner.on('end', function () { + cursor.show() + console.log() + self.epilogue() + }) + } + + /** * Inherit from `Base.prototype`. */ -function F(){}; -F.prototype = Base.prototype; -Progress.prototype = new F; -Progress.prototype.constructor = Progress; - - -}); // module: reporters/progress.js - -require.register("reporters/spec.js", function(module, exports, require){ + function F () {}; + F.prototype = Base.prototype + Progress.prototype = new F() + Progress.prototype.constructor = Progress + }) // module: reporters/progress.js -/** + require.register('reporters/spec.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; + var Base = require('./base') + var cursor = Base.cursor + var color = Base.color -/** + /** * Expose `Spec`. */ -exports = module.exports = Spec; + exports = module.exports = Spec -/** + /** * Initialize a new `Spec` test reporter. * * @param {Runner} runner * @api public */ -function Spec(runner) { - Base.call(this, runner); + function Spec (runner) { + Base.call(this, runner) - var self = this - , stats = this.stats - , indents = 0 - , n = 0; + var self = this + var stats = this.stats + var indents = 0 + var n = 0 - function indent() { - return Array(indents).join(' ') - } + function indent () { + return Array(indents).join(' ') + } - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s '); - cursor.CR(); - console.log(fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s ') - + color(test.speed, '(%dms)'); - cursor.CR(); - console.log(fmt, test.title, test.duration); - } - }); + runner.on('start', function () { + console.log() + }) + + runner.on('suite', function (suite) { + ++indents + console.log(color('suite', '%s%s'), indent(), suite.title) + }) + + runner.on('suite end', function (suite) { + --indents + if (indents == 1) console.log() + }) + + runner.on('pending', function (test) { + var fmt = indent() + color('pending', ' - %s') + console.log(fmt, test.title) + }) + + runner.on('pass', function (test) { + if (test.speed == 'fast') { + var fmt = indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s ') + cursor.CR() + console.log(fmt, test.title) + } else { + var fmt = indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s ') + + color(test.speed, '(%dms)') + cursor.CR() + console.log(fmt, test.title, test.duration) + } + }) - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); - }); + runner.on('fail', function (test, err) { + cursor.CR() + console.log(indent() + color('fail', ' %d) %s'), ++n, test.title) + }) - runner.on('end', self.epilogue.bind(self)); -} + runner.on('end', self.epilogue.bind(self)) + } -/** + /** * Inherit from `Base.prototype`. */ -function F(){}; -F.prototype = Base.prototype; -Spec.prototype = new F; -Spec.prototype.constructor = Spec; - + function F () {}; + F.prototype = Base.prototype + Spec.prototype = new F() + Spec.prototype.constructor = Spec + }) // module: reporters/spec.js -}); // module: reporters/spec.js - -require.register("reporters/tap.js", function(module, exports, require){ - -/** + require.register('reporters/tap.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; + var Base = require('./base') + var cursor = Base.cursor + var color = Base.color -/** + /** * Expose `TAP`. */ -exports = module.exports = TAP; + exports = module.exports = TAP -/** + /** * Initialize a new `TAP` reporter. * * @param {Runner} runner * @api public */ -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 1 - , passes = 0 - , failures = 0; - - runner.on('start', function(){ - var total = runner.grepTotal(runner.suite); - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pending', function(test){ - console.log('ok %d %s # SKIP -', n, title(test)); - }); - - runner.on('pass', function(test){ - passes++; - console.log('ok %d %s', n, title(test)); - }); - - runner.on('fail', function(test, err){ - failures++; - console.log('not ok %d %s', n, title(test)); - if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - console.log('# tests ' + (passes + failures)); - console.log('# pass ' + passes); - console.log('# fail ' + failures); - }); -} + function TAP (runner) { + Base.call(this, runner) + + var self = this + var stats = this.stats + var n = 1 + var passes = 0 + var failures = 0 + + runner.on('start', function () { + var total = runner.grepTotal(runner.suite) + console.log('%d..%d', 1, total) + }) + + runner.on('test end', function () { + ++n + }) + + runner.on('pending', function (test) { + console.log('ok %d %s # SKIP -', n, title(test)) + }) + + runner.on('pass', function (test) { + passes++ + console.log('ok %d %s', n, title(test)) + }) + + runner.on('fail', function (test, err) { + failures++ + console.log('not ok %d %s', n, title(test)) + if (err.stack) console.log(err.stack.replace(/^/gm, ' ')) + }) + + runner.on('end', function () { + console.log('# tests ' + (passes + failures)) + console.log('# pass ' + passes) + console.log('# fail ' + failures) + }) + } -/** + /** * Return a TAP-safe title of `test` * * @param {Object} test @@ -3975,172 +3913,167 @@ function TAP(runner) { * @api private */ -function title(test) { - return test.fullTitle().replace(/#/g, ''); -} - -}); // module: reporters/tap.js - -require.register("reporters/xunit.js", function(module, exports, require){ + function title (test) { + return test.fullTitle().replace(/#/g, '') + } + }) // module: reporters/tap.js -/** + require.register('reporters/xunit.js', function (module, exports, require) { + /** * Module dependencies. */ -var Base = require('./base') - , utils = require('../utils') - , escape = utils.escape; + var Base = require('./base') + var utils = require('../utils') + var escape = utils.escape -/** + /** * Save timer references to avoid Sinon interfering (see GH-237). */ -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; + var Date = global.Date + var setTimeout = global.setTimeout + var setInterval = global.setInterval + var clearTimeout = global.clearTimeout + var clearInterval = global.clearInterval -/** + /** * Expose `XUnit`. */ -exports = module.exports = XUnit; + exports = module.exports = XUnit -/** + /** * Initialize a new `XUnit` reporter. * * @param {Runner} runner * @api public */ -function XUnit(runner) { - Base.call(this, runner); - var stats = this.stats - , tests = [] - , self = this; - - runner.on('pending', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - tests.push(test); - }); - - runner.on('fail', function(test){ - tests.push(test); - }); - - runner.on('end', function(){ - console.log(tag('testsuite', { - name: 'Mocha Tests' - , tests: stats.tests - , failures: stats.failures - , errors: stats.failures - , skipped: stats.tests - stats.failures - stats.passes - , timestamp: (new Date).toUTCString() - , time: (stats.duration / 1000) || 0 - }, false)); - - tests.forEach(test); - console.log(''); - }); -} - -/** + function XUnit (runner) { + Base.call(this, runner) + var stats = this.stats + var tests = [] + var self = this + + runner.on('pending', function (test) { + tests.push(test) + }) + + runner.on('pass', function (test) { + tests.push(test) + }) + + runner.on('fail', function (test) { + tests.push(test) + }) + + runner.on('end', function () { + console.log(tag('testsuite', { + name: 'Mocha Tests', + tests: stats.tests, + failures: stats.failures, + errors: stats.failures, + skipped: stats.tests - stats.failures - stats.passes, + timestamp: (new Date()).toUTCString(), + time: (stats.duration / 1000) || 0 + }, false)) + + tests.forEach(test) + console.log('') + }) + } + + /** * Inherit from `Base.prototype`. */ -function F(){}; -F.prototype = Base.prototype; -XUnit.prototype = new F; -XUnit.prototype.constructor = XUnit; + function F () {}; + F.prototype = Base.prototype + XUnit.prototype = new F() + XUnit.prototype.constructor = XUnit - -/** + /** * Output tag for the given `test.` */ -function test(test) { - var attrs = { - classname: test.parent.fullTitle() - , name: test.title - , time: (test.duration / 1000) || 0 - }; - - if ('failed' == test.state) { - var err = test.err; - attrs.message = escape(err.message); - console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); - } else if (test.pending) { - console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - console.log(tag('testcase', attrs, true) ); - } -} + function test (test) { + var attrs = { + classname: test.parent.fullTitle(), + name: test.title, + time: (test.duration / 1000) || 0 + } -/** + if (test.state == 'failed') { + var err = test.err + attrs.message = escape(err.message) + console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))) + } else if (test.pending) { + console.log(tag('testcase', attrs, false, tag('skipped', {}, true))) + } else { + console.log(tag('testcase', attrs, true)) + } + } + + /** * HTML tag helper. */ -function tag(name, attrs, close, content) { - var end = close ? '/>' : '>' - , pairs = [] - , tag; + function tag (name, attrs, close, content) { + var end = close ? '/>' : '>' + var pairs = [] + var tag - for (var key in attrs) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } + for (var key in attrs) { + pairs.push(key + '="' + escape(attrs[key]) + '"') + } - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - if (content) tag += content + ''; -} - -}); // module: reporters/xunit.js - -require.register("runnable.js", function(module, exports, require){ + function cdata (str) { + return '' + } + }) // module: reporters/xunit.js -/** + require.register('runnable.js', function (module, exports, require) { + /** * Module dependencies. */ -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runnable') - , milliseconds = require('./ms'); + var EventEmitter = require('browser/events').EventEmitter + var debug = require('browser/debug')('mocha:runnable') + var milliseconds = require('./ms') -/** + /** * Save timer references to avoid Sinon interfering (see GH-237). */ -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; + var Date = global.Date + var setTimeout = global.setTimeout + var setInterval = global.setInterval + var clearTimeout = global.clearTimeout + var clearInterval = global.clearInterval -/** + /** * Object#toString(). */ -var toString = Object.prototype.toString; + var toString = Object.prototype.toString -/** + /** * Expose `Runnable`. */ -module.exports = Runnable; + module.exports = Runnable -/** + /** * Initialize a new `Runnable` with the given `title` and callback `fn`. * * @param {String} title @@ -4148,27 +4081,26 @@ module.exports = Runnable; * @api private */ -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this._timeout = 2000; - this._slow = 75; - this.timedOut = false; -} + function Runnable (title, fn) { + this.title = title + this.fn = fn + this.async = fn && fn.length + this.sync = !this.async + this._timeout = 2000 + this._slow = 75 + this.timedOut = false + } -/** + /** * Inherit from `EventEmitter.prototype`. */ -function F(){}; -F.prototype = EventEmitter.prototype; -Runnable.prototype = new F; -Runnable.prototype.constructor = Runnable; - + function F () {}; + F.prototype = EventEmitter.prototype + Runnable.prototype = new F() + Runnable.prototype.constructor = Runnable -/** + /** * Set & get timeout `ms`. * * @param {Number|String} ms @@ -4176,16 +4108,16 @@ Runnable.prototype.constructor = Runnable; * @api private */ -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = ms; - if (this.timer) this.resetTimeout(); - return this; -}; + Runnable.prototype.timeout = function (ms) { + if (arguments.length == 0) return this._timeout + if (typeof ms === 'string') ms = milliseconds(ms) + debug('timeout %d', ms) + this._timeout = ms + if (this.timer) this.resetTimeout() + return this + } -/** + /** * Set & get slow `ms`. * * @param {Number|String} ms @@ -4193,15 +4125,15 @@ Runnable.prototype.timeout = function(ms){ * @api private */ -Runnable.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._slow = ms; - return this; -}; + Runnable.prototype.slow = function (ms) { + if (arguments.length === 0) return this._slow + if (typeof ms === 'string') ms = milliseconds(ms) + debug('timeout %d', ms) + this._slow = ms + return this + } -/** + /** * Return the full title generated by recursively * concatenating the parent's full title. * @@ -4209,176 +4141,175 @@ Runnable.prototype.slow = function(ms){ * @api public */ -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; + Runnable.prototype.fullTitle = function () { + return this.parent.fullTitle() + ' ' + this.title + } -/** + /** * Clear the timeout. * * @api private */ -Runnable.prototype.clearTimeout = function(){ - clearTimeout(this.timer); -}; + Runnable.prototype.clearTimeout = function () { + clearTimeout(this.timer) + } -/** + /** * Inspect the runnable void of private properties. * * @return {String} * @api private */ -Runnable.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_' == key[0]) return; - if ('parent' == key) return '#'; - if ('ctx' == key) return '#'; - return val; - }, 2); -}; + Runnable.prototype.inspect = function () { + return JSON.stringify(this, function (key, val) { + if (key[0] == '_') return + if (key == 'parent') return '#' + if (key == 'ctx') return '#' + return val + }, 2) + } -/** + /** * Reset the timeout. * * @api private */ -Runnable.prototype.resetTimeout = function(){ - var self = this; - var ms = this.timeout() || 1e9; + Runnable.prototype.resetTimeout = function () { + var self = this + var ms = this.timeout() || 1e9 - this.clearTimeout(); - this.timer = setTimeout(function(){ - self.callback(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); -}; + this.clearTimeout() + this.timer = setTimeout(function () { + self.callback(new Error('timeout of ' + ms + 'ms exceeded')) + self.timedOut = true + }, ms) + } -/** + /** * Whitelist these globals for this test run * * @api private */ -Runnable.prototype.globals = function(arr){ - var self = this; - this._allowedGlobals = arr; -}; + Runnable.prototype.globals = function (arr) { + var self = this + this._allowedGlobals = arr + } -/** + /** * Run the test and invoke `fn(err)`. * * @param {Function} fn * @api private */ -Runnable.prototype.run = function(fn){ - var self = this - , ms = this.timeout() - , start = new Date - , ctx = this.ctx - , finished - , emitted; - - if (ctx) ctx.runnable(this); + Runnable.prototype.run = function (fn) { + var self = this + var ms = this.timeout() + var start = new Date() + var ctx = this.ctx + var finished + var emitted - // called multiple times - function multiple(err) { - if (emitted) return; - emitted = true; - self.emit('error', err || new Error('done() called multiple times')); - } - - // finished - function done(err) { - if (self.timedOut) return; - if (finished) return multiple(err); - self.clearTimeout(); - self.duration = new Date - start; - finished = true; - fn(err); - } + if (ctx) ctx.runnable(this) - // for .resetTimeout() - this.callback = done; + // called multiple times + function multiple (err) { + if (emitted) return + emitted = true + self.emit('error', err || new Error('done() called multiple times')) + } - // explicit async with `done` argument - if (this.async) { - this.resetTimeout(); + // finished + function done (err) { + if (self.timedOut) return + if (finished) return multiple(err) + self.clearTimeout() + self.duration = new Date() - start + finished = true + fn(err) + } - try { - this.fn.call(ctx, function(err){ - if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); - if (null != err) return done(new Error('done() invoked with non-Error: ' + err)); - done(); - }); - } catch (err) { - done(err); - } - return; - } + // for .resetTimeout() + this.callback = done + + // explicit async with `done` argument + if (this.async) { + this.resetTimeout() + + try { + this.fn.call(ctx, function (err) { + if (err instanceof Error || toString.call(err) === '[object Error]') return done(err) + if (err != null) return done(new Error('done() invoked with non-Error: ' + err)) + done() + }) + } catch (err) { + done(err) + } + return + } - if (this.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()`')); - } + if (this.asyncOnly) { + return done(new Error('--async-only option in use without declaring `done()`')) + } - // sync or promise-returning - try { - if (this.pending) { - done(); - } else { - callFn(this.fn); - } - } catch (err) { - done(err); - } + // sync or promise-returning + try { + if (this.pending) { + done() + } else { + callFn(this.fn) + } + } catch (err) { + done(err) + } - function callFn(fn) { - var result = fn.call(ctx); - if (result && typeof result.then === 'function') { - self.resetTimeout(); - result.then(function(){ done() }, done); - } else { - done(); + function callFn (fn) { + var result = fn.call(ctx) + if (result && typeof result.then === 'function') { + self.resetTimeout() + result.then(function () { done() }, done) + } else { + done() + } + } } - } -}; + }) // module: runnable.js -}); // module: runnable.js - -require.register("runner.js", function(module, exports, require){ -/** + require.register('runner.js', function (module, exports, require) { + /** * Module dependencies. */ -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runner') - , Test = require('./test') - , utils = require('./utils') - , filter = utils.filter - , keys = utils.keys; + var EventEmitter = require('browser/events').EventEmitter + var debug = require('browser/debug')('mocha:runner') + var Test = require('./test') + var utils = require('./utils') + var filter = utils.filter + var keys = utils.keys -/** + /** * Non-enumerable globals. */ -var globals = [ - 'setTimeout', - 'clearTimeout', - 'setInterval', - 'clearInterval', - 'XMLHttpRequest', - 'Date' -]; + var globals = [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'XMLHttpRequest', + 'Date' + ] -/** + /** * Expose `Runner`. */ -module.exports = Runner; + module.exports = Runner -/** + /** * Initialize a `Runner` for the given `suite`. * * Events: @@ -4398,39 +4329,38 @@ module.exports = Runner; * @api public */ -function Runner(suite) { - var self = this; - this._globals = []; - this._abort = false; - this.suite = suite; - this.total = suite.total(); - this.failures = 0; - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); - this.globals(this.globalProps().concat(extraGlobals())); -} - -/** + function Runner (suite) { + var self = this + this._globals = [] + this._abort = false + this.suite = suite + this.total = suite.total() + this.failures = 0 + this.on('test end', function (test) { self.checkGlobals(test) }) + this.on('hook end', function (hook) { self.checkGlobals(hook) }) + this.grep(/.*/) + this.globals(this.globalProps().concat(extraGlobals())) + } + + /** * Wrapper for setImmediate, process.nextTick, or browser polyfill. * * @param {Function} fn * @api private */ -Runner.immediately = global.setImmediate || process.nextTick; + Runner.immediately = global.setImmediate || process.nextTick -/** + /** * Inherit from `EventEmitter.prototype`. */ -function F(){}; -F.prototype = EventEmitter.prototype; -Runner.prototype = new F; -Runner.prototype.constructor = Runner; - + function F () {}; + F.prototype = EventEmitter.prototype + Runner.prototype = new F() + Runner.prototype.constructor = Runner -/** + /** * Run tests with full titles matching `re`. Updates runner.total * with number of tests matched. * @@ -4440,15 +4370,15 @@ Runner.prototype.constructor = Runner; * @api public */ -Runner.prototype.grep = function(re, invert){ - debug('grep %s', re); - this._grep = re; - this._invert = invert; - this.total = this.grepTotal(this.suite); - return this; -}; + Runner.prototype.grep = function (re, invert) { + debug('grep %s', re) + this._grep = re + this._invert = invert + this.total = this.grepTotal(this.suite) + return this + } -/** + /** * Returns the number of tests matching the grep search for the * given suite. * @@ -4457,39 +4387,39 @@ Runner.prototype.grep = function(re, invert){ * @api public */ -Runner.prototype.grepTotal = function(suite) { - var self = this; - var total = 0; + Runner.prototype.grepTotal = function (suite) { + var self = this + var total = 0 - suite.eachTest(function(test){ - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (match) total++; - }); + suite.eachTest(function (test) { + var match = self._grep.test(test.fullTitle()) + if (self._invert) match = !match + if (match) total++ + }) - return total; -}; + return total + } -/** + /** * Return a list of global properties. * * @return {Array} * @api private */ -Runner.prototype.globalProps = function() { - var props = utils.keys(global); + Runner.prototype.globalProps = function () { + var props = utils.keys(global) - // non-enumerables - for (var i = 0; i < globals.length; ++i) { - if (~utils.indexOf(props, globals[i])) continue; - props.push(globals[i]); - } + // non-enumerables + for (var i = 0; i < globals.length; ++i) { + if (~utils.indexOf(props, globals[i])) continue + props.push(globals[i]) + } - return props; -}; + return props + } -/** + /** * Allow the given `arr` of globals. * * @param {Array} arr @@ -4497,45 +4427,45 @@ Runner.prototype.globalProps = function() { * @api public */ -Runner.prototype.globals = function(arr){ - if (0 == arguments.length) return this._globals; - debug('globals %j', arr); - this._globals = this._globals.concat(arr); - return this; -}; + Runner.prototype.globals = function (arr) { + if (arguments.length == 0) return this._globals + debug('globals %j', arr) + this._globals = this._globals.concat(arr) + return this + } -/** + /** * Check for global variable leaks. * * @api private */ -Runner.prototype.checkGlobals = function(test){ - if (this.ignoreLeaks) return; - var ok = this._globals; + Runner.prototype.checkGlobals = function (test) { + if (this.ignoreLeaks) return + var ok = this._globals - var globals = this.globalProps(); - var isNode = process.kill; - var leaks; + var globals = this.globalProps() + var isNode = process.kill + var leaks - if (test) { - ok = ok.concat(test._allowedGlobals || []); - } + if (test) { + ok = ok.concat(test._allowedGlobals || []) + } - if(this.prevGlobalsLength == globals.length) return; - this.prevGlobalsLength = globals.length; + if (this.prevGlobalsLength == globals.length) return + this.prevGlobalsLength = globals.length - leaks = filterLeaks(ok, globals); - this._globals = this._globals.concat(leaks); + leaks = filterLeaks(ok, globals) + this._globals = this._globals.concat(leaks) - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; + if (leaks.length > 1) { + this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')) + } else if (leaks.length) { + this.fail(test, new Error('global leak detected: ' + leaks[0])) + } + } -/** + /** * Fail the given `test`. * * @param {Test} test @@ -4543,18 +4473,18 @@ Runner.prototype.checkGlobals = function(test){ * @api private */ -Runner.prototype.fail = function(test, err){ - ++this.failures; - test.state = 'failed'; + Runner.prototype.fail = function (test, err) { + ++this.failures + test.state = 'failed' - if ('string' == typeof err) { - err = new Error('the string "' + err + '" was thrown, throw an Error :)'); - } + if (typeof err === 'string') { + err = new Error('the string "' + err + '" was thrown, throw an Error :)') + } - this.emit('fail', test, err); -}; + this.emit('fail', test, err) + } -/** + /** * Fail the given `hook` with `err`. * * Hook failures work in the following pattern: @@ -4575,14 +4505,14 @@ Runner.prototype.fail = function(test, err){ * @api private */ -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - if (this.suite.bail()) { - this.emit('end'); - } -}; + Runner.prototype.failHook = function (hook, err) { + this.fail(hook, err) + if (this.suite.bail()) { + this.emit('end') + } + } -/** + /** * Run hook `name` callbacks and then invoke `fn()`. * * @param {String} name @@ -4590,48 +4520,48 @@ Runner.prototype.failHook = function(hook, err){ * @api private */ -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , self = this - , timer; + Runner.prototype.hook = function (name, fn) { + var suite = this.suite + var hooks = suite['_' + name] + var self = this + var timer - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - if (self.failures && suite.bail()) return fn(); - self.currentRunnable = hook; + function next (i) { + var hook = hooks[i] + if (!hook) return fn() + if (self.failures && suite.bail()) return fn() + self.currentRunnable = hook - hook.ctx.currentTest = self.test; + hook.ctx.currentTest = self.test - self.emit('hook', hook); + self.emit('hook', hook) - hook.on('error', function(err){ - self.failHook(hook, err); - }); + hook.on('error', function (err) { + self.failHook(hook, err) + }) - hook.run(function(err){ - hook.removeAllListeners('error'); - var testError = hook.error(); - if (testError) self.fail(self.test, testError); - if (err) { - self.failHook(hook, err); + hook.run(function (err) { + hook.removeAllListeners('error') + var testError = hook.error() + if (testError) self.fail(self.test, testError) + if (err) { + self.failHook(hook, err) - // stop executing hooks, notify callee of hook err - return fn(err); + // stop executing hooks, notify callee of hook err + return fn(err) + } + self.emit('hook end', hook) + delete hook.ctx.currentTest + next(++i) + }) } - self.emit('hook end', hook); - delete hook.ctx.currentTest; - next(++i); - }); - } - Runner.immediately(function(){ - next(0); - }); -}; + Runner.immediately(function () { + next(0) + }) + } -/** + /** * Run hook `name` for the given array of `suites` * in order, and callback `fn(err, errSuite)`. * @@ -4641,33 +4571,33 @@ Runner.prototype.hook = function(name, fn){ * @api private */ -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; + Runner.prototype.hooks = function (name, suites, fn) { + var self = this + var orig = this.suite - function next(suite) { - self.suite = suite; + function next (suite) { + self.suite = suite - if (!suite) { - self.suite = orig; - return fn(); - } + if (!suite) { + self.suite = orig + return fn() + } - self.hook(name, function(err){ - if (err) { - var errSuite = self.suite; - self.suite = orig; - return fn(err, errSuite); - } + self.hook(name, function (err) { + if (err) { + var errSuite = self.suite + self.suite = orig + return fn(err, errSuite) + } - next(suites.pop()); - }); - } + next(suites.pop()) + }) + } - next(suites.pop()); -}; + next(suites.pop()) + } -/** + /** * Run hooks from the top level down. * * @param {String} name @@ -4675,12 +4605,12 @@ Runner.prototype.hooks = function(name, suites, fn){ * @api private */ -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; + Runner.prototype.hookUp = function (name, fn) { + var suites = [this.suite].concat(this.parents()).reverse() + this.hooks(name, suites, fn) + } -/** + /** * Run hooks from the bottom up. * * @param {String} name @@ -4688,12 +4618,12 @@ Runner.prototype.hookUp = function(name, fn){ * @api private */ -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; + Runner.prototype.hookDown = function (name, fn) { + var suites = [this.suite].concat(this.parents()) + this.hooks(name, suites, fn) + } -/** + /** * Return an array of parent Suites from * closest to furthest. * @@ -4701,37 +4631,37 @@ Runner.prototype.hookDown = function(name, fn){ * @api private */ -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; + Runner.prototype.parents = function () { + var suite = this.suite + var suites = [] + while (suite = suite.parent) suites.push(suite) + return suites + } -/** + /** * Run the current test and callback `fn(err)`. * * @param {Function} fn * @api private */ -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; + Runner.prototype.runTest = function (fn) { + var test = this.test + var self = this - if (this.asyncOnly) test.asyncOnly = true; + if (this.asyncOnly) test.asyncOnly = true - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; + try { + test.on('error', function (err) { + self.fail(test, err) + }) + test.run(fn) + } catch (err) { + fn(err) + } + } -/** + /** * Run tests in the given `suite` and invoke * the callback `fn()` when complete. * @@ -4740,91 +4670,89 @@ Runner.prototype.runTest = function(fn){ * @api private */ -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests.slice() - , test; - - - function hookErr(err, errSuite, after) { - // before/after Each hook for errSuite failed: - var orig = self.suite; - - // for failed 'after each' hook start from errSuite parent, - // otherwise start from errSuite itself - self.suite = after ? errSuite.parent : errSuite; - - if (self.suite) { - // call hookUp afterEach - self.hookUp('afterEach', function(err2, errSuite2) { - self.suite = orig; - // some hooks may fail even now - if (err2) return hookErr(err2, errSuite2, true); - // report error suite - fn(errSuite); - }); - } else { - // there is no need calling other 'after each' hooks - self.suite = orig; - fn(errSuite); - } - } - - function next(err, errSuite) { - // if we bail after first err - if (self.failures && suite._bail) return fn(); + Runner.prototype.runTests = function (suite, fn) { + var self = this + var tests = suite.tests.slice() + var test + + function hookErr (err, errSuite, after) { + // before/after Each hook for errSuite failed: + var orig = self.suite + + // for failed 'after each' hook start from errSuite parent, + // otherwise start from errSuite itself + self.suite = after ? errSuite.parent : errSuite + + if (self.suite) { + // call hookUp afterEach + self.hookUp('afterEach', function (err2, errSuite2) { + self.suite = orig + // some hooks may fail even now + if (err2) return hookErr(err2, errSuite2, true) + // report error suite + fn(errSuite) + }) + } else { + // there is no need calling other 'after each' hooks + self.suite = orig + fn(errSuite) + } + } - if (self._abort) return fn(); + function next (err, errSuite) { + // if we bail after first err + if (self.failures && suite._bail) return fn() - if (err) return hookErr(err, errSuite, true); + if (self._abort) return fn() - // next test - test = tests.shift(); + if (err) return hookErr(err, errSuite, true) - // all done - if (!test) return fn(); + // next test + test = tests.shift() - // grep - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (!match) return next(); + // all done + if (!test) return fn() - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } + // grep + var match = self._grep.test(test.fullTitle()) + if (self._invert) match = !match + if (!match) return next() - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(err, errSuite){ + // pending + if (test.pending) { + self.emit('pending', test) + self.emit('test end', test) + return next() + } - if (err) return hookErr(err, errSuite, false); + // execute test and hook(s) + self.emit('test', self.test = test) + self.hookDown('beforeEach', function (err, errSuite) { + if (err) return hookErr(err, errSuite, false) - self.currentRunnable = self.test; - self.runTest(function(err){ - test = self.test; + self.currentRunnable = self.test + self.runTest(function (err) { + test = self.test - if (err) { - self.fail(test, err); - self.emit('test end', test); - return self.hookUp('afterEach', next); - } + if (err) { + self.fail(test, err) + self.emit('test end', test) + return self.hookUp('afterEach', next) + } - test.state = 'passed'; - self.emit('pass', test); - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } + test.state = 'passed' + self.emit('pass', test) + self.emit('test end', test) + self.hookUp('afterEach', next) + }) + }) + } - this.next = next; - next(); -}; + this.next = next + next() + } -/** + /** * Run the given `suite` and invoke the * callback `fn()` when complete. * @@ -4833,79 +4761,79 @@ Runner.prototype.runTests = function(suite, fn){ * @api private */ -Runner.prototype.runSuite = function(suite, fn){ - var total = this.grepTotal(suite) - , self = this - , i = 0; + Runner.prototype.runSuite = function (suite, fn) { + var total = this.grepTotal(suite) + var self = this + var i = 0 - debug('run suite %s', suite.fullTitle()); + debug('run suite %s', suite.fullTitle()) - if (!total) return fn(); + if (!total) return fn() - this.emit('suite', this.suite = suite); + this.emit('suite', this.suite = suite) - function next(errSuite) { - if (errSuite) { - // current suite failed on a hook from errSuite - if (errSuite == suite) { - // if errSuite is current suite - // continue to the next sibling suite - return done(); - } else { - // errSuite is among the parents of current suite - // stop execution of errSuite and all sub-suites - return done(errSuite); - } - } + function next (errSuite) { + if (errSuite) { + // current suite failed on a hook from errSuite + if (errSuite == suite) { + // if errSuite is current suite + // continue to the next sibling suite + return done() + } else { + // errSuite is among the parents of current suite + // stop execution of errSuite and all sub-suites + return done(errSuite) + } + } - if (self._abort) return done(); + if (self._abort) return done() - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } + var curr = suite.suites[i++] + if (!curr) return done() + self.runSuite(curr, next) + } - function done(errSuite) { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(errSuite); - }); - } + function done (errSuite) { + self.suite = suite + self.hook('afterAll', function () { + self.emit('suite end', suite) + fn(errSuite) + }) + } - this.hook('beforeAll', function(err){ - if (err) return done(); - self.runTests(suite, next); - }); -}; + this.hook('beforeAll', function (err) { + if (err) return done() + self.runTests(suite, next) + }) + } -/** + /** * Handle uncaught exceptions. * * @param {Error} err * @api private */ -Runner.prototype.uncaught = function(err){ - debug('uncaught exception %s', err.message); - var runnable = this.currentRunnable; - if (!runnable || 'failed' == runnable.state) return; - runnable.clearTimeout(); - err.uncaught = true; - this.fail(runnable, err); + Runner.prototype.uncaught = function (err) { + debug('uncaught exception %s', err.message) + var runnable = this.currentRunnable + if (!runnable || runnable.state == 'failed') return + runnable.clearTimeout() + err.uncaught = true + this.fail(runnable, err) - // recover from test - if ('test' == runnable.type) { - this.emit('test end', runnable); - this.hookUp('afterEach', this.next); - return; - } + // recover from test + if (runnable.type == 'test') { + this.emit('test end', runnable) + this.hookUp('afterEach', this.next) + return + } - // bail on hooks - this.emit('end'); -}; + // bail on hooks + this.emit('end') + } -/** + /** * Run the root suite and invoke `fn(failures)` * on completion. * @@ -4914,48 +4842,48 @@ Runner.prototype.uncaught = function(err){ * @api public */ -Runner.prototype.run = function(fn){ - var self = this - , fn = fn || function(){}; + Runner.prototype.run = function (fn) { + var self = this + var fn = fn || function () {} - function uncaught(err){ - self.uncaught(err); - } + function uncaught (err) { + self.uncaught(err) + } - debug('start'); + debug('start') - // callback - this.on('end', function(){ - debug('end'); - process.removeListener('uncaughtException', uncaught); - fn(self.failures); - }); + // callback + this.on('end', function () { + debug('end') + process.removeListener('uncaughtException', uncaught) + fn(self.failures) + }) - // run suites - this.emit('start'); - this.runSuite(this.suite, function(){ - debug('finished running'); - self.emit('end'); - }); + // run suites + this.emit('start') + this.runSuite(this.suite, function () { + debug('finished running') + self.emit('end') + }) - // uncaught exception - process.on('uncaughtException', uncaught); + // uncaught exception + process.on('uncaughtException', uncaught) - return this; -}; + return this + } -/** + /** * Cleanly abort execution * * @return {Runner} for chaining * @api public */ -Runner.prototype.abort = function(){ - debug('aborting'); - this._abort = true; -} + Runner.prototype.abort = function () { + debug('aborting') + this._abort = true + } -/** + /** * Filter leaks with the given globals flagged as `ok`. * * @param {Array} ok @@ -4964,77 +4892,74 @@ Runner.prototype.abort = function(){ * @api private */ -function filterLeaks(ok, globals) { - return filter(globals, function(key){ - // Firefox and Chrome exposes iframes as index inside the window object - if (/^d+/.test(key)) return false; + function filterLeaks (ok, globals) { + return filter(globals, function (key) { + // Firefox and Chrome exposes iframes as index inside the window object + if (/^d+/.test(key)) return false - // in firefox - // if runner runs in an iframe, this iframe's window.getInterface method not init at first - // it is assigned in some seconds - if (global.navigator && /^getInterface/.test(key)) return false; + // in firefox + // if runner runs in an iframe, this iframe's window.getInterface method not init at first + // it is assigned in some seconds + if (global.navigator && /^getInterface/.test(key)) return false - // an iframe could be approached by window[iframeIndex] - // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak - if (global.navigator && /^\d+/.test(key)) return false; + // an iframe could be approached by window[iframeIndex] + // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak + if (global.navigator && /^\d+/.test(key)) return false - // Opera and IE expose global variables for HTML element IDs (issue #243) - if (/^mocha-/.test(key)) return false; + // Opera and IE expose global variables for HTML element IDs (issue #243) + if (/^mocha-/.test(key)) return false - var matched = filter(ok, function(ok){ - if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); - return key == ok; - }); - return matched.length == 0 && (!global.navigator || 'onerror' !== key); - }); -} + var matched = filter(ok, function (ok) { + if (~ok.indexOf('*')) return key.indexOf(ok.split('*')[0]) == 0 + return key == ok + }) + return matched.length == 0 && (!global.navigator || key !== 'onerror') + }) + } -/** + /** * Array of globals dependent on the environment. * * @return {Array} * @api private */ - function extraGlobals() { - if (typeof(process) === 'object' && - typeof(process.version) === 'string') { + function extraGlobals () { + if (typeof (process) === 'object' && + typeof (process.version) === 'string') { + var nodeVersion = process.version.split('.').reduce(function (a, v) { + return a << 8 | v + }) - var nodeVersion = process.version.split('.').reduce(function(a, v) { - return a << 8 | v; - }); + // 'errno' was renamed to process._errno in v0.9.11. - // 'errno' was renamed to process._errno in v0.9.11. + if (nodeVersion < 0x00090B) { + return ['errno'] + } + } - if (nodeVersion < 0x00090B) { - return ['errno']; + return [] } - } - - return []; - } - -}); // module: runner.js - -require.register("suite.js", function(module, exports, require){ + }) // module: runner.js -/** + require.register('suite.js', function (module, exports, require) { + /** * Module dependencies. */ -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:suite') - , milliseconds = require('./ms') - , utils = require('./utils') - , Hook = require('./hook'); + var EventEmitter = require('browser/events').EventEmitter + var debug = require('browser/debug')('mocha:suite') + var milliseconds = require('./ms') + var utils = require('./utils') + var Hook = require('./hook') -/** + /** * Expose `Suite`. */ -exports = module.exports = Suite; + exports = module.exports = Suite -/** + /** * Create a new `Suite` with the given `title` * and parent `Suite`. When a suite with the * same title is already present, that suite @@ -5047,16 +4972,16 @@ exports = module.exports = Suite; * @api public */ -exports.create = function(parent, title){ - var suite = new Suite(title, parent.ctx); - suite.parent = parent; - if (parent.pending) suite.pending = true; - title = suite.fullTitle(); - parent.addSuite(suite); - return suite; -}; + exports.create = function (parent, title) { + var suite = new Suite(title, parent.ctx) + suite.parent = parent + if (parent.pending) suite.pending = true + title = suite.fullTitle() + parent.addSuite(suite) + return suite + } -/** + /** * Initialize a new `Suite` with the given * `title` and `ctx`. * @@ -5065,52 +4990,51 @@ exports.create = function(parent, title){ * @api private */ -function Suite(title, parentContext) { - this.title = title; - var context = function () {}; - context.prototype = parentContext; - this.ctx = new context(); - this.suites = []; - this.tests = []; - this.pending = false; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this._timeout = 2000; - this._slow = 75; - this._bail = false; -} - -/** + function Suite (title, parentContext) { + this.title = title + var context = function () {} + context.prototype = parentContext + this.ctx = new context() + this.suites = [] + this.tests = [] + this.pending = false + this._beforeEach = [] + this._beforeAll = [] + this._afterEach = [] + this._afterAll = [] + this.root = !title + this._timeout = 2000 + this._slow = 75 + this._bail = false + } + + /** * Inherit from `EventEmitter.prototype`. */ -function F(){}; -F.prototype = EventEmitter.prototype; -Suite.prototype = new F; -Suite.prototype.constructor = Suite; + function F () {}; + F.prototype = EventEmitter.prototype + Suite.prototype = new F() + Suite.prototype.constructor = Suite - -/** + /** * Return a clone of this `Suite`. * * @return {Suite} * @api private */ -Suite.prototype.clone = function(){ - var suite = new Suite(this.title); - debug('clone'); - suite.ctx = this.ctx; - suite.timeout(this.timeout()); - suite.slow(this.slow()); - suite.bail(this.bail()); - return suite; -}; + Suite.prototype.clone = function () { + var suite = new Suite(this.title) + debug('clone') + suite.ctx = this.ctx + suite.timeout(this.timeout()) + suite.slow(this.slow()) + suite.bail(this.bail()) + return suite + } -/** + /** * Set timeout `ms` or short-hand such as "2s". * * @param {Number|String} ms @@ -5118,15 +5042,15 @@ Suite.prototype.clone = function(){ * @api private */ -Suite.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = parseInt(ms, 10); - return this; -}; + Suite.prototype.timeout = function (ms) { + if (arguments.length == 0) return this._timeout + if (typeof ms === 'string') ms = milliseconds(ms) + debug('timeout %d', ms) + this._timeout = parseInt(ms, 10) + return this + } -/** + /** * Set slow `ms` or short-hand such as "2s". * * @param {Number|String} ms @@ -5134,15 +5058,15 @@ Suite.prototype.timeout = function(ms){ * @api private */ -Suite.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('slow %d', ms); - this._slow = ms; - return this; -}; + Suite.prototype.slow = function (ms) { + if (arguments.length === 0) return this._slow + if (typeof ms === 'string') ms = milliseconds(ms) + debug('slow %d', ms) + this._slow = ms + return this + } -/** + /** * Sets whether to bail after first error. * * @parma {Boolean} bail @@ -5150,14 +5074,14 @@ Suite.prototype.slow = function(ms){ * @api private */ -Suite.prototype.bail = function(bail){ - if (0 == arguments.length) return this._bail; - debug('bail %s', bail); - this._bail = bail; - return this; -}; + Suite.prototype.bail = function (bail) { + if (arguments.length == 0) return this._bail + debug('bail %s', bail) + this._bail = bail + return this + } -/** + /** * Run `fn(test[, done])` before running tests. * * @param {Function} fn @@ -5165,25 +5089,25 @@ Suite.prototype.bail = function(bail){ * @api private */ -Suite.prototype.beforeAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** + Suite.prototype.beforeAll = function (title, fn) { + if (this.pending) return this + if (typeof title === 'function') { + fn = title + title = fn.name + } + title = '"before all" hook' + (title ? ': ' + title : '') + + var hook = new Hook(title, fn) + hook.parent = this + hook.timeout(this.timeout()) + hook.slow(this.slow()) + hook.ctx = this.ctx + this._beforeAll.push(hook) + this.emit('beforeAll', hook) + return this + } + + /** * Run `fn(test[, done])` after running tests. * * @param {Function} fn @@ -5191,25 +5115,25 @@ Suite.prototype.beforeAll = function(title, fn){ * @api private */ -Suite.prototype.afterAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** + Suite.prototype.afterAll = function (title, fn) { + if (this.pending) return this + if (typeof title === 'function') { + fn = title + title = fn.name + } + title = '"after all" hook' + (title ? ': ' + title : '') + + var hook = new Hook(title, fn) + hook.parent = this + hook.timeout(this.timeout()) + hook.slow(this.slow()) + hook.ctx = this.ctx + this._afterAll.push(hook) + this.emit('afterAll', hook) + return this + } + + /** * Run `fn(test[, done])` before each test case. * * @param {Function} fn @@ -5217,25 +5141,25 @@ Suite.prototype.afterAll = function(title, fn){ * @api private */ -Suite.prototype.beforeEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** + Suite.prototype.beforeEach = function (title, fn) { + if (this.pending) return this + if (typeof title === 'function') { + fn = title + title = fn.name + } + title = '"before each" hook' + (title ? ': ' + title : '') + + var hook = new Hook(title, fn) + hook.parent = this + hook.timeout(this.timeout()) + hook.slow(this.slow()) + hook.ctx = this.ctx + this._beforeEach.push(hook) + this.emit('beforeEach', hook) + return this + } + + /** * Run `fn(test[, done])` after each test case. * * @param {Function} fn @@ -5243,25 +5167,25 @@ Suite.prototype.beforeEach = function(title, fn){ * @api private */ -Suite.prototype.afterEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** + Suite.prototype.afterEach = function (title, fn) { + if (this.pending) return this + if (typeof title === 'function') { + fn = title + title = fn.name + } + title = '"after each" hook' + (title ? ': ' + title : '') + + var hook = new Hook(title, fn) + hook.parent = this + hook.timeout(this.timeout()) + hook.slow(this.slow()) + hook.ctx = this.ctx + this._afterEach.push(hook) + this.emit('afterEach', hook) + return this + } + + /** * Add a test `suite`. * * @param {Suite} suite @@ -5269,17 +5193,17 @@ Suite.prototype.afterEach = function(title, fn){ * @api private */ -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - suite.timeout(this.timeout()); - suite.slow(this.slow()); - suite.bail(this.bail()); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; + Suite.prototype.addSuite = function (suite) { + suite.parent = this + suite.timeout(this.timeout()) + suite.slow(this.slow()) + suite.bail(this.bail()) + this.suites.push(suite) + this.emit('suite', suite) + return this + } -/** + /** * Add a `test` to this suite. * * @param {Test} test @@ -5287,17 +5211,17 @@ Suite.prototype.addSuite = function(suite){ * @api private */ -Suite.prototype.addTest = function(test){ - test.parent = this; - test.timeout(this.timeout()); - test.slow(this.slow()); - test.ctx = this.ctx; - this.tests.push(test); - this.emit('test', test); - return this; -}; + Suite.prototype.addTest = function (test) { + test.parent = this + test.timeout(this.timeout()) + test.slow(this.slow()) + test.ctx = this.ctx + this.tests.push(test) + this.emit('test', test) + return this + } -/** + /** * Return the full title generated by recursively * concatenating the parent's full title. * @@ -5305,28 +5229,28 @@ Suite.prototype.addTest = function(test){ * @api public */ -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; + Suite.prototype.fullTitle = function () { + if (this.parent) { + var full = this.parent.fullTitle() + if (full) return full + ' ' + this.title + } + return this.title + } -/** + /** * Return the total number of tests. * * @return {Number} * @api public */ -Suite.prototype.total = function(){ - return utils.reduce(this.suites, function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; + Suite.prototype.total = function () { + return utils.reduce(this.suites, function (sum, suite) { + return sum + suite.total() + }, 0) + this.tests.length + } -/** + /** * Iterates through each suite recursively to find * all tests. Applies a function in the format * `fn(test)`. @@ -5336,31 +5260,29 @@ Suite.prototype.total = function(){ * @api private */ -Suite.prototype.eachTest = function(fn){ - utils.forEach(this.tests, fn); - utils.forEach(this.suites, function(suite){ - suite.eachTest(fn); - }); - return this; -}; - -}); // module: suite.js - -require.register("test.js", function(module, exports, require){ + Suite.prototype.eachTest = function (fn) { + utils.forEach(this.tests, fn) + utils.forEach(this.suites, function (suite) { + suite.eachTest(fn) + }) + return this + } + }) // module: suite.js -/** + require.register('test.js', function (module, exports, require) { + /** * Module dependencies. */ -var Runnable = require('./runnable'); + var Runnable = require('./runnable') -/** + /** * Expose `Test`. */ -module.exports = Test; + module.exports = Test -/** + /** * Initialize a new `Test` with the given `title` and callback `fn`. * * @param {String} title @@ -5368,41 +5290,39 @@ module.exports = Test; * @api private */ -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; - this.type = 'test'; -} + function Test (title, fn) { + Runnable.call(this, title, fn) + this.pending = !fn + this.type = 'test' + } -/** + /** * Inherit from `Runnable.prototype`. */ -function F(){}; -F.prototype = Runnable.prototype; -Test.prototype = new F; -Test.prototype.constructor = Test; + function F () {}; + F.prototype = Runnable.prototype + Test.prototype = new F() + Test.prototype.constructor = Test + }) // module: test.js - -}); // module: test.js - -require.register("utils.js", function(module, exports, require){ -/** + require.register('utils.js', function (module, exports, require) { + /** * Module dependencies. */ -var fs = require('browser/fs') - , path = require('browser/path') - , join = path.join - , debug = require('browser/debug')('mocha:watch'); + var fs = require('browser/fs') + var path = require('browser/path') + var join = path.join + var debug = require('browser/debug')('mocha:watch') -/** + /** * Ignored directories. */ -var ignore = ['node_modules', '.git']; + var ignore = ['node_modules', '.git'] -/** + /** * Escape special characters in the given string of html. * * @param {String} html @@ -5410,15 +5330,15 @@ var ignore = ['node_modules', '.git']; * @api private */ -exports.escape = function(html){ - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; + exports.escape = function (html) { + return String(html) + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(//g, '>') + } -/** + /** * Array#forEach (<=IE8) * * @param {Array} array @@ -5427,12 +5347,11 @@ exports.escape = function(html){ * @api private */ -exports.forEach = function(arr, fn, scope){ - for (var i = 0, l = arr.length; i < l; i++) - fn.call(scope, arr[i], i); -}; + exports.forEach = function (arr, fn, scope) { + for (var i = 0, l = arr.length; i < l; i++) { fn.call(scope, arr[i], i) } + } -/** + /** * Array#map (<=IE8) * * @param {Array} array @@ -5441,14 +5360,13 @@ exports.forEach = function(arr, fn, scope){ * @api private */ -exports.map = function(arr, fn, scope){ - var result = []; - for (var i = 0, l = arr.length; i < l; i++) - result.push(fn.call(scope, arr[i], i)); - return result; -}; + exports.map = function (arr, fn, scope) { + var result = [] + for (var i = 0, l = arr.length; i < l; i++) { result.push(fn.call(scope, arr[i], i)) } + return result + } -/** + /** * Array#indexOf (<=IE8) * * @parma {Array} arr @@ -5457,15 +5375,14 @@ exports.map = function(arr, fn, scope){ * @api private */ -exports.indexOf = function(arr, obj, start){ - for (var i = start || 0, l = arr.length; i < l; i++) { - if (arr[i] === obj) - return i; - } - return -1; -}; + exports.indexOf = function (arr, obj, start) { + for (var i = start || 0, l = arr.length; i < l; i++) { + if (arr[i] === obj) { return i } + } + return -1 + } -/** + /** * Array#reduce (<=IE8) * * @param {Array} array @@ -5474,17 +5391,17 @@ exports.indexOf = function(arr, obj, start){ * @api private */ -exports.reduce = function(arr, fn, val){ - var rval = val; + exports.reduce = function (arr, fn, val) { + var rval = val - for (var i = 0, l = arr.length; i < l; i++) { - rval = fn(rval, arr[i], i, arr); - } + for (var i = 0, l = arr.length; i < l; i++) { + rval = fn(rval, arr[i], i, arr) + } - return rval; -}; + return rval + } -/** + /** * Array#filter (<=IE8) * * @param {Array} array @@ -5492,18 +5409,18 @@ exports.reduce = function(arr, fn, val){ * @api private */ -exports.filter = function(arr, fn){ - var ret = []; + exports.filter = function (arr, fn) { + var ret = [] - for (var i = 0, l = arr.length; i < l; i++) { - var val = arr[i]; - if (fn(val, i, arr)) ret.push(val); - } + for (var i = 0, l = arr.length; i < l; i++) { + var val = arr[i] + if (fn(val, i, arr)) ret.push(val) + } - return ret; -}; + return ret + } -/** + /** * Object.keys (<=IE8) * * @param {Object} obj @@ -5511,20 +5428,20 @@ exports.filter = function(arr, fn){ * @api private */ -exports.keys = Object.keys || function(obj) { - var keys = [] - , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 + exports.keys = Object.keys || function (obj) { + var keys = [] + var has = Object.prototype.hasOwnProperty // for `window` on <=IE8 - for (var key in obj) { - if (has.call(obj, key)) { - keys.push(key); - } - } + for (var key in obj) { + if (has.call(obj, key)) { + keys.push(key) + } + } - return keys; -}; + return keys + } -/** + /** * Watch the given `files` for changes * and invoke `fn(file)` on modification. * @@ -5533,49 +5450,49 @@ exports.keys = Object.keys || function(obj) { * @api private */ -exports.watch = function(files, fn){ - var options = { interval: 100 }; - files.forEach(function(file){ - debug('file %s', file); - fs.watchFile(file, options, function(curr, prev){ - if (prev.mtime < curr.mtime) fn(file); - }); - }); -}; + exports.watch = function (files, fn) { + var options = { interval: 100 } + files.forEach(function (file) { + debug('file %s', file) + fs.watchFile(file, options, function (curr, prev) { + if (prev.mtime < curr.mtime) fn(file) + }) + }) + } -/** + /** * Ignored files. */ -function ignored(path){ - return !~ignore.indexOf(path); -} + function ignored (path) { + return !~ignore.indexOf(path) + } -/** + /** * Lookup files in the given `dir`. * * @return {Array} * @api private */ -exports.files = function(dir, ret){ - ret = ret || []; + exports.files = function (dir, ret) { + ret = ret || [] - fs.readdirSync(dir) - .filter(ignored) - .forEach(function(path){ - path = join(dir, path); - if (fs.statSync(path).isDirectory()) { - exports.files(path, ret); - } else if (path.match(/\.(js|coffee|litcoffee|coffee.md)$/)) { - ret.push(path); - } - }); + fs.readdirSync(dir) + .filter(ignored) + .forEach(function (path) { + path = join(dir, path) + if (fs.statSync(path).isDirectory()) { + exports.files(path, ret) + } else if (path.match(/\.(js|coffee|litcoffee|coffee.md)$/)) { + ret.push(path) + } + }) - return ret; -}; + return ret + } -/** + /** * Compute a slug from the given `str`. * * @param {String} str @@ -5583,34 +5500,34 @@ exports.files = function(dir, ret){ * @api private */ -exports.slug = function(str){ - return str - .toLowerCase() - .replace(/ +/g, '-') - .replace(/[^-\w]/g, ''); -}; + exports.slug = function (str) { + return str + .toLowerCase() + .replace(/ +/g, '-') + .replace(/[^-\w]/g, '') + } -/** + /** * Strip the function definition from `str`, * and re-indent for pre whitespace. */ -exports.clean = function(str) { - str = str - .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '') - .replace(/^function *\(.*\) *{/, '') - .replace(/\s+\}$/, ''); + exports.clean = function (str) { + str = str + .replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '') + .replace(/^function *\(.*\) *{/, '') + .replace(/\s+\}$/, '') - var spaces = str.match(/^\n?( *)/)[1].length - , tabs = str.match(/^\n?(\t*)/)[1].length - , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm'); + var spaces = str.match(/^\n?( *)/)[1].length + var tabs = str.match(/^\n?(\t*)/)[1].length + var re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}', 'gm') - str = str.replace(re, ''); + str = str.replace(re, '') - return exports.trim(str); -}; + return exports.trim(str) + } -/** + /** * Escape regular expression characters in `str`. * * @param {String} str @@ -5618,11 +5535,11 @@ exports.clean = function(str) { * @api private */ -exports.escapeRegexp = function(str){ - return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); -}; + exports.escapeRegexp = function (str) { + return str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&') + } -/** + /** * Trim the given `str`. * * @param {String} str @@ -5630,11 +5547,11 @@ exports.escapeRegexp = function(str){ * @api private */ -exports.trim = function(str){ - return str.replace(/^\s+|\s+$/g, ''); -}; + exports.trim = function (str) { + return str.replace(/^\s+|\s+$/g, '') + } -/** + /** * Parse the given `qs`. * * @param {String} qs @@ -5642,18 +5559,18 @@ exports.trim = function(str){ * @api private */ -exports.parseQuery = function(qs){ - return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); + exports.parseQuery = function (qs) { + return exports.reduce(qs.replace('?', '').split('&'), function (obj, pair) { + var i = pair.indexOf('=') + var key = pair.slice(0, i) + var val = pair.slice(++i) - obj[key] = decodeURIComponent(val); - return obj; - }, {}); -}; + obj[key] = decodeURIComponent(val) + return obj + }, {}) + } -/** + /** * Highlight the given string of `js`. * * @param {String} js @@ -5661,47 +5578,46 @@ exports.parseQuery = function(qs){ * @api private */ -function highlight(js) { - return js - .replace(//g, '>') - .replace(/\/\/(.*)/gm, '//$1') - .replace(/('.*?')/gm, '$1') - .replace(/(\d+\.\d+)/gm, '$1') - .replace(/(\d+)/gm, '$1') - .replace(/\bnew *(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') -} + function highlight (js) { + return js + .replace(//g, '>') + .replace(/\/\/(.*)/gm, '//$1') + .replace(/('.*?')/gm, '$1') + .replace(/(\d+\.\d+)/gm, '$1') + .replace(/(\d+)/gm, '$1') + .replace(/\bnew *(\w+)/gm, 'new $1') + .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') + } -/** + /** * Highlight the contents of tag `name`. * * @param {String} name * @api private */ -exports.highlightTags = function(name) { - var code = document.getElementsByTagName(name); - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } -}; - -}); // module: utils.js -// The global object is "self" in Web Workers. -global = (function() { return this; })(); + exports.highlightTags = function (name) { + var code = document.getElementsByTagName(name) + for (var i = 0, len = code.length; i < len; ++i) { + code[i].innerHTML = highlight(code[i].innerHTML) + } + } + }) // module: utils.js + // The global object is "self" in Web Workers. + global = (function () { return this })() -/** + /** * Save timer references to avoid Sinon interfering (see GH-237). */ -var Date = global.Date; -var setTimeout = global.setTimeout; -var setInterval = global.setInterval; -var clearTimeout = global.clearTimeout; -var clearInterval = global.clearInterval; + var Date = global.Date + var setTimeout = global.setTimeout + var setInterval = global.setInterval + var clearTimeout = global.clearTimeout + var clearInterval = global.clearInterval -/** + /** * Node shims. * * These are meant only to allow @@ -5710,133 +5626,133 @@ var clearInterval = global.clearInterval; * the browser. */ -var process = {}; -process.exit = function(status){}; -process.stdout = {}; + var process = {} + process.exit = function (status) {} + process.stdout = {} -var uncaughtExceptionHandlers = []; + var uncaughtExceptionHandlers = [] -/** + /** * Remove uncaughtException listener. */ -process.removeListener = function(e, fn){ - if ('uncaughtException' == e) { - global.onerror = function() {}; - var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn); - if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); } + process.removeListener = function (e, fn) { + if (e == 'uncaughtException') { + global.onerror = function () {} + var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn) + if (i != -1) { uncaughtExceptionHandlers.splice(i, 1) } + } } -}; -/** + /** * Implements uncaughtException listener. */ -process.on = function(e, fn){ - if ('uncaughtException' == e) { - global.onerror = function(err, url, line){ - fn(new Error(err + ' (' + url + ':' + line + ')')); - return true; - }; - uncaughtExceptionHandlers.push(fn); + process.on = function (e, fn) { + if (e == 'uncaughtException') { + global.onerror = function (err, url, line) { + fn(new Error(err + ' (' + url + ':' + line + ')')) + return true + } + uncaughtExceptionHandlers.push(fn) + } } -}; -/** + /** * Expose mocha. */ -var Mocha = global.Mocha = require('mocha'), - mocha = global.mocha = new Mocha({ reporter: 'html' }); + var Mocha = global.Mocha = require('mocha') + var mocha = global.mocha = new Mocha({ reporter: 'html' }) -// The BDD UI is registered by default, but no UI will be functional in the -// browser without an explicit call to the overridden `mocha.ui` (see below). -// Ensure that this default UI does not expose its methods to the global scope. -mocha.suite.removeAllListeners('pre-require'); + // The BDD UI is registered by default, but no UI will be functional in the + // browser without an explicit call to the overridden `mocha.ui` (see below). + // Ensure that this default UI does not expose its methods to the global scope. + mocha.suite.removeAllListeners('pre-require') -var immediateQueue = [] - , immediateTimeout; + var immediateQueue = [] + var immediateTimeout -function timeslice() { - var immediateStart = new Date().getTime(); - while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { - immediateQueue.shift()(); - } - if (immediateQueue.length) { - immediateTimeout = setTimeout(timeslice, 0); - } else { - immediateTimeout = null; + function timeslice () { + var immediateStart = new Date().getTime() + while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { + immediateQueue.shift()() + } + if (immediateQueue.length) { + immediateTimeout = setTimeout(timeslice, 0) + } else { + immediateTimeout = null + } } -} -/** + /** * High-performance override of Runner.immediately. */ -Mocha.Runner.immediately = function(callback) { - immediateQueue.push(callback); - if (!immediateTimeout) { - immediateTimeout = setTimeout(timeslice, 0); + Mocha.Runner.immediately = function (callback) { + immediateQueue.push(callback) + if (!immediateTimeout) { + immediateTimeout = setTimeout(timeslice, 0) + } } -}; -/** + /** * Function to allow assertion libraries to throw errors directly into mocha. * This is useful when running tests in a browser because window.onerror will * only receive the 'message' attribute of the Error. */ -mocha.throwError = function(err) { - Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) { - fn(err); - }); - throw err; -}; + mocha.throwError = function (err) { + Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) { + fn(err) + }) + throw err + } -/** + /** * Override ui to ensure that the ui functions are initialized. * Normally this would happen in Mocha.prototype.loadFiles. */ -mocha.ui = function(ui){ - Mocha.prototype.ui.call(this, ui); - this.suite.emit('pre-require', global, null, this); - return this; -}; + mocha.ui = function (ui) { + Mocha.prototype.ui.call(this, ui) + this.suite.emit('pre-require', global, null, this) + return this + } -/** + /** * Setup mocha with the given setting options. */ -mocha.setup = function(opts){ - if ('string' == typeof opts) opts = { ui: opts }; - for (var opt in opts) this[opt](opts[opt]); - return this; -}; + mocha.setup = function (opts) { + if (typeof opts === 'string') opts = { ui: opts } + for (var opt in opts) this[opt](opts[opt]) + return this + } -/** + /** * Run mocha, returning the Runner. */ -mocha.run = function(fn){ - var options = mocha.options; - mocha.globals('location'); + mocha.run = function (fn) { + var options = mocha.options + mocha.globals('location') - var query = Mocha.utils.parseQuery(global.location.search || ''); - if (query.grep) mocha.grep(query.grep); - if (query.invert) mocha.invert(); + var query = Mocha.utils.parseQuery(global.location.search || '') + if (query.grep) mocha.grep(query.grep) + if (query.invert) mocha.invert() - return Mocha.prototype.run.call(mocha, function(){ + return Mocha.prototype.run.call(mocha, function () { // The DOM Document is not available in Web Workers. - if (global.document) { - Mocha.utils.highlightTags('code'); - } - if (fn) fn(); - }); -}; + if (global.document) { + Mocha.utils.highlightTags('code') + } + if (fn) fn() + }) + } -/** + /** * Expose the process shim. */ -Mocha.process = process; -})(); \ No newline at end of file + Mocha.process = process +})() diff --git a/examples/mocha/spec/tests.js b/examples/mocha/spec/tests.js index 80998a2..00d699a 100644 --- a/examples/mocha/spec/tests.js +++ b/examples/mocha/spec/tests.js @@ -1,5 +1,5 @@ -describe('This spec', function () { +describe('This spec', function () { it('should succeed', function () { - expect(5).to.be.a('number'); - }); -}); \ No newline at end of file + expect(5).to.be.a('number') + }) +}) diff --git a/examples/qunit/Gruntfile.js b/examples/qunit/Gruntfile.js index 40a790b..e2bff61 100644 --- a/examples/qunit/Gruntfile.js +++ b/examples/qunit/Gruntfile.js @@ -17,7 +17,7 @@ module.exports = function (grunt) { browserName: 'internet explorer', platform: 'VISTA', version: '9' - }]; + }] grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), @@ -47,10 +47,10 @@ module.exports = function (grunt) { } }, watch: {} - }); + }) - grunt.loadNpmTasks('grunt-contrib-connect'); - grunt.loadNpmTasks('grunt-saucelabs'); + grunt.loadNpmTasks('grunt-contrib-connect') + grunt.loadNpmTasks('grunt-saucelabs') - grunt.registerTask('default', ['connect', 'saucelabs-qunit']); -}; \ No newline at end of file + grunt.registerTask('default', ['connect', 'saucelabs-qunit']) +} diff --git a/examples/qunit/lib/qunit/qunit.js b/examples/qunit/lib/qunit/qunit.js index 0e279fd..e92c9fa 100644 --- a/examples/qunit/lib/qunit/qunit.js +++ b/examples/qunit/lib/qunit/qunit.js @@ -9,35 +9,34 @@ * Date: 2014-01-31T16:40Z */ -(function( window ) { - -var QUnit, - assert, - config, - onErrorFnPrev, - testId = 0, - fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""), - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - // Keep a local reference to Date (GH-283) - Date = window.Date, - setTimeout = window.setTimeout, - clearTimeout = window.clearTimeout, - defined = { - document: typeof window.document !== "undefined", - setTimeout: typeof window.setTimeout !== "undefined", - sessionStorage: (function() { - var x = "qunit-test-string"; - try { - sessionStorage.setItem( x, x ); - sessionStorage.removeItem( x ); - return true; - } catch( e ) { - return false; - } - }()) - }, - /** +(function (window) { + var QUnit + var assert + var config + var onErrorFnPrev + var testId = 0 + var fileName = (sourceFromStacktrace(0) || '').replace(/(:\d+)+\)?/, '').replace(/.+\//, '') + var toString = Object.prototype.toString + var hasOwn = Object.prototype.hasOwnProperty + // Keep a local reference to Date (GH-283) + var Date = window.Date + var setTimeout = window.setTimeout + var clearTimeout = window.clearTimeout + var defined = { + document: typeof window.document !== 'undefined', + setTimeout: typeof window.setTimeout !== 'undefined', + sessionStorage: (function () { + var x = 'qunit-test-string' + try { + sessionStorage.setItem(x, x) + sessionStorage.removeItem(x) + return true + } catch (e) { + return false + } + }()) + } + /** * Provides a normalized error string, correcting an issue * with IE 7 (and prior) where Error.prototype.toString is * not properly implemented @@ -47,1703 +46,1692 @@ var QUnit, * @param {String|Error} error * @return {String} error message */ - errorString = function( error ) { - var name, message, - errorString = error.toString(); - if ( errorString.substring( 0, 7 ) === "[object" ) { - name = error.name ? error.name.toString() : "Error"; - message = error.message ? error.message.toString() : ""; - if ( name && message ) { - return name + ": " + message; - } else if ( name ) { - return name; - } else if ( message ) { - return message; - } else { - return "Error"; - } - } else { - return errorString; - } - }, - /** + var errorString = function (error) { + var name; var message + var errorString = error.toString() + if (errorString.substring(0, 7) === '[object') { + name = error.name ? error.name.toString() : 'Error' + message = error.message ? error.message.toString() : '' + if (name && message) { + return name + ': ' + message + } else if (name) { + return name + } else if (message) { + return message + } else { + return 'Error' + } + } else { + return errorString + } + } + /** * Makes a clone of an object using only Array or Object as base, * and copies over the own enumerable properties. * * @param {Object} obj * @return {Object} New object with only the own properties (recursively). */ - objectValues = function( obj ) { - // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392. - /*jshint newcap: false */ - var key, val, - vals = QUnit.is( "array", obj ) ? [] : {}; - for ( key in obj ) { - if ( hasOwn.call( obj, key ) ) { - val = obj[key]; - vals[key] = val === Object(val) ? objectValues(val) : val; - } - } - return vals; - }; - - -// Root QUnit object. -// `QUnit` initialized at top of scope -QUnit = { - - // call on start of module test to prepend name to all tests - module: function( name, testEnvironment ) { - config.currentModule = name; - config.currentModuleTestEnvironment = testEnvironment; - config.modules[name] = true; - }, - - asyncTest: function( testName, expected, callback ) { - if ( arguments.length === 2 ) { - callback = expected; - expected = null; - } - - QUnit.test( testName, expected, callback, true ); - }, - - test: function( testName, expected, callback, async ) { - var test, - nameHtml = "" + escapeText( testName ) + ""; - - if ( arguments.length === 2 ) { - callback = expected; - expected = null; - } - - if ( config.currentModule ) { - nameHtml = "" + escapeText( config.currentModule ) + ": " + nameHtml; - } - - test = new Test({ - nameHtml: nameHtml, - testName: testName, - expected: expected, - async: async, - callback: callback, - module: config.currentModule, - moduleTestEnvironment: config.currentModuleTestEnvironment, - stack: sourceFromStacktrace( 2 ) - }); - - if ( !validTest( test ) ) { - return; - } - - test.queue(); - }, - - // Specify the number of expected assertions to guarantee that failed test (no assertions are run at all) don't slip through. - expect: function( asserts ) { - if (arguments.length === 1) { - config.current.expected = asserts; - } else { - return config.current.expected; - } - }, - - start: function( count ) { - // QUnit hasn't been initialized yet. - // Note: RequireJS (et al) may delay onLoad - if ( config.semaphore === undefined ) { - QUnit.begin(function() { - // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first - setTimeout(function() { - QUnit.start( count ); - }); - }); - return; - } - - config.semaphore -= count || 1; - // don't start until equal number of stop-calls - if ( config.semaphore > 0 ) { - return; - } - // ignore if start is called more often then stop - if ( config.semaphore < 0 ) { - config.semaphore = 0; - QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) ); - return; - } - // A slight delay, to avoid any current callbacks - if ( defined.setTimeout ) { - setTimeout(function() { - if ( config.semaphore > 0 ) { - return; - } - if ( config.timeout ) { - clearTimeout( config.timeout ); - } - - config.blocking = false; - process( true ); - }, 13); - } else { - config.blocking = false; - process( true ); - } - }, - - stop: function( count ) { - config.semaphore += count || 1; - config.blocking = true; - - if ( config.testTimeout && defined.setTimeout ) { - clearTimeout( config.timeout ); - config.timeout = setTimeout(function() { - QUnit.ok( false, "Test timed out" ); - config.semaphore = 1; - QUnit.start(); - }, config.testTimeout ); - } - } -}; - -// We use the prototype to distinguish between properties that should -// be exposed as globals (and in exports) and those that shouldn't -(function() { - function F() {} - F.prototype = QUnit; - QUnit = new F(); - // Make F QUnit's constructor so that we can add to the prototype later - QUnit.constructor = F; -}()); - -/** + var objectValues = function (obj) { + // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392. + /* jshint newcap: false */ + var key; var val + var vals = QUnit.is('array', obj) ? [] : {} + for (key in obj) { + if (hasOwn.call(obj, key)) { + val = obj[key] + vals[key] = val === Object(val) ? objectValues(val) : val + } + } + return vals + } + + // Root QUnit object. + // `QUnit` initialized at top of scope + QUnit = { + + // call on start of module test to prepend name to all tests + module: function (name, testEnvironment) { + config.currentModule = name + config.currentModuleTestEnvironment = testEnvironment + config.modules[name] = true + }, + + asyncTest: function (testName, expected, callback) { + if (arguments.length === 2) { + callback = expected + expected = null + } + + QUnit.test(testName, expected, callback, true) + }, + + test: function (testName, expected, callback, async) { + var test + var nameHtml = "" + escapeText(testName) + '' + + if (arguments.length === 2) { + callback = expected + expected = null + } + + if (config.currentModule) { + nameHtml = "" + escapeText(config.currentModule) + ': ' + nameHtml + } + + test = new Test({ + nameHtml: nameHtml, + testName: testName, + expected: expected, + async: async, + callback: callback, + module: config.currentModule, + moduleTestEnvironment: config.currentModuleTestEnvironment, + stack: sourceFromStacktrace(2) + }) + + if (!validTest(test)) { + return + } + + test.queue() + }, + + // Specify the number of expected assertions to guarantee that failed test (no assertions are run at all) don't slip through. + expect: function (asserts) { + if (arguments.length === 1) { + config.current.expected = asserts + } else { + return config.current.expected + } + }, + + start: function (count) { + // QUnit hasn't been initialized yet. + // Note: RequireJS (et al) may delay onLoad + if (config.semaphore === undefined) { + QUnit.begin(function () { + // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first + setTimeout(function () { + QUnit.start(count) + }) + }) + return + } + + config.semaphore -= count || 1 + // don't start until equal number of stop-calls + if (config.semaphore > 0) { + return + } + // ignore if start is called more often then stop + if (config.semaphore < 0) { + config.semaphore = 0 + QUnit.pushFailure('Called start() while already started (QUnit.config.semaphore was 0 already)', null, sourceFromStacktrace(2)) + return + } + // A slight delay, to avoid any current callbacks + if (defined.setTimeout) { + setTimeout(function () { + if (config.semaphore > 0) { + return + } + if (config.timeout) { + clearTimeout(config.timeout) + } + + config.blocking = false + process(true) + }, 13) + } else { + config.blocking = false + process(true) + } + }, + + stop: function (count) { + config.semaphore += count || 1 + config.blocking = true + + if (config.testTimeout && defined.setTimeout) { + clearTimeout(config.timeout) + config.timeout = setTimeout(function () { + QUnit.ok(false, 'Test timed out') + config.semaphore = 1 + QUnit.start() + }, config.testTimeout) + } + } + }; + + // We use the prototype to distinguish between properties that should + // be exposed as globals (and in exports) and those that shouldn't + (function () { + function F () {} + F.prototype = QUnit + QUnit = new F() + // Make F QUnit's constructor so that we can add to the prototype later + QUnit.constructor = F + }()) + + /** * Config object: Maintain internal state * Later exposed as QUnit.config * `config` initialized at top of scope */ -config = { - // The queue of tests to run - queue: [], - - // block until document ready - blocking: true, - - // when enabled, show only failing tests - // gets persisted through sessionStorage and can be changed in UI via checkbox - hidepassed: false, - - // by default, run previously failed tests first - // very useful in combination with "Hide passed tests" checked - reorder: true, - - // by default, modify document.title when suite is done - altertitle: true, - - // by default, scroll to top of the page when suite is done - scrolltop: true, - - // when enabled, all tests must call expect() - requireExpects: false, - - // add checkboxes that are persisted in the query-string - // when enabled, the id is set to `true` as a `QUnit.config` property - urlConfig: [ - { - id: "noglobals", - label: "Check for Globals", - tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." - }, - { - id: "notrycatch", - label: "No try-catch", - tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." - } - ], - - // Set of all modules. - modules: {}, - - // logging callback queues - begin: [], - done: [], - log: [], - testStart: [], - testDone: [], - moduleStart: [], - moduleDone: [] -}; - -// Initialize more QUnit.config and QUnit.urlParams -(function() { - var i, current, - location = window.location || { search: "", protocol: "file:" }, - params = location.search.slice( 1 ).split( "&" ), - length = params.length, - urlParams = {}; - - if ( params[ 0 ] ) { - for ( i = 0; i < length; i++ ) { - current = params[ i ].split( "=" ); - current[ 0 ] = decodeURIComponent( current[ 0 ] ); - - // allow just a key to turn on a flag, e.g., test.html?noglobals - current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; - if ( urlParams[ current[ 0 ] ] ) { - urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] ); - } else { - urlParams[ current[ 0 ] ] = current[ 1 ]; - } - } - } - - QUnit.urlParams = urlParams; - - // String search anywhere in moduleName+testName - config.filter = urlParams.filter; - - // Exact match of the module name - config.module = urlParams.module; - - config.testNumber = []; - if ( urlParams.testNumber ) { - - // Ensure that urlParams.testNumber is an array - urlParams.testNumber = [].concat( urlParams.testNumber ); - for ( i = 0; i < urlParams.testNumber.length; i++ ) { - current = urlParams.testNumber[ i ]; - config.testNumber.push( parseInt( current, 10 ) ); - } - } - - // Figure out if we're running the tests from a server or not - QUnit.isLocal = location.protocol === "file:"; -}()); - -extend( QUnit, { - - config: config, - - // Initialize the configuration options - init: function() { - extend( config, { - stats: { all: 0, bad: 0 }, - moduleStats: { all: 0, bad: 0 }, - started: +new Date(), - updateRate: 1000, - blocking: false, - autostart: true, - autorun: false, - filter: "", - queue: [], - semaphore: 1 - }); - - var tests, banner, result, - qunit = id( "qunit" ); - - if ( qunit ) { - qunit.innerHTML = - "

      " + escapeText( document.title ) + "

      " + + config = { + // The queue of tests to run + queue: [], + + // block until document ready + blocking: true, + + // when enabled, show only failing tests + // gets persisted through sessionStorage and can be changed in UI via checkbox + hidepassed: false, + + // by default, run previously failed tests first + // very useful in combination with "Hide passed tests" checked + reorder: true, + + // by default, modify document.title when suite is done + altertitle: true, + + // by default, scroll to top of the page when suite is done + scrolltop: true, + + // when enabled, all tests must call expect() + requireExpects: false, + + // add checkboxes that are persisted in the query-string + // when enabled, the id is set to `true` as a `QUnit.config` property + urlConfig: [ + { + id: 'noglobals', + label: 'Check for Globals', + tooltip: 'Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings.' + }, + { + id: 'notrycatch', + label: 'No try-catch', + tooltip: 'Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings.' + } + ], + + // Set of all modules. + modules: {}, + + // logging callback queues + begin: [], + done: [], + log: [], + testStart: [], + testDone: [], + moduleStart: [], + moduleDone: [] + }; + + // Initialize more QUnit.config and QUnit.urlParams + (function () { + var i; var current + var location = window.location || { search: '', protocol: 'file:' } + var params = location.search.slice(1).split('&') + var length = params.length + var urlParams = {} + + if (params[0]) { + for (i = 0; i < length; i++) { + current = params[i].split('=') + current[0] = decodeURIComponent(current[0]) + + // allow just a key to turn on a flag, e.g., test.html?noglobals + current[1] = current[1] ? decodeURIComponent(current[1]) : true + if (urlParams[current[0]]) { + urlParams[current[0]] = [].concat(urlParams[current[0]], current[1]) + } else { + urlParams[current[0]] = current[1] + } + } + } + + QUnit.urlParams = urlParams + + // String search anywhere in moduleName+testName + config.filter = urlParams.filter + + // Exact match of the module name + config.module = urlParams.module + + config.testNumber = [] + if (urlParams.testNumber) { + // Ensure that urlParams.testNumber is an array + urlParams.testNumber = [].concat(urlParams.testNumber) + for (i = 0; i < urlParams.testNumber.length; i++) { + current = urlParams.testNumber[i] + config.testNumber.push(parseInt(current, 10)) + } + } + + // Figure out if we're running the tests from a server or not + QUnit.isLocal = location.protocol === 'file:' + }()) + + extend(QUnit, { + + config: config, + + // Initialize the configuration options + init: function () { + extend(config, { + stats: { all: 0, bad: 0 }, + moduleStats: { all: 0, bad: 0 }, + started: +new Date(), + updateRate: 1000, + blocking: false, + autostart: true, + autorun: false, + filter: '', + queue: [], + semaphore: 1 + }) + + var tests; var banner; var result + var qunit = id('qunit') + + if (qunit) { + qunit.innerHTML = + "

      " + escapeText(document.title) + '

      ' + "

      " + "
      " + "

      " + - "
        "; - } - - tests = id( "qunit-tests" ); - banner = id( "qunit-banner" ); - result = id( "qunit-testresult" ); - - if ( tests ) { - tests.innerHTML = ""; - } - - if ( banner ) { - banner.className = ""; - } - - if ( result ) { - result.parentNode.removeChild( result ); - } - - if ( tests ) { - result = document.createElement( "p" ); - result.id = "qunit-testresult"; - result.className = "result"; - tests.parentNode.insertBefore( result, tests ); - result.innerHTML = "Running...
         "; - } - }, - - // Resets the test setup. Useful for tests that modify the DOM. - /* + "
          " + } + + tests = id('qunit-tests') + banner = id('qunit-banner') + result = id('qunit-testresult') + + if (tests) { + tests.innerHTML = '' + } + + if (banner) { + banner.className = '' + } + + if (result) { + result.parentNode.removeChild(result) + } + + if (tests) { + result = document.createElement('p') + result.id = 'qunit-testresult' + result.className = 'result' + tests.parentNode.insertBefore(result, tests) + result.innerHTML = 'Running...
           ' + } + }, + + // Resets the test setup. Useful for tests that modify the DOM. + /* DEPRECATED: Use multiple tests instead of resetting inside a test. Use testStart or testDone for custom cleanup. This method will throw an error in 2.0, and will be removed in 2.1 */ - reset: function() { - var fixture = id( "qunit-fixture" ); - if ( fixture ) { - fixture.innerHTML = config.fixture; - } - }, - - // Safe object type checking - is: function( type, obj ) { - return QUnit.objectType( obj ) === type; - }, - - objectType: function( obj ) { - if ( typeof obj === "undefined" ) { - return "undefined"; - } - - // Consider: typeof null === object - if ( obj === null ) { - return "null"; - } - - var match = toString.call( obj ).match(/^\[object\s(.*)\]$/), - type = match && match[1] || ""; - - switch ( type ) { - case "Number": - if ( isNaN(obj) ) { - return "nan"; - } - return "number"; - case "String": - case "Boolean": - case "Array": - case "Date": - case "RegExp": - case "Function": - return type.toLowerCase(); - } - if ( typeof obj === "object" ) { - return "object"; - } - return undefined; - }, - - push: function( result, actual, expected, message ) { - if ( !config.current ) { - throw new Error( "assertion outside test context, was " + sourceFromStacktrace() ); - } - - var output, source, - details = { - module: config.current.module, - name: config.current.testName, - result: result, - message: message, - actual: actual, - expected: expected - }; - - message = escapeText( message ) || ( result ? "okay" : "failed" ); - message = "" + message + ""; - output = message; - - if ( !result ) { - expected = escapeText( QUnit.jsDump.parse(expected) ); - actual = escapeText( QUnit.jsDump.parse(actual) ); - output += ""; - - if ( actual !== expected ) { - output += ""; - output += ""; - } - - source = sourceFromStacktrace(); - - if ( source ) { - details.source = source; - output += ""; - } - - output += "
          Expected:
          " + expected + "
          Result:
          " + actual + "
          Diff:
          " + QUnit.diff( expected, actual ) + "
          Source:
          " + escapeText( source ) + "
          "; - } - - runLoggingCallbacks( "log", QUnit, details ); - - config.current.assertions.push({ - result: !!result, - message: output - }); - }, - - pushFailure: function( message, source, actual ) { - if ( !config.current ) { - throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) ); - } - - var output, - details = { - module: config.current.module, - name: config.current.testName, - result: false, - message: message - }; - - message = escapeText( message ) || "error"; - message = "" + message + ""; - output = message; - - output += ""; - - if ( actual ) { - output += ""; - } - - if ( source ) { - details.source = source; - output += ""; - } - - output += "
          Result:
          " + escapeText( actual ) + "
          Source:
          " + escapeText( source ) + "
          "; - - runLoggingCallbacks( "log", QUnit, details ); - - config.current.assertions.push({ - result: false, - message: output - }); - }, - - url: function( params ) { - params = extend( extend( {}, QUnit.urlParams ), params ); - var key, - querystring = "?"; - - for ( key in params ) { - if ( hasOwn.call( params, key ) ) { - querystring += encodeURIComponent( key ) + "=" + - encodeURIComponent( params[ key ] ) + "&"; - } - } - return window.location.protocol + "//" + window.location.host + - window.location.pathname + querystring.slice( 0, -1 ); - }, - - extend: extend, - id: id, - addEvent: addEvent, - addClass: addClass, - hasClass: hasClass, - removeClass: removeClass - // load, equiv, jsDump, diff: Attached later -}); - -/** + reset: function () { + var fixture = id('qunit-fixture') + if (fixture) { + fixture.innerHTML = config.fixture + } + }, + + // Safe object type checking + is: function (type, obj) { + return QUnit.objectType(obj) === type + }, + + objectType: function (obj) { + if (typeof obj === 'undefined') { + return 'undefined' + } + + // Consider: typeof null === object + if (obj === null) { + return 'null' + } + + var match = toString.call(obj).match(/^\[object\s(.*)\]$/) + var type = match && match[1] || '' + + switch (type) { + case 'Number': + if (isNaN(obj)) { + return 'nan' + } + return 'number' + case 'String': + case 'Boolean': + case 'Array': + case 'Date': + case 'RegExp': + case 'Function': + return type.toLowerCase() + } + if (typeof obj === 'object') { + return 'object' + } + return undefined + }, + + push: function (result, actual, expected, message) { + if (!config.current) { + throw new Error('assertion outside test context, was ' + sourceFromStacktrace()) + } + + var output; var source + var details = { + module: config.current.module, + name: config.current.testName, + result: result, + message: message, + actual: actual, + expected: expected + } + + message = escapeText(message) || (result ? 'okay' : 'failed') + message = "" + message + '' + output = message + + if (!result) { + expected = escapeText(QUnit.jsDump.parse(expected)) + actual = escapeText(QUnit.jsDump.parse(actual)) + output += "' + + if (actual !== expected) { + output += "' + output += "' + } + + source = sourceFromStacktrace() + + if (source) { + details.source = source + output += "' + } + + output += '
          Expected:
          " + expected + '
          Result:
          " + actual + '
          Diff:
          " + QUnit.diff(expected, actual) + '
          Source:
          " + escapeText(source) + '
          ' + } + + runLoggingCallbacks('log', QUnit, details) + + config.current.assertions.push({ + result: !!result, + message: output + }) + }, + + pushFailure: function (message, source, actual) { + if (!config.current) { + throw new Error('pushFailure() assertion outside test context, was ' + sourceFromStacktrace(2)) + } + + var output + var details = { + module: config.current.module, + name: config.current.testName, + result: false, + message: message + } + + message = escapeText(message) || 'error' + message = "" + message + '' + output = message + + output += '' + + if (actual) { + output += "' + } + + if (source) { + details.source = source + output += "' + } + + output += '
          Result:
          " + escapeText(actual) + '
          Source:
          " + escapeText(source) + '
          ' + + runLoggingCallbacks('log', QUnit, details) + + config.current.assertions.push({ + result: false, + message: output + }) + }, + + url: function (params) { + params = extend(extend({}, QUnit.urlParams), params) + var key + var querystring = '?' + + for (key in params) { + if (hasOwn.call(params, key)) { + querystring += encodeURIComponent(key) + '=' + + encodeURIComponent(params[key]) + '&' + } + } + return window.location.protocol + '//' + window.location.host + + window.location.pathname + querystring.slice(0, -1) + }, + + extend: extend, + id: id, + addEvent: addEvent, + addClass: addClass, + hasClass: hasClass, + removeClass: removeClass + // load, equiv, jsDump, diff: Attached later + }) + + /** * @deprecated: Created for backwards compatibility with test runner that set the hook function * into QUnit.{hook}, instead of invoking it and passing the hook function. * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. * Doing this allows us to tell if the following methods have been overwritten on the actual * QUnit object. */ -extend( QUnit.constructor.prototype, { - - // Logging callbacks; all receive a single argument with the listed properties - // run test/logs.html for any related changes - begin: registerLoggingCallback( "begin" ), - - // done: { failed, passed, total, runtime } - done: registerLoggingCallback( "done" ), - - // log: { result, actual, expected, message } - log: registerLoggingCallback( "log" ), - - // testStart: { name } - testStart: registerLoggingCallback( "testStart" ), - - // testDone: { name, failed, passed, total, runtime } - testDone: registerLoggingCallback( "testDone" ), - - // moduleStart: { name } - moduleStart: registerLoggingCallback( "moduleStart" ), - - // moduleDone: { name, failed, passed, total } - moduleDone: registerLoggingCallback( "moduleDone" ) -}); - -if ( !defined.document || document.readyState === "complete" ) { - config.autorun = true; -} - -QUnit.load = function() { - runLoggingCallbacks( "begin", QUnit, {} ); - - // Initialize the config, saving the execution queue - var banner, filter, i, j, label, len, main, ol, toolbar, val, selection, - urlConfigContainer, moduleFilter, userAgent, - numModules = 0, - moduleNames = [], - moduleFilterHtml = "", - urlConfigHtml = "", - oldconfig = extend( {}, config ); - - QUnit.init(); - extend(config, oldconfig); - - config.blocking = false; - - len = config.urlConfig.length; - - for ( i = 0; i < len; i++ ) { - val = config.urlConfig[i]; - if ( typeof val === "string" ) { - val = { - id: val, - label: val - }; - } - config[ val.id ] = QUnit.urlParams[ val.id ]; - if ( !val.value || typeof val.value === "string" ) { - urlConfigHtml += ""; - } else { - urlConfigHtml += "