diff --git a/bin/_mocha b/bin/_mocha index bef97990f7..97542ac59c 100755 --- a/bin/_mocha +++ b/bin/_mocha @@ -58,7 +58,7 @@ const exit = code => { // https://github.com/joyent/node/issues/6247 is just one bug example // https://github.com/visionmedia/mocha/issues/333 has a good discussion const done = () => { - if (!(draining--)) { + if (!draining--) { process.exit(clampedCode); } }; @@ -150,9 +150,16 @@ const images = { // options program - .version(JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8')).version) + .version( + JSON.parse( + fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8') + ).version + ) .usage('[debug] [options] [files]') - .option('-A, --async-only', 'force all tests to take a callback (async) or return a promise') + .option( + '-A, --async-only', + 'force all tests to take a callback (async) or return a promise' + ) .option('-c, --colors', 'force enabling of colors') .option('-C, --no-colors', 'force disabling of colors') .option('-G, --growl', 'enable growl notification support') @@ -168,24 +175,53 @@ program .option('-r, --require ', 'require the given module') .option('-s, --slow ', '"slow" test threshold in milliseconds [75]') .option('-t, --timeout ', 'set test-case timeout in milliseconds [2000]') - .option('-u, --ui ', `specify user-interface (${interfaceNames.join('|')})`, 'bdd') + .option( + '-u, --ui ', + `specify user-interface (${interfaceNames.join('|')})`, + 'bdd' + ) .option('-w, --watch', 'watch files for changes') .option('--check-leaks', 'check for global variable leaks') .option('--full-trace', 'display the full stack trace') - .option('--compilers :,...', 'use the given module(s) to compile files', list, []) + .option( + '--compilers :,...', + 'use the given module(s) to compile files', + list, + [] + ) .option('--debug-brk', "enable node's debugger breaking on the first line") - .option('--globals ', 'allow the given comma-delimited global [names]', list, []) + .option( + '--globals ', + 'allow the given comma-delimited global [names]', + list, + [] + ) .option('--es_staging', 'enable all staged features') - .option('--harmony<_classes,_generators,...>', 'all node --harmony* flags are available') - .option('--preserve-symlinks', 'Instructs the module loader to preserve symbolic links when resolving and caching modules') + .option( + '--harmony<_classes,_generators,...>', + 'all node --harmony* flags are available' + ) + .option( + '--preserve-symlinks', + 'Instructs the module loader to preserve symbolic links when resolving and caching modules' + ) .option('--icu-data-dir', 'include ICU data') - .option('--inline-diffs', 'display actual/expected differences inline within each string') + .option( + '--inline-diffs', + 'display actual/expected differences inline within each string' + ) .option('--no-diff', 'do not show a diff on failure') .option('--inspect', 'activate devtools in chrome') - .option('--inspect-brk', 'activate devtools in chrome and break on the first line') + .option( + '--inspect-brk', + 'activate devtools in chrome and break on the first line' + ) .option('--interfaces', 'display available interfaces') .option('--no-deprecation', 'silence deprecation warnings') - .option('--exit', 'force shutdown of the event loop after test run: mocha will call process.exit') + .option( + '--exit', + 'force shutdown of the event loop after test run: mocha will call process.exit' + ) .option('--no-timeouts', 'disables timeouts, given implicitly with --debug') .option('--no-warnings', 'silence all node process warnings') .option('--opts ', 'specify opts path', 'test/mocha.opts') @@ -195,18 +231,37 @@ program .option('--log-timer-events', 'Time events including external callbacks') .option('--recursive', 'include sub directories') .option('--reporters', 'display available reporters') - .option('--retries ', 'set numbers of time to retry a failed test case') - .option('--throw-deprecation', 'throw an exception anytime a deprecated function is used') + .option( + '--retries ', + 'set numbers of time to retry a failed test case' + ) + .option( + '--throw-deprecation', + 'throw an exception anytime a deprecated function is used' + ) .option('--trace', 'trace function calls') .option('--trace-deprecation', 'show stack traces on deprecations') .option('--trace-warnings', 'show stack traces on node process warnings') .option('--use_strict', 'enforce strict mode') - .option('--watch-extensions ,...', 'specify extensions to monitor with --watch', list, []) + .option( + '--watch-extensions ,...', + 'specify extensions to monitor with --watch', + list, + [] + ) .option('--delay', 'wait for async suite definition') .option('--allow-uncaught', 'enable uncaught errors to propagate') .option('--forbid-only', 'causes test marked with only to fail the suite') - .option('--forbid-pending', 'causes pending tests and test marked with skip to fail the suite') - .option('--file ', 'include a file to be ran during the suite', collect, []) + .option( + '--forbid-pending', + 'causes pending tests and test marked with skip to fail the suite' + ) + .option( + '--file ', + 'include a file to be ran during the suite', + collect, + [] + ) .option('--exclude ', 'a file or glob pattern to ignore', collect, []); program._name = 'mocha'; @@ -447,7 +502,7 @@ if (program.forbidPending) mocha.forbidPending(); if (program.compilers.length > 0) { require('util').deprecate(() => {}, - '"--compilers" will be removed in a future version of Mocha; see https://git.io/vdcSr for more info')(); + '"--compilers" will be removed in a future version of Mocha; see https://git.io/vdcSr for more info')(); } const extensions = ['js']; program.compilers.forEach(c => { @@ -489,7 +544,9 @@ args.forEach(arg => { newFiles = utils.lookupFiles(arg, extensions, program.recursive); } catch (err) { if (err.message.indexOf('cannot resolve path') === 0) { - console.error(`Warning: Could not find any test files matching pattern: ${arg}`); + console.error( + `Warning: Could not find any test files matching pattern: ${arg}` + ); return; } @@ -500,7 +557,9 @@ args.forEach(arg => { if (typeof newFiles === 'string') { newFiles = [newFiles]; } - newFiles = newFiles.filter(fileName => program.exclude.every(pattern => !minimatch(fileName, pattern))); + newFiles = newFiles.filter(fileName => + program.exclude.every(pattern => !minimatch(fileName, pattern)) + ); } files = files.concat(newFiles); @@ -585,7 +644,7 @@ if (program.watch) { } }); } else { -// load + // load mocha.files = files; runner = mocha.run(program.exit ? exit : exitLater); diff --git a/bin/options.js b/bin/options.js index ac835bf833..41f7222a62 100644 --- a/bin/options.js +++ b/bin/options.js @@ -16,17 +16,22 @@ module.exports = getOptions; * Get options. */ -function getOptions () { - if (process.argv.length === 3 && (process.argv[2] === '-h' || process.argv[2] === '--help')) { +function getOptions() { + if ( + process.argv.length === 3 && + (process.argv[2] === '-h' || process.argv[2] === '--help') + ) { return; } - const optsPath = process.argv.indexOf('--opts') === -1 - ? 'test/mocha.opts' - : process.argv[process.argv.indexOf('--opts') + 1]; + const optsPath = + process.argv.indexOf('--opts') === -1 + ? 'test/mocha.opts' + : process.argv[process.argv.indexOf('--opts') + 1]; try { - const opts = fs.readFileSync(optsPath, 'utf8') + const opts = fs + .readFileSync(optsPath, 'utf8') .replace(/\\\s/g, '%20') .split(/\s/) .filter(Boolean) diff --git a/browser-entry.js b/browser-entry.js index 2d1aeecea5..ad422e6c5b 100644 --- a/browser-entry.js +++ b/browser-entry.js @@ -17,7 +17,7 @@ var Mocha = require('./lib/mocha'); * @return {undefined} */ -var mocha = new Mocha({ reporter: 'html' }); +var mocha = new Mocha({reporter: 'html'}); /** * Save timer references to avoid Sinon interfering (see GH-237). @@ -38,12 +38,12 @@ var originalOnerrorHandler = global.onerror; * Revert to original onerror handler if previously defined. */ -process.removeListener = function (e, fn) { +process.removeListener = function(e, fn) { if (e === 'uncaughtException') { if (originalOnerrorHandler) { global.onerror = originalOnerrorHandler; } else { - global.onerror = function () {}; + global.onerror = function() {}; } var i = uncaughtExceptionHandlers.indexOf(fn); if (i !== -1) { @@ -56,9 +56,9 @@ process.removeListener = function (e, fn) { * Implements uncaughtException listener. */ -process.on = function (e, fn) { +process.on = function(e, fn) { if (e === 'uncaughtException') { - global.onerror = function (err, url, line) { + global.onerror = function(err, url, line) { fn(new Error(err + ' (' + url + ':' + line + ')')); return !mocha.allowUncaught; }; @@ -74,9 +74,9 @@ mocha.suite.removeAllListeners('pre-require'); var immediateQueue = []; var immediateTimeout; -function timeslice () { +function timeslice() { var immediateStart = new Date().getTime(); - while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { + while (immediateQueue.length && new Date().getTime() - immediateStart < 100) { immediateQueue.shift()(); } if (immediateQueue.length) { @@ -90,7 +90,7 @@ function timeslice () { * High-performance override of Runner.immediately. */ -Mocha.Runner.immediately = function (callback) { +Mocha.Runner.immediately = function(callback) { immediateQueue.push(callback); if (!immediateTimeout) { immediateTimeout = setTimeout(timeslice, 0); @@ -102,8 +102,8 @@ Mocha.Runner.immediately = function (callback) { * 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) { - uncaughtExceptionHandlers.forEach(function (fn) { +mocha.throwError = function(err) { + uncaughtExceptionHandlers.forEach(function(fn) { fn(err); }); throw err; @@ -114,7 +114,7 @@ mocha.throwError = function (err) { * Normally this would happen in Mocha.prototype.loadFiles. */ -mocha.ui = function (ui) { +mocha.ui = function(ui) { Mocha.prototype.ui.call(this, ui); this.suite.emit('pre-require', global, null, this); return this; @@ -124,9 +124,9 @@ mocha.ui = function (ui) { * Setup mocha with the given setting options. */ -mocha.setup = function (opts) { +mocha.setup = function(opts) { if (typeof opts === 'string') { - opts = { ui: opts }; + opts = {ui: opts}; } for (var opt in opts) { if (opts.hasOwnProperty(opt)) { @@ -140,7 +140,7 @@ mocha.setup = function (opts) { * Run mocha, returning the Runner. */ -mocha.run = function (fn) { +mocha.run = function(fn) { var options = mocha.options; mocha.globals('location'); @@ -155,10 +155,14 @@ mocha.run = function (fn) { mocha.invert(); } - return Mocha.prototype.run.call(mocha, function (err) { + return Mocha.prototype.run.call(mocha, function(err) { // The DOM Document is not available in Web Workers. var document = global.document; - if (document && document.getElementById('mocha') && options.noHighlighting !== true) { + if ( + document && + document.getElementById('mocha') && + options.noHighlighting !== true + ) { Mocha.utils.highlightTags('code'); } if (fn) { diff --git a/karma.conf.js b/karma.conf.js index 1db52054f1..1ccbb2bbbf 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -16,11 +16,7 @@ const browserPlatformPairs = { module.exports = config => { let bundleDirpath; const cfg = { - frameworks: [ - 'browserify', - 'expect', - 'mocha' - ], + frameworks: ['browserify', 'expect', 'mocha'], files: [ // we use the BDD interface for all of the tests that // aren't interface-specific. @@ -32,8 +28,9 @@ module.exports = config => { }, browserify: { debug: true, - configure: function configure (b) { - b.ignore('glob') + configure: function configure(b) { + b + .ignore('glob') .ignore('fs') .ignore('path') .ignore('supports-color') @@ -43,8 +40,10 @@ module.exports = config => { } if (bundleDirpath) { // write bundle to directory for debugging - fs.writeFileSync(path.join(bundleDirpath, - `mocha.${Date.now()}.js`), content); + fs.writeFileSync( + path.join(bundleDirpath, `mocha.${Date.now()}.js`), + content + ); } }); } @@ -155,7 +154,7 @@ module.exports = config => { config.set(cfg); }; -function addSauceTests (cfg) { +function addSauceTests(cfg) { cfg.reporters.push('saucelabs'); const browsers = Object.keys(browserPlatformPairs); cfg.browsers = cfg.browsers.concat(browsers); diff --git a/lib/browser/progress.js b/lib/browser/progress.js index 2b23656b99..0dcb341898 100644 --- a/lib/browser/progress.js +++ b/lib/browser/progress.js @@ -9,7 +9,7 @@ module.exports = Progress; /** * Initialize a new `Progress` indicator. */ -function Progress () { +function Progress() { this.percent = 0; this.size(0); this.fontSize(11); @@ -23,7 +23,7 @@ function Progress () { * @param {number} size * @return {Progress} Progress instance. */ -Progress.prototype.size = function (size) { +Progress.prototype.size = function(size) { this._size = size; return this; }; @@ -35,7 +35,7 @@ Progress.prototype.size = function (size) { * @param {string} text * @return {Progress} Progress instance. */ -Progress.prototype.text = function (text) { +Progress.prototype.text = function(text) { this._text = text; return this; }; @@ -47,7 +47,7 @@ Progress.prototype.text = function (text) { * @param {number} size * @return {Progress} Progress instance. */ -Progress.prototype.fontSize = function (size) { +Progress.prototype.fontSize = function(size) { this._fontSize = size; return this; }; @@ -58,7 +58,7 @@ Progress.prototype.fontSize = function (size) { * @param {string} family * @return {Progress} Progress instance. */ -Progress.prototype.font = function (family) { +Progress.prototype.font = function(family) { this._font = family; return this; }; @@ -69,7 +69,7 @@ Progress.prototype.font = function (family) { * @param {number} n * @return {Progress} Progress instance. */ -Progress.prototype.update = function (n) { +Progress.prototype.update = function(n) { this.percent = n; return this; }; @@ -80,7 +80,7 @@ Progress.prototype.update = function (n) { * @param {CanvasRenderingContext2d} ctx * @return {Progress} Progress instance. */ -Progress.prototype.draw = function (ctx) { +Progress.prototype.draw = function(ctx) { try { var percent = Math.min(this.percent, 100); var size = this._size; diff --git a/lib/browser/tty.js b/lib/browser/tty.js index c77f7e99a6..e903365023 100644 --- a/lib/browser/tty.js +++ b/lib/browser/tty.js @@ -1,10 +1,10 @@ 'use strict'; -exports.isatty = function isatty () { +exports.isatty = function isatty() { return true; }; -exports.getWindowSize = function getWindowSize () { +exports.getWindowSize = function getWindowSize() { if ('innerHeight' in global) { return [global.innerHeight, global.innerWidth]; } diff --git a/lib/context.js b/lib/context.js index 342e5cfcdc..812162b137 100644 --- a/lib/context.js +++ b/lib/context.js @@ -13,7 +13,7 @@ module.exports = Context; * * @api private */ -function Context () {} +function Context() {} /** * Set or get the context `Runnable` to `runnable`. @@ -22,7 +22,7 @@ function Context () {} * @param {Runnable} runnable * @return {Context} context */ -Context.prototype.runnable = function (runnable) { +Context.prototype.runnable = function(runnable) { if (!arguments.length) { return this._runnable; } @@ -37,7 +37,7 @@ Context.prototype.runnable = function (runnable) { * @param {number} ms * @return {Context} self */ -Context.prototype.timeout = function (ms) { +Context.prototype.timeout = function(ms) { if (!arguments.length) { return this.runnable().timeout(); } @@ -52,7 +52,7 @@ Context.prototype.timeout = function (ms) { * @param {boolean} enabled * @return {Context} self */ -Context.prototype.enableTimeouts = function (enabled) { +Context.prototype.enableTimeouts = function(enabled) { if (!arguments.length) { return this.runnable().enableTimeouts(); } @@ -67,7 +67,7 @@ Context.prototype.enableTimeouts = function (enabled) { * @param {number} ms * @return {Context} self */ -Context.prototype.slow = function (ms) { +Context.prototype.slow = function(ms) { if (!arguments.length) { return this.runnable().slow(); } @@ -81,7 +81,7 @@ Context.prototype.slow = function (ms) { * @api private * @throws Pending */ -Context.prototype.skip = function () { +Context.prototype.skip = function() { this.runnable().skip(); }; @@ -92,7 +92,7 @@ Context.prototype.skip = function () { * @param {number} n * @return {Context} self */ -Context.prototype.retries = function (n) { +Context.prototype.retries = function(n) { if (!arguments.length) { return this.runnable().retries(); } diff --git a/lib/hook.js b/lib/hook.js index 6512d0ef0a..71440d23d0 100644 --- a/lib/hook.js +++ b/lib/hook.js @@ -17,7 +17,7 @@ module.exports = Hook; * @param {String} title * @param {Function} fn */ -function Hook (title, fn) { +function Hook(title, fn) { Runnable.call(this, title, fn); this.type = 'hook'; } @@ -35,7 +35,7 @@ inherits(Hook, Runnable); * @param {Error} err * @return {Error} */ -Hook.prototype.error = function (err) { +Hook.prototype.error = function(err) { if (!arguments.length) { err = this._error; this._error = null; diff --git a/lib/interfaces/bdd.js b/lib/interfaces/bdd.js index 17dae8266e..730e67e0e8 100644 --- a/lib/interfaces/bdd.js +++ b/lib/interfaces/bdd.js @@ -19,10 +19,10 @@ var Test = require('../test'); * * @param {Suite} suite Root suite. */ -module.exports = function bddInterface (suite) { +module.exports = function bddInterface(suite) { var suites = [suite]; - suite.on('pre-require', function (context, file, mocha) { + suite.on('pre-require', function(context, file, mocha) { var common = require('./common')(suites, context, mocha); context.before = common.before; @@ -36,7 +36,7 @@ module.exports = function bddInterface (suite) { * and/or tests. */ - context.describe = context.context = function (title, fn) { + context.describe = context.context = function(title, fn) { return common.suite.create({ title: title, file: file, @@ -48,7 +48,10 @@ module.exports = function bddInterface (suite) { * Pending describe. */ - context.xdescribe = context.xcontext = context.describe.skip = function (title, fn) { + context.xdescribe = context.xcontext = context.describe.skip = function( + title, + fn + ) { return common.suite.skip({ title: title, file: file, @@ -60,7 +63,7 @@ module.exports = function bddInterface (suite) { * Exclusive suite. */ - context.describe.only = function (title, fn) { + context.describe.only = function(title, fn) { return common.suite.only({ title: title, file: file, @@ -74,7 +77,7 @@ module.exports = function bddInterface (suite) { * acting as a thunk. */ - context.it = context.specify = function (title, fn) { + context.it = context.specify = function(title, fn) { var suite = suites[0]; if (suite.isPending()) { fn = null; @@ -89,7 +92,7 @@ module.exports = function bddInterface (suite) { * Exclusive test-case. */ - context.it.only = function (title, fn) { + context.it.only = function(title, fn) { return common.test.only(mocha, context.it(title, fn)); }; @@ -97,14 +100,14 @@ module.exports = function bddInterface (suite) { * Pending test case. */ - context.xit = context.xspecify = context.it.skip = function (title) { + context.xit = context.xspecify = context.it.skip = function(title) { return context.it(title); }; /** * Number of attempts to retry. */ - context.it.retries = function (n) { + context.it.retries = function(n) { context.retries(n); }; }); diff --git a/lib/interfaces/common.js b/lib/interfaces/common.js index f0cdd4eb1a..4ca340a608 100644 --- a/lib/interfaces/common.js +++ b/lib/interfaces/common.js @@ -10,7 +10,7 @@ var Suite = require('../suite'); * @param {Mocha} mocha * @return {Object} An object containing common functions. */ -module.exports = function (suites, context, mocha) { +module.exports = function(suites, context, mocha) { return { /** * This is only present if flag --delay is passed into Mocha. It triggers @@ -19,8 +19,8 @@ module.exports = function (suites, context, mocha) { * @param {Suite} suite The root suite. * @return {Function} A function which runs the root suite */ - runWithSuite: function runWithSuite (suite) { - return function run () { + runWithSuite: function runWithSuite(suite) { + return function run() { suite.run(); }; }, @@ -31,7 +31,7 @@ module.exports = function (suites, context, mocha) { * @param {string} name * @param {Function} fn */ - before: function (name, fn) { + before: function(name, fn) { suites[0].beforeAll(name, fn); }, @@ -41,7 +41,7 @@ module.exports = function (suites, context, mocha) { * @param {string} name * @param {Function} fn */ - after: function (name, fn) { + after: function(name, fn) { suites[0].afterAll(name, fn); }, @@ -51,7 +51,7 @@ module.exports = function (suites, context, mocha) { * @param {string} name * @param {Function} fn */ - beforeEach: function (name, fn) { + beforeEach: function(name, fn) { suites[0].beforeEach(name, fn); }, @@ -61,7 +61,7 @@ module.exports = function (suites, context, mocha) { * @param {string} name * @param {Function} fn */ - afterEach: function (name, fn) { + afterEach: function(name, fn) { suites[0].afterEach(name, fn); }, @@ -73,7 +73,7 @@ module.exports = function (suites, context, mocha) { * @param {Object} opts * @returns {Suite} */ - only: function only (opts) { + only: function only(opts) { opts.isOnly = true; return this.create(opts); }, @@ -85,7 +85,7 @@ module.exports = function (suites, context, mocha) { * @param {Object} opts * @returns {Suite} */ - skip: function skip (opts) { + skip: function skip(opts) { opts.pending = true; return this.create(opts); }, @@ -100,7 +100,7 @@ module.exports = function (suites, context, mocha) { * @param {boolean} [opts.isOnly] Is Suite exclusive? * @returns {Suite} */ - create: function create (opts) { + create: function create(opts) { var suite = Suite.create(suites[0], opts.title); suite.pending = Boolean(opts.pending); suite.file = opts.file; @@ -112,7 +112,11 @@ module.exports = function (suites, context, mocha) { opts.fn.call(suite); suites.shift(); } else if (typeof opts.fn === 'undefined' && !suite.pending) { - throw new Error('Suite "' + suite.fullTitle() + '" was defined but no callback was supplied. Supply a callback or explicitly skip the suite.'); + throw new Error( + 'Suite "' + + suite.fullTitle() + + '" was defined but no callback was supplied. Supply a callback or explicitly skip the suite.' + ); } else if (!opts.fn && suite.pending) { suites.shift(); } @@ -122,7 +126,6 @@ module.exports = function (suites, context, mocha) { }, test: { - /** * Exclusive test-case. * @@ -130,7 +133,7 @@ module.exports = function (suites, context, mocha) { * @param {Function} test * @returns {*} */ - only: function (mocha, test) { + only: function(mocha, test) { test.parent._onlyTests = test.parent._onlyTests.concat(test); return test; }, @@ -140,7 +143,7 @@ module.exports = function (suites, context, mocha) { * * @param {string} title */ - skip: function (title) { + skip: function(title) { context.test(title); }, @@ -149,7 +152,7 @@ module.exports = function (suites, context, mocha) { * * @param {number} n */ - retries: function (n) { + retries: function(n) { context.retries(n); } } diff --git a/lib/interfaces/exports.js b/lib/interfaces/exports.js index 9de4763aa2..1a5c5bbc2c 100644 --- a/lib/interfaces/exports.js +++ b/lib/interfaces/exports.js @@ -19,12 +19,12 @@ var Test = require('../test'); * * @param {Suite} suite Root suite. */ -module.exports = function (suite) { +module.exports = function(suite) { var suites = [suite]; suite.on('require', visit); - function visit (obj, file) { + function visit(obj, file) { var suite; for (var key in obj) { if (typeof obj[key] === 'function') { diff --git a/lib/interfaces/qunit.js b/lib/interfaces/qunit.js index 96d9788092..ad3c900c2c 100644 --- a/lib/interfaces/qunit.js +++ b/lib/interfaces/qunit.js @@ -27,10 +27,10 @@ var Test = require('../test'); * * @param {Suite} suite Root suite. */ -module.exports = function qUnitInterface (suite) { +module.exports = function qUnitInterface(suite) { var suites = [suite]; - suite.on('pre-require', function (context, file, mocha) { + suite.on('pre-require', function(context, file, mocha) { var common = require('./common')(suites, context, mocha); context.before = common.before; @@ -42,7 +42,7 @@ module.exports = function qUnitInterface (suite) { * Describe a "suite" with the given `title`. */ - context.suite = function (title) { + context.suite = function(title) { if (suites.length > 1) { suites.shift(); } @@ -57,7 +57,7 @@ module.exports = function qUnitInterface (suite) { * Exclusive Suite. */ - context.suite.only = function (title) { + context.suite.only = function(title) { if (suites.length > 1) { suites.shift(); } @@ -74,7 +74,7 @@ module.exports = function qUnitInterface (suite) { * acting as a thunk. */ - context.test = function (title, fn) { + context.test = function(title, fn) { var test = new Test(title, fn); test.file = file; suites[0].addTest(test); @@ -85,7 +85,7 @@ module.exports = function qUnitInterface (suite) { * Exclusive test-case. */ - context.test.only = function (title, fn) { + context.test.only = function(title, fn) { return common.test.only(mocha, context.test(title, fn)); }; diff --git a/lib/interfaces/tdd.js b/lib/interfaces/tdd.js index 1d238e9eab..1e72cf7ac3 100644 --- a/lib/interfaces/tdd.js +++ b/lib/interfaces/tdd.js @@ -27,10 +27,10 @@ var Test = require('../test'); * * @param {Suite} suite Root suite. */ -module.exports = function (suite) { +module.exports = function(suite) { var suites = [suite]; - suite.on('pre-require', function (context, file, mocha) { + suite.on('pre-require', function(context, file, mocha) { var common = require('./common')(suites, context, mocha); context.setup = common.beforeEach; @@ -43,7 +43,7 @@ module.exports = function (suite) { * Describe a "suite" with the given `title` and callback `fn` containing * nested suites and/or tests. */ - context.suite = function (title, fn) { + context.suite = function(title, fn) { return common.suite.create({ title: title, file: file, @@ -54,7 +54,7 @@ module.exports = function (suite) { /** * Pending suite. */ - context.suite.skip = function (title, fn) { + context.suite.skip = function(title, fn) { return common.suite.skip({ title: title, file: file, @@ -65,7 +65,7 @@ module.exports = function (suite) { /** * Exclusive test-case. */ - context.suite.only = function (title, fn) { + context.suite.only = function(title, fn) { return common.suite.only({ title: title, file: file, @@ -77,7 +77,7 @@ module.exports = function (suite) { * Describe a specification or test-case with the given `title` and * callback `fn` acting as a thunk. */ - context.test = function (title, fn) { + context.test = function(title, fn) { var suite = suites[0]; if (suite.isPending()) { fn = null; @@ -92,7 +92,7 @@ module.exports = function (suite) { * Exclusive test-case. */ - context.test.only = function (title, fn) { + context.test.only = function(title, fn) { return common.test.only(mocha, context.test(title, fn)); }; diff --git a/lib/mocha.js b/lib/mocha.js index 8c676dbbf9..673dbec394 100644 --- a/lib/mocha.js +++ b/lib/mocha.js @@ -57,7 +57,7 @@ exports.Test = require('./test'); * @param {string} name * @return {string} */ -function image (name) { +function image(name) { return path.join(__dirname, '..', 'assets', 'growl', name + '.png'); } @@ -80,7 +80,7 @@ function image (name) { * @class Mocha * @param {Object} options */ -function Mocha (options) { +function Mocha(options) { options = options || {}; this.files = []; this.options = options; @@ -116,7 +116,7 @@ function Mocha (options) { * @api public * @param {boolean} [bail] */ -Mocha.prototype.bail = function (bail) { +Mocha.prototype.bail = function(bail) { if (!arguments.length) { bail = true; } @@ -131,7 +131,7 @@ Mocha.prototype.bail = function (bail) { * @api public * @param {string} file */ -Mocha.prototype.addFile = function (file) { +Mocha.prototype.addFile = function(file) { this.files.push(file); return this; }; @@ -146,7 +146,7 @@ Mocha.prototype.addFile = function (file) { * @param {string|Function} reporter name or constructor * @param {Object} reporterOptions optional options */ -Mocha.prototype.reporter = function (reporter, reporterOptions) { +Mocha.prototype.reporter = function(reporter, reporterOptions) { if (typeof reporter === 'function') { this._reporter = reporter; } else { @@ -166,18 +166,28 @@ Mocha.prototype.reporter = function (reporter, reporterOptions) { try { _reporter = require(path.resolve(process.cwd(), reporter)); } catch (_err) { - err.message.indexOf('Cannot find module') !== -1 ? console.warn('"' + reporter + '" reporter not found') - : console.warn('"' + reporter + '" reporter blew up with error:\n' + err.stack); + err.message.indexOf('Cannot find module') !== -1 + ? console.warn('"' + reporter + '" reporter not found') + : console.warn( + '"' + + reporter + + '" reporter blew up with error:\n' + + err.stack + ); } } else { - console.warn('"' + reporter + '" reporter blew up with error:\n' + err.stack); + console.warn( + '"' + reporter + '" reporter blew up with error:\n' + err.stack + ); } } } 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).'); + 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 + '"'); @@ -194,7 +204,7 @@ Mocha.prototype.reporter = function (reporter, reporterOptions) { * @api public * @param {string} bdd */ -Mocha.prototype.ui = function (name) { +Mocha.prototype.ui = function(name) { name = name || 'bdd'; this._ui = exports.interfaces[name]; if (!this._ui) { @@ -206,7 +216,7 @@ Mocha.prototype.ui = function (name) { } this._ui = this._ui(this.suite); - this.suite.on('pre-require', function (context) { + 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; @@ -231,10 +241,10 @@ Mocha.prototype.ui = function (name) { * * @api private */ -Mocha.prototype.loadFiles = function (fn) { +Mocha.prototype.loadFiles = function(fn) { var self = this; var suite = this.suite; - this.files.forEach(function (file) { + this.files.forEach(function(file) { file = path.resolve(file); suite.emit('pre-require', global, file, self); suite.emit('require', require(file), file, self); @@ -248,14 +258,14 @@ Mocha.prototype.loadFiles = function (fn) { * * @api private */ -Mocha.prototype._growl = function (runner, reporter) { +Mocha.prototype._growl = function(runner, reporter) { var notify = require('growl'); - runner.on('end', function () { + 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') }); + notify(msg, {name: 'mocha', title: 'Failed', image: image('error')}); } else { notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { name: 'mocha', @@ -274,7 +284,7 @@ Mocha.prototype._growl = function (runner, reporter) { * @param str * @returns {Mocha} */ -Mocha.prototype.fgrep = function (str) { +Mocha.prototype.fgrep = function(str) { return this.grep(new RegExp(escapeRe(str))); }; @@ -288,7 +298,7 @@ Mocha.prototype.fgrep = function (str) { * @param {RegExp|string} re * @return {Mocha} */ -Mocha.prototype.grep = function (re) { +Mocha.prototype.grep = function(re) { if (utils.isString(re)) { // extract args if it's regex-like, i.e: [string, pattern, flag] var arg = re.match(/^\/(.*)\/(g|i|)$|.*/); @@ -305,7 +315,7 @@ Mocha.prototype.grep = function (re) { * @return {Mocha} * @api public */ -Mocha.prototype.invert = function () { +Mocha.prototype.invert = function() { this.options.invert = true; return this; }; @@ -320,7 +330,7 @@ Mocha.prototype.invert = function () { * @param {boolean} ignore * @return {Mocha} */ -Mocha.prototype.ignoreLeaks = function (ignore) { +Mocha.prototype.ignoreLeaks = function(ignore) { this.options.ignoreLeaks = Boolean(ignore); return this; }; @@ -332,7 +342,7 @@ Mocha.prototype.ignoreLeaks = function (ignore) { * @api public * @public */ -Mocha.prototype.checkLeaks = function () { +Mocha.prototype.checkLeaks = function() { this.options.ignoreLeaks = false; return this; }; @@ -344,7 +354,7 @@ Mocha.prototype.checkLeaks = function () { * @api public * @public */ -Mocha.prototype.fullTrace = function () { +Mocha.prototype.fullTrace = function() { this.options.fullStackTrace = true; return this; }; @@ -356,7 +366,7 @@ Mocha.prototype.fullTrace = function () { * @api public * @public */ -Mocha.prototype.growl = function () { +Mocha.prototype.growl = function() { this.options.growl = true; return this; }; @@ -371,7 +381,7 @@ Mocha.prototype.growl = function () { * @param {Array|string} globals * @return {Mocha} */ -Mocha.prototype.globals = function (globals) { +Mocha.prototype.globals = function(globals) { this.options.globals = (this.options.globals || []).concat(globals); return this; }; @@ -386,7 +396,7 @@ Mocha.prototype.globals = function (globals) { * @param {boolean} colors * @return {Mocha} */ -Mocha.prototype.useColors = function (colors) { +Mocha.prototype.useColors = function(colors) { if (colors !== undefined) { this.options.useColors = colors; } @@ -403,7 +413,7 @@ Mocha.prototype.useColors = function (colors) { * @param {boolean} inlineDiffs * @return {Mocha} */ -Mocha.prototype.useInlineDiffs = function (inlineDiffs) { +Mocha.prototype.useInlineDiffs = function(inlineDiffs) { this.options.useInlineDiffs = inlineDiffs !== undefined && inlineDiffs; return this; }; @@ -418,7 +428,7 @@ Mocha.prototype.useInlineDiffs = function (inlineDiffs) { * @param {boolean} hideDiff * @return {Mocha} */ -Mocha.prototype.hideDiff = function (hideDiff) { +Mocha.prototype.hideDiff = function(hideDiff) { this.options.hideDiff = hideDiff !== undefined && hideDiff; return this; }; @@ -433,7 +443,7 @@ Mocha.prototype.hideDiff = function (hideDiff) { * @param {number} timeout * @return {Mocha} */ -Mocha.prototype.timeout = function (timeout) { +Mocha.prototype.timeout = function(timeout) { this.suite.timeout(timeout); return this; }; @@ -446,7 +456,7 @@ Mocha.prototype.timeout = function (timeout) { * @api public * @public */ -Mocha.prototype.retries = function (n) { +Mocha.prototype.retries = function(n) { this.suite.retries(n); return this; }; @@ -461,7 +471,7 @@ Mocha.prototype.retries = function (n) { * @param {number} slow * @return {Mocha} */ -Mocha.prototype.slow = function (slow) { +Mocha.prototype.slow = function(slow) { this.suite.slow(slow); return this; }; @@ -476,8 +486,10 @@ Mocha.prototype.slow = function (slow) { * @param {boolean} enabled * @return {Mocha} */ -Mocha.prototype.enableTimeouts = function (enabled) { - this.suite.enableTimeouts(arguments.length && enabled !== undefined ? enabled : true); +Mocha.prototype.enableTimeouts = function(enabled) { + this.suite.enableTimeouts( + arguments.length && enabled !== undefined ? enabled : true + ); return this; }; @@ -488,7 +500,7 @@ Mocha.prototype.enableTimeouts = function (enabled) { * @api public * @public */ -Mocha.prototype.asyncOnly = function () { +Mocha.prototype.asyncOnly = function() { this.options.asyncOnly = true; return this; }; @@ -499,7 +511,7 @@ Mocha.prototype.asyncOnly = function () { * @api public * @public */ -Mocha.prototype.noHighlighting = function () { +Mocha.prototype.noHighlighting = function() { this.options.noHighlighting = true; return this; }; @@ -511,7 +523,7 @@ Mocha.prototype.noHighlighting = function () { * @api public * @public */ -Mocha.prototype.allowUncaught = function () { +Mocha.prototype.allowUncaught = function() { this.options.allowUncaught = true; return this; }; @@ -520,7 +532,7 @@ Mocha.prototype.allowUncaught = function () { * Delay root suite execution. * @returns {Mocha} */ -Mocha.prototype.delay = function delay () { +Mocha.prototype.delay = function delay() { this.options.delay = true; return this; }; @@ -529,7 +541,7 @@ Mocha.prototype.delay = function delay () { * Tests marked only fail the suite * @returns {Mocha} */ -Mocha.prototype.forbidOnly = function () { +Mocha.prototype.forbidOnly = function() { this.options.forbidOnly = true; return this; }; @@ -538,7 +550,7 @@ Mocha.prototype.forbidOnly = function () { * Pending tests and tests marked skip fail the suite * @returns {Mocha} */ -Mocha.prototype.forbidPending = function () { +Mocha.prototype.forbidPending = function() { this.options.forbidPending = true; return this; }; @@ -559,7 +571,7 @@ Mocha.prototype.forbidPending = function () { * @param {Function} fn * @return {Runner} */ -Mocha.prototype.run = function (fn) { +Mocha.prototype.run = function(fn) { if (this.files.length) { this.loadFiles(); } @@ -589,7 +601,7 @@ Mocha.prototype.run = function (fn) { exports.reporters.Base.inlineDiffs = options.useInlineDiffs; exports.reporters.Base.hideDiff = options.hideDiff; - function done (failures) { + function done(failures) { if (reporter.done) { reporter.done(failures, fn); } else { diff --git a/lib/ms.js b/lib/ms.js index c906b15f9b..91c55afaa4 100644 --- a/lib/ms.js +++ b/lib/ms.js @@ -21,7 +21,7 @@ var y = d * 365.25; * @param {string|number} val * @return {string|number} */ -module.exports = function (val) { +module.exports = function(val) { if (typeof val === 'string') { return parse(val); } @@ -35,8 +35,10 @@ module.exports = function (val) { * @param {string} str * @return {number} */ -function parse (str) { - var match = (/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i).exec(str); +function parse(str) { + var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec( + str + ); if (!match) { return; } @@ -66,7 +68,7 @@ function parse (str) { case 'ms': return n; default: - // No default case + // No default case } } @@ -77,7 +79,7 @@ function parse (str) { * @param {number} ms * @return {string} */ -function format (ms) { +function format(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } diff --git a/lib/pending.js b/lib/pending.js index ecbcda33e9..bb9a505337 100644 --- a/lib/pending.js +++ b/lib/pending.js @@ -7,6 +7,6 @@ module.exports = Pending; * * @param {string} message */ -function Pending (message) { +function Pending(message) { this.message = message; } diff --git a/lib/reporters/base.js b/lib/reporters/base.js index fdab06e7d7..b3b49873b7 100644 --- a/lib/reporters/base.js +++ b/lib/reporters/base.js @@ -41,7 +41,8 @@ var isatty = tty.isatty(1) && tty.isatty(2); * Enable coloring by default, except in the browser interface. */ -exports.useColors = !process.browser && (supportsColor || (process.env.MOCHA_COLORS !== undefined)); +exports.useColors = + !process.browser && (supportsColor || process.env.MOCHA_COLORS !== undefined); /** * Inline diffs instead of +/- @@ -105,12 +106,12 @@ if (process.platform === 'win32') { * @return {string} * @api private */ -var color = exports.color = function (type, str) { +var color = (exports.color = function(type, str) { if (!exports.useColors) { return String(str); } return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; -}; +}); /** * Expose term window size, with some defaults for when stderr is not a tty. @@ -131,23 +132,23 @@ if (isatty) { */ exports.cursor = { - hide: function () { + hide: function() { isatty && process.stdout.write('\u001b[?25l'); }, - show: function () { + show: function() { isatty && process.stdout.write('\u001b[?25h'); }, - deleteLine: function () { + deleteLine: function() { isatty && process.stdout.write('\u001b[2K'); }, - beginningOfLine: function () { + beginningOfLine: function() { isatty && process.stdout.write('\u001b[0G'); }, - CR: function () { + CR: function() { if (isatty) { exports.cursor.deleteLine(); exports.cursor.beginningOfLine(); @@ -157,11 +158,16 @@ exports.cursor = { } }; -function showDiff (err) { - return err && err.showDiff !== false && sameType(err.actual, err.expected) && err.expected !== undefined; +function showDiff(err) { + return ( + err && + err.showDiff !== false && + sameType(err.actual, err.expected) && + err.expected !== undefined + ); } -function stringifyDiffObjs (err) { +function stringifyDiffObjs(err) { if (!utils.isString(err.actual) || !utils.isString(err.expected)) { err.actual = utils.stringify(err.actual); err.expected = utils.stringify(err.expected); @@ -178,11 +184,11 @@ function stringifyDiffObjs (err) { * @param {string} expected * @return {string} Diff */ -var generateDiff = exports.generateDiff = function (actual, expected) { +var generateDiff = (exports.generateDiff = function(actual, expected) { return exports.inlineDiffs ? inlineDiff(actual, expected) : unifiedDiff(actual, expected); -}; +}); /** * Output the given `failures` as a list. @@ -194,11 +200,12 @@ var generateDiff = exports.generateDiff = function (actual, expected) { * @api public */ -exports.list = function (failures) { +exports.list = function(failures) { console.log(); - failures.forEach(function (test, i) { + failures.forEach(function(test, i) { // format - var fmt = color('error title', ' %s) %s:\n') + + var fmt = + color('error title', ' %s) %s:\n') + color('error message', ' %s') + color('error stack', '\n%s\n'); @@ -232,7 +239,8 @@ exports.list = function (failures) { // explicitly show diff if (!exports.hideDiff && showDiff(err)) { stringifyDiffObjs(err); - fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); + 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); @@ -244,7 +252,7 @@ exports.list = function (failures) { // indented test title var testTitle = ''; - test.titlePath().forEach(function (str, index) { + test.titlePath().forEach(function(str, index) { if (index !== 0) { testTitle += '\n '; } @@ -254,7 +262,7 @@ exports.list = function (failures) { testTitle += str; }); - console.log(fmt, (i + 1), testTitle, msg, stack); + console.log(fmt, i + 1, testTitle, msg, stack); }); }; @@ -273,9 +281,15 @@ exports.list = function (failures) { * @api public */ -function Base (runner) { - var stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }; - var failures = this.failures = []; +function Base(runner) { + var stats = (this.stats = { + suites: 0, + tests: 0, + passes: 0, + pending: 0, + failures: 0 + }); + var failures = (this.failures = []); if (!runner) { return; @@ -284,21 +298,21 @@ function Base (runner) { runner.stats = stats; - runner.on('start', function () { + runner.on('start', function() { stats.start = new Date(); }); - runner.on('suite', function (suite) { + runner.on('suite', function(suite) { stats.suites = stats.suites || 0; suite.root || stats.suites++; }); - runner.on('test end', function () { + runner.on('test end', function() { stats.tests = stats.tests || 0; stats.tests++; }); - runner.on('pass', function (test) { + runner.on('pass', function(test) { stats.passes = stats.passes || 0; if (test.duration > test.slow()) { @@ -312,7 +326,7 @@ function Base (runner) { stats.passes++; }); - runner.on('fail', function (test, err) { + runner.on('fail', function(test, err) { stats.failures = stats.failures || 0; stats.failures++; if (showDiff(err)) { @@ -322,12 +336,12 @@ function Base (runner) { failures.push(test); }); - runner.once('end', function () { + runner.once('end', function() { stats.end = new Date(); stats.duration = stats.end - stats.start; }); - runner.on('pending', function () { + runner.on('pending', function() { stats.pending++; }); } @@ -340,25 +354,23 @@ function Base (runner) { * @public * @api public */ -Base.prototype.epilogue = function () { +Base.prototype.epilogue = function() { var stats = this.stats; var fmt; console.log(); // passes - fmt = color('bright pass', ' ') + + 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'); + fmt = color('pending', ' ') + color('pending', ' %d pending'); console.log(fmt, stats.pending); } @@ -384,7 +396,7 @@ Base.prototype.epilogue = function () { * @param {string} len * @return {string} */ -function pad (str, len) { +function pad(str, len) { str = String(str); return Array(len - str.length + 1).join(' ') + str; } @@ -397,20 +409,23 @@ function pad (str, len) { * @param {String} expected * @return {string} Diff */ -function inlineDiff (actual, expected) { +function inlineDiff(actual, expected) { var msg = errorDiff(actual, expected); // 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'); + msg = lines + .map(function(str, i) { + return pad(++i, width) + ' |' + ' ' + str; + }) + .join('\n'); } // legend - msg = '\n' + + msg = + '\n' + color('diff removed', 'actual') + ' ' + color('diff added', 'expected') + @@ -431,9 +446,9 @@ function inlineDiff (actual, expected) { * @param {String} expected * @return {string} The diff. */ -function unifiedDiff (actual, expected) { +function unifiedDiff(actual, expected) { var indent = ' '; - function cleanUp (line) { + function cleanUp(line) { if (line[0] === '+') { return indent + colorLines('diff added', line); } @@ -448,16 +463,22 @@ function unifiedDiff (actual, expected) { } return indent + line; } - function notBlank (line) { + function notBlank(line) { return typeof line !== 'undefined' && line !== null; } var msg = diff.createPatch('string', actual, expected); var lines = msg.split('\n').splice(5); - return '\n ' + - colorLines('diff added', '+ expected') + ' ' + + return ( + '\n ' + + colorLines('diff added', '+ expected') + + ' ' + colorLines('diff removed', '- actual') + '\n\n' + - lines.map(cleanUp).filter(notBlank).join('\n'); + lines + .map(cleanUp) + .filter(notBlank) + .join('\n') + ); } /** @@ -468,16 +489,19 @@ function unifiedDiff (actual, expected) { * @param {String} expected * @return {string} the diff */ -function errorDiff (actual, expected) { - return diff.diffWordsWithSpace(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(actual, expected) { + return diff + .diffWordsWithSpace(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(''); } /** @@ -488,10 +512,13 @@ function errorDiff (actual, expected) { * @param {string} str * @return {string} */ -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'); } /** @@ -507,6 +534,6 @@ var objToString = Object.prototype.toString; * @param {Object} b * @return {boolean} */ -function sameType (a, b) { +function sameType(a, b) { return objToString.call(a) === objToString.call(b); } diff --git a/lib/reporters/doc.js b/lib/reporters/doc.js index 844ac5fd24..5cb0bda8fc 100644 --- a/lib/reporters/doc.js +++ b/lib/reporters/doc.js @@ -25,16 +25,16 @@ exports = module.exports = Doc; * @param {Runner} runner * @api public */ -function Doc (runner) { +function Doc(runner) { Base.call(this, runner); var indents = 2; - function indent () { + function indent() { return Array(indents).join(' '); } - runner.on('suite', function (suite) { + runner.on('suite', function(suite) { if (suite.root) { return; } @@ -45,7 +45,7 @@ function Doc (runner) { console.log('%s
', indent()); }); - runner.on('suite end', function (suite) { + runner.on('suite end', function(suite) { if (suite.root) { return; } @@ -55,16 +55,24 @@ function Doc (runner) { --indents; }); - runner.on('pass', function (test) { + runner.on('pass', function(test) { console.log('%s
%s
', indent(), utils.escape(test.title)); var code = utils.escape(utils.clean(test.body)); console.log('%s
%s
', indent(), code); }); - runner.on('fail', function (test, err) { - console.log('%s
%s
', indent(), utils.escape(test.title)); + runner.on('fail', function(test, err) { + console.log( + '%s
%s
', + indent(), + utils.escape(test.title) + ); var code = utils.escape(utils.clean(test.body)); - console.log('%s
%s
', indent(), code); + console.log( + '%s
%s
', + indent(), + code + ); console.log('%s
%s
', indent(), utils.escape(err)); }); } diff --git a/lib/reporters/dot.js b/lib/reporters/dot.js index d83c026777..22320e31c3 100644 --- a/lib/reporters/dot.js +++ b/lib/reporters/dot.js @@ -26,25 +26,25 @@ exports = module.exports = Dot; * @api public * @param {Runner} runner */ -function Dot (runner) { +function Dot(runner) { Base.call(this, runner); var self = this; - var width = Base.window.width * 0.75 | 0; + var width = (Base.window.width * 0.75) | 0; var n = -1; - runner.on('start', function () { + runner.on('start', function() { process.stdout.write('\n'); }); - runner.on('pending', function () { + runner.on('pending', function() { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(color('pending', Base.symbols.comma)); }); - runner.on('pass', function (test) { + runner.on('pass', function(test) { if (++n % width === 0) { process.stdout.write('\n '); } @@ -55,14 +55,14 @@ function Dot (runner) { } }); - runner.on('fail', function () { + runner.on('fail', function() { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(color('fail', Base.symbols.bang)); }); - runner.once('end', function () { + runner.once('end', function() { console.log(); self.epilogue(); }); diff --git a/lib/reporters/html.js b/lib/reporters/html.js index 2a8034da98..85a5b1b19f 100644 --- a/lib/reporters/html.js +++ b/lib/reporters/html.js @@ -36,7 +36,8 @@ exports = module.exports = HTML; * Stats template. */ -var statsTemplate = '
    ' + +var statsTemplate = + '
      ' + '
    • ' + '
    • passes: 0
    • ' + '
    • failures: 0
    • ' + @@ -55,7 +56,7 @@ var playIcon = '‣'; * @api public * @param {Runner} runner */ -function HTML (runner) { +function HTML(runner) { Base.call(this, runner); var self = this; @@ -90,10 +91,10 @@ function HTML (runner) { } // pass toggle - on(passesLink, 'click', function (evt) { + on(passesLink, 'click', function(evt) { evt.preventDefault(); unhide(); - var name = (/pass/).test(report.className) ? '' : ' pass'; + var name = /pass/.test(report.className) ? '' : ' pass'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) { hideSuitesWithout('test pass'); @@ -101,10 +102,10 @@ function HTML (runner) { }); // failure toggle - on(failuresLink, 'click', function (evt) { + on(failuresLink, 'click', function(evt) { evt.preventDefault(); unhide(); - var name = (/fail/).test(report.className) ? '' : ' fail'; + var name = /fail/.test(report.className) ? '' : ' fail'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) { hideSuitesWithout('test fail'); @@ -118,14 +119,18 @@ function HTML (runner) { progress.size(40); } - runner.on('suite', function (suite) { + runner.on('suite', function(suite) { if (suite.root) { return; } // suite var url = self.suiteURL(suite); - var el = fragment('
    • %s

    • ', url, escape(suite.title)); + var el = fragment( + '
    • %s

    • ', + url, + escape(suite.title) + ); // container stack[0].appendChild(el); @@ -133,7 +138,7 @@ function HTML (runner) { el.appendChild(stack[0]); }); - runner.on('suite end', function (suite) { + runner.on('suite end', function(suite) { if (suite.root) { updateStats(); return; @@ -141,19 +146,27 @@ function HTML (runner) { stack.shift(); }); - runner.on('pass', function (test) { + runner.on('pass', function(test) { var url = self.testURL(test); - var markup = '
    • %e%ems ' + - '' + playIcon + '

    • '; + var markup = + '
    • %e%ems ' + + '' + + playIcon + + '

    • '; var el = fragment(markup, test.speed, test.title, test.duration, url); self.addCodeToggle(el, test.body); appendToStack(el); updateStats(); }); - runner.on('fail', function (test) { - var el = fragment('
    • %e ' + playIcon + '

    • ', - test.title, self.testURL(test)); + runner.on('fail', function(test) { + var el = fragment( + '
    • %e ' + + playIcon + + '

    • ', + test.title, + self.testURL(test) + ); var stackString; // Note: Includes leading newline var message = test.err.toString(); @@ -168,7 +181,9 @@ function HTML (runner) { if (indexOfMessage === -1) { stackString = test.err.stack; } else { - stackString = test.err.stack.substr(test.err.message.length + indexOfMessage); + stackString = test.err.stack.substr( + test.err.message.length + indexOfMessage + ); } } else if (test.err.sourceURL && test.err.line !== undefined) { // Safari doesn't give you a stack. Let's at least provide a source line. @@ -178,12 +193,21 @@ function HTML (runner) { stackString = stackString || ''; if (test.err.htmlMessage && stackString) { - el.appendChild(fragment('
      %s\n
      %e
      ', - test.err.htmlMessage, stackString)); + el.appendChild( + fragment( + '
      %s\n
      %e
      ', + test.err.htmlMessage, + stackString + ) + ); } else if (test.err.htmlMessage) { - el.appendChild(fragment('
      %s
      ', test.err.htmlMessage)); + el.appendChild( + fragment('
      %s
      ', test.err.htmlMessage) + ); } else { - el.appendChild(fragment('
      %e%e
      ', message, stackString)); + el.appendChild( + fragment('
      %e%e
      ', message, stackString) + ); } self.addCodeToggle(el, test.body); @@ -191,22 +215,25 @@ function HTML (runner) { updateStats(); }); - runner.on('pending', function (test) { - var el = fragment('
    • %e

    • ', test.title); + runner.on('pending', function(test) { + var el = fragment( + '
    • %e

    • ', + test.title + ); appendToStack(el); updateStats(); }); - function appendToStack (el) { + function appendToStack(el) { // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. if (stack[0]) { stack[0].appendChild(el); } } - function updateStats () { + function updateStats() { // TODO: add to stats - var percent = stats.tests / runner.total * 100 | 0; + var percent = (stats.tests / runner.total * 100) | 0; if (progress) { progress.update(percent).draw(ctx); } @@ -225,7 +252,7 @@ function HTML (runner) { * @param {string} s * @return {string} A new URL. */ -function makeUrl (s) { +function makeUrl(s) { var search = window.location.search; // Remove previous grep query parameter if present @@ -233,7 +260,12 @@ function makeUrl (s) { search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?'); } - return window.location.pathname + (search ? search + '&' : '?') + 'grep=' + encodeURIComponent(escapeRe(s)); + return ( + window.location.pathname + + (search ? search + '&' : '?') + + 'grep=' + + encodeURIComponent(escapeRe(s)) + ); } /** @@ -241,7 +273,7 @@ function makeUrl (s) { * * @param {Object} [suite] */ -HTML.prototype.suiteURL = function (suite) { +HTML.prototype.suiteURL = function(suite) { return makeUrl(suite.fullTitle()); }; @@ -250,7 +282,7 @@ HTML.prototype.suiteURL = function (suite) { * * @param {Object} [test] */ -HTML.prototype.testURL = function (test) { +HTML.prototype.testURL = function(test) { return makeUrl(test.fullTitle()); }; @@ -260,10 +292,10 @@ HTML.prototype.testURL = function (test) { * @param {HTMLLIElement} el * @param {string} contents */ -HTML.prototype.addCodeToggle = function (el, contents) { +HTML.prototype.addCodeToggle = function(el, contents) { var h2 = el.getElementsByTagName('h2')[0]; - on(h2, 'click', function () { + on(h2, 'click', function() { pre.style.display = pre.style.display === 'none' ? 'block' : 'none'; }); @@ -277,7 +309,7 @@ HTML.prototype.addCodeToggle = function (el, contents) { * * @param {string} msg */ -function error (msg) { +function error(msg) { document.body.appendChild(fragment('
      %s
      ', msg)); } @@ -286,15 +318,17 @@ function error (msg) { * * @param {string} html */ -function fragment (html) { +function fragment(html) { var args = arguments; var div = document.createElement('div'); var i = 1; - div.innerHTML = html.replace(/%([se])/g, function (_, type) { + div.innerHTML = html.replace(/%([se])/g, function(_, type) { switch (type) { - case 's': return String(args[i++]); - case 'e': return escape(args[i++]); + case 's': + return String(args[i++]); + case 'e': + return escape(args[i++]); // no default } }); @@ -308,7 +342,7 @@ function fragment (html) { * * @param {text} classname */ -function hideSuitesWithout (classname) { +function hideSuitesWithout(classname) { var suites = document.getElementsByClassName('suite'); for (var i = 0; i < suites.length; i++) { var els = suites[i].getElementsByClassName(classname); @@ -321,7 +355,7 @@ function hideSuitesWithout (classname) { /** * Unhide .hidden suites. */ -function unhide () { +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'); @@ -334,7 +368,7 @@ function unhide () { * @param {HTMLElement} el * @param {string} contents */ -function text (el, contents) { +function text(el, contents) { if (el.textContent) { el.textContent = contents; } else { @@ -345,7 +379,7 @@ function text (el, contents) { /** * Listen on `event` with callback `fn`. */ -function on (el, event, fn) { +function on(el, event, fn) { if (el.addEventListener) { el.addEventListener(event, fn, false); } else { diff --git a/lib/reporters/json-stream.js b/lib/reporters/json-stream.js index 884cc8ffec..0edd0cbf88 100644 --- a/lib/reporters/json-stream.js +++ b/lib/reporters/json-stream.js @@ -25,28 +25,28 @@ exports = module.exports = List; * @api public * @param {Runner} runner */ -function List (runner) { +function List(runner) { Base.call(this, runner); var self = this; 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) { + runner.on('pass', function(test) { console.log(JSON.stringify(['pass', clean(test)])); }); - runner.on('fail', function (test, err) { + runner.on('fail', function(test, err) { test = clean(test); test.err = err.message; test.stack = err.stack || null; console.log(JSON.stringify(['fail', test])); }); - runner.once('end', function () { + runner.once('end', function() { process.stdout.write(JSON.stringify(['end', self.stats])); }); } @@ -59,7 +59,7 @@ function List (runner) { * @param {Object} test * @return {Object} */ -function clean (test) { +function clean(test) { return { title: test.title, fullTitle: test.fullTitle(), diff --git a/lib/reporters/json.js b/lib/reporters/json.js index d70f9a5591..046e4ba4a5 100644 --- a/lib/reporters/json.js +++ b/lib/reporters/json.js @@ -24,7 +24,7 @@ exports = module.exports = JSONReporter; * @api public * @param {Runner} runner */ -function JSONReporter (runner) { +function JSONReporter(runner) { Base.call(this, runner); var self = this; @@ -33,23 +33,23 @@ function JSONReporter (runner) { var failures = []; var passes = []; - runner.on('test end', function (test) { + runner.on('test end', function(test) { tests.push(test); }); - runner.on('pass', function (test) { + runner.on('pass', function(test) { passes.push(test); }); - runner.on('fail', function (test) { + runner.on('fail', function(test) { failures.push(test); }); - runner.on('pending', function (test) { + runner.on('pending', function(test) { pending.push(test); }); - runner.once('end', function () { + runner.once('end', function() { var obj = { stats: self.stats, tests: tests.map(clean), @@ -72,7 +72,7 @@ function JSONReporter (runner) { * @param {Object} test * @return {Object} */ -function clean (test) { +function clean(test) { var err = test.err || {}; if (err instanceof Error) { err = errorJSON(err); @@ -94,19 +94,21 @@ function clean (test) { * @param {Object} obj * @return {Object} */ -function cleanCycles (obj) { +function cleanCycles(obj) { var cache = []; - return JSON.parse(JSON.stringify(obj, function (key, value) { - if (typeof value === 'object' && value !== null) { - if (cache.indexOf(value) !== -1) { - // Instead of going in a circle, we'll print [object Object] - return '' + value; + return JSON.parse( + JSON.stringify(obj, function(key, value) { + if (typeof value === 'object' && value !== null) { + if (cache.indexOf(value) !== -1) { + // Instead of going in a circle, we'll print [object Object] + return '' + value; + } + cache.push(value); } - cache.push(value); - } - return value; - })); + return value; + }) + ); } /** @@ -116,9 +118,9 @@ function cleanCycles (obj) { * @param {Error} err * @return {Object} */ -function errorJSON (err) { +function errorJSON(err) { var res = {}; - Object.getOwnPropertyNames(err).forEach(function (key) { + Object.getOwnPropertyNames(err).forEach(function(key) { res[key] = err[key]; }, err); return res; diff --git a/lib/reporters/landing.js b/lib/reporters/landing.js index c1f67b21ca..b0a9fb23be 100644 --- a/lib/reporters/landing.js +++ b/lib/reporters/landing.js @@ -45,30 +45,30 @@ Base.colors.runway = 90; * @api public * @param {Runner} runner */ -function Landing (runner) { +function Landing(runner) { Base.call(this, runner); var self = this; - var width = Base.window.width * 0.75 | 0; + 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 () { + function runway() { var buf = Array(width).join('-'); return ' ' + color('runway', buf); } - runner.on('start', function () { + runner.on('start', function() { stream.write('\n\n\n '); cursor.hide(); }); - runner.on('test end', function (test) { + runner.on('test end', function(test) { // check if the plane crashed - var col = crashed === -1 ? width * ++n / total | 0 : crashed; + var col = crashed === -1 ? (width * ++n / total) | 0 : crashed; // show the crash if (test.state === 'failed') { @@ -87,7 +87,7 @@ function Landing (runner) { stream.write('\u001b[0m'); }); - runner.once('end', function () { + runner.once('end', function() { cursor.show(); console.log(); self.epilogue(); diff --git a/lib/reporters/list.js b/lib/reporters/list.js index d98f4ff333..29ce74ab79 100644 --- a/lib/reporters/list.js +++ b/lib/reporters/list.js @@ -27,35 +27,35 @@ exports = module.exports = List; * @api public * @param {Runner} runner */ -function List (runner) { +function List(runner) { Base.call(this, runner); var self = this; var n = 0; - runner.on('start', function () { + runner.on('start', function() { console.log(); }); - runner.on('test', function (test) { + runner.on('test', function(test) { process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); }); - runner.on('pending', function (test) { - var fmt = color('checkmark', ' -') + - color('pending', ' %s'); + 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.ok) + + runner.on('pass', function(test) { + var fmt = + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s: ') + color(test.speed, '%dms'); cursor.CR(); console.log(fmt, test.fullTitle(), test.duration); }); - runner.on('fail', function (test) { + runner.on('fail', function(test) { cursor.CR(); console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); }); diff --git a/lib/reporters/markdown.js b/lib/reporters/markdown.js index 43f1468d2c..ff75ee4d67 100644 --- a/lib/reporters/markdown.js +++ b/lib/reporters/markdown.js @@ -31,29 +31,29 @@ exports = module.exports = Markdown; * @api public * @param {Runner} runner */ -function Markdown (runner) { +function Markdown(runner) { Base.call(this, runner); var level = 0; var buf = ''; - function title (str) { + function title(str) { return Array(level).join('#') + ' ' + str; } - function mapTOC (suite, obj) { + function mapTOC(suite, obj) { var ret = obj; var key = SUITE_PREFIX + suite.title; - obj = obj[key] = obj[key] || { suite: suite }; - suite.suites.forEach(function (suite) { + obj = obj[key] = obj[key] || {suite: suite}; + suite.suites.forEach(function(suite) { mapTOC(suite, obj); }); return ret; } - function stringifyTOC (obj, level) { + function stringifyTOC(obj, level) { ++level; var buf = ''; var link; @@ -71,25 +71,25 @@ function Markdown (runner) { return buf; } - function generateTOC (suite) { + function generateTOC(suite) { var obj = mapTOC(suite, {}); return stringifyTOC(obj, 0); } generateTOC(runner.suite); - runner.on('suite', function (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 () { + runner.on('suite end', function() { --level; }); - runner.on('pass', function (test) { + runner.on('pass', function(test) { var code = utils.clean(test.body); buf += test.title + '.\n'; buf += '\n```js\n'; @@ -97,7 +97,7 @@ function Markdown (runner) { buf += '```\n\n'; }); - runner.once('end', function () { + runner.once('end', function() { process.stdout.write('# TOC\n'); process.stdout.write(generateTOC(runner.suite)); process.stdout.write(buf); diff --git a/lib/reporters/min.js b/lib/reporters/min.js index 39e04c6210..2a91a3c1e2 100644 --- a/lib/reporters/min.js +++ b/lib/reporters/min.js @@ -25,10 +25,10 @@ exports = module.exports = Min; * @api public * @param {Runner} runner */ -function Min (runner) { +function Min(runner) { Base.call(this, runner); - runner.on('start', function () { + runner.on('start', function() { // clear screen process.stdout.write('\u001b[2J'); // set cursor position diff --git a/lib/reporters/nyan.js b/lib/reporters/nyan.js index 9beb3969bb..164a3fadc4 100644 --- a/lib/reporters/nyan.js +++ b/lib/reporters/nyan.js @@ -26,12 +26,12 @@ exports = module.exports = NyanCat; * @extends Mocha.reporters.Base */ -function NyanCat (runner) { +function NyanCat(runner) { Base.call(this, runner); var self = this; - var width = Base.window.width * 0.75 | 0; - var nyanCatWidth = this.nyanCatWidth = 11; + var width = (Base.window.width * 0.75) | 0; + var nyanCatWidth = (this.nyanCatWidth = 11); this.colorIndex = 0; this.numberOfLines = 4; @@ -39,26 +39,26 @@ function NyanCat (runner) { this.scoreboardWidth = 5; this.tick = 0; this.trajectories = [[], [], [], []]; - this.trajectoryWidthMax = (width - nyanCatWidth); + this.trajectoryWidthMax = width - nyanCatWidth; - runner.on('start', function () { + runner.on('start', function() { Base.cursor.hide(); self.draw(); }); - runner.on('pending', function () { + runner.on('pending', function() { self.draw(); }); - runner.on('pass', function () { + runner.on('pass', function() { self.draw(); }); - runner.on('fail', function () { + runner.on('fail', function() { self.draw(); }); - runner.once('end', function () { + runner.once('end', function() { Base.cursor.show(); for (var i = 0; i < self.numberOfLines; i++) { write('\n'); @@ -78,7 +78,7 @@ inherits(NyanCat, Base); * @api private */ -NyanCat.prototype.draw = function () { +NyanCat.prototype.draw = function() { this.appendRainbow(); this.drawScoreboard(); this.drawRainbow(); @@ -93,10 +93,10 @@ NyanCat.prototype.draw = function () { * @api private */ -NyanCat.prototype.drawScoreboard = function () { +NyanCat.prototype.drawScoreboard = function() { var stats = this.stats; - function draw (type, n) { + function draw(type, n) { write(' '); write(Base.color(type, n)); write('\n'); @@ -116,7 +116,7 @@ NyanCat.prototype.drawScoreboard = function () { * @api private */ -NyanCat.prototype.appendRainbow = function () { +NyanCat.prototype.appendRainbow = function() { var segment = this.tick ? '_' : '-'; var rainbowified = this.rainbowify(segment); @@ -135,10 +135,10 @@ NyanCat.prototype.appendRainbow = function () { * @api private */ -NyanCat.prototype.drawRainbow = function () { +NyanCat.prototype.drawRainbow = function() { var self = this; - this.trajectories.forEach(function (line) { + this.trajectories.forEach(function(line) { write('\u001b[' + self.scoreboardWidth + 'C'); write(line.join('')); write('\n'); @@ -152,7 +152,7 @@ NyanCat.prototype.drawRainbow = function () { * * @api private */ -NyanCat.prototype.drawNyanCat = function () { +NyanCat.prototype.drawNyanCat = function() { var self = this; var startWidth = this.scoreboardWidth + this.trajectories[0].length; var dist = '\u001b[' + startWidth + 'C'; @@ -188,7 +188,7 @@ NyanCat.prototype.drawNyanCat = function () { * @return {string} */ -NyanCat.prototype.face = function () { +NyanCat.prototype.face = function() { var stats = this.stats; if (stats.failures) { return '( x .x)'; @@ -207,7 +207,7 @@ NyanCat.prototype.face = function () { * @param {number} n */ -NyanCat.prototype.cursorUp = function (n) { +NyanCat.prototype.cursorUp = function(n) { write('\u001b[' + n + 'A'); }; @@ -218,7 +218,7 @@ NyanCat.prototype.cursorUp = function (n) { * @param {number} n */ -NyanCat.prototype.cursorDown = function (n) { +NyanCat.prototype.cursorDown = function(n) { write('\u001b[' + n + 'B'); }; @@ -228,12 +228,12 @@ NyanCat.prototype.cursorDown = function (n) { * @api private * @return {Array} */ -NyanCat.prototype.generateColors = function () { +NyanCat.prototype.generateColors = function() { var colors = []; - for (var i = 0; i < (6 * 7); i++) { + for (var i = 0; i < 6 * 7; i++) { var pi3 = Math.floor(Math.PI / 3); - var n = (i * (1.0 / 6)); + 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); @@ -250,7 +250,7 @@ NyanCat.prototype.generateColors = function () { * @param {string} str * @return {string} */ -NyanCat.prototype.rainbowify = function (str) { +NyanCat.prototype.rainbowify = function(str) { if (!Base.useColors) { return str; } @@ -264,6 +264,6 @@ NyanCat.prototype.rainbowify = function (str) { * * @param {string} string A message to write to stdout. */ -function write (string) { +function write(string) { process.stdout.write(string); } diff --git a/lib/reporters/progress.js b/lib/reporters/progress.js index ad592c4fd3..042fc1b91b 100644 --- a/lib/reporters/progress.js +++ b/lib/reporters/progress.js @@ -34,11 +34,11 @@ Base.colors.progress = 90; * @param {Runner} runner * @param {Object} options */ -function Progress (runner, options) { +function Progress(runner, options) { Base.call(this, runner); var self = this; - var width = Base.window.width * 0.50 | 0; + var width = (Base.window.width * 0.5) | 0; var total = runner.total; var complete = 0; var lastN = -1; @@ -54,17 +54,17 @@ function Progress (runner, options) { options.verbose = reporterOptions.verbose || false; // tests started - runner.on('start', function () { + runner.on('start', function() { console.log(); cursor.hide(); }); // tests complete - runner.on('test end', function () { + runner.on('test end', function() { complete++; var percent = complete / total; - var n = width * percent | 0; + var n = (width * percent) | 0; var i = width - n; if (n === lastN && !options.verbose) { @@ -86,7 +86,7 @@ function Progress (runner, options) { // tests are complete, output some stats // and the failures if any - runner.once('end', function () { + runner.once('end', function() { cursor.show(); console.log(); self.epilogue(); diff --git a/lib/reporters/spec.js b/lib/reporters/spec.js index 89499e9cb1..75e6dda1b5 100644 --- a/lib/reporters/spec.js +++ b/lib/reporters/spec.js @@ -26,47 +26,49 @@ exports = module.exports = Spec; * @api public * @param {Runner} runner */ -function Spec (runner) { +function Spec(runner) { Base.call(this, runner); var self = this; var indents = 0; var n = 0; - function indent () { + function indent() { return Array(indents).join(' '); } - runner.on('start', function () { + runner.on('start', function() { console.log(); }); - runner.on('suite', function (suite) { + runner.on('suite', function(suite) { ++indents; console.log(color('suite', '%s%s'), indent(), suite.title); }); - runner.on('suite end', function () { + runner.on('suite end', function() { --indents; if (indents === 1) { console.log(); } }); - runner.on('pending', function (test) { + runner.on('pending', function(test) { var fmt = indent() + color('pending', ' - %s'); console.log(fmt, test.title); }); - runner.on('pass', function (test) { + runner.on('pass', function(test) { var fmt; if (test.speed === 'fast') { - fmt = indent() + + fmt = + indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s'); console.log(fmt, test.title); } else { - fmt = indent() + + fmt = + indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s') + color(test.speed, ' (%dms)'); @@ -74,7 +76,7 @@ function Spec (runner) { } }); - runner.on('fail', function (test) { + runner.on('fail', function(test) { console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); }); diff --git a/lib/reporters/tap.js b/lib/reporters/tap.js index cbe6c73fda..feaf7ea21a 100644 --- a/lib/reporters/tap.js +++ b/lib/reporters/tap.js @@ -24,32 +24,32 @@ exports = module.exports = TAP; * @api public * @param {Runner} runner */ -function TAP (runner) { +function TAP(runner) { Base.call(this, runner); var n = 1; var passes = 0; var failures = 0; - runner.on('start', function () { + runner.on('start', function() { var total = runner.grepTotal(runner.suite); console.log('%d..%d', 1, total); }); - runner.on('test end', function () { + runner.on('test end', function() { ++n; }); - runner.on('pending', function (test) { + runner.on('pending', function(test) { console.log('ok %d %s # SKIP -', n, title(test)); }); - runner.on('pass', function (test) { + runner.on('pass', function(test) { passes++; console.log('ok %d %s', n, title(test)); }); - runner.on('fail', function (test, err) { + runner.on('fail', function(test, err) { failures++; console.log('not ok %d %s', n, title(test)); if (err.message) { @@ -60,7 +60,7 @@ function TAP (runner) { } }); - runner.once('end', function () { + runner.once('end', function() { console.log('# tests ' + (passes + failures)); console.log('# pass ' + passes); console.log('# fail ' + failures); @@ -74,6 +74,6 @@ function TAP (runner) { * @param {Object} test * @return {String} */ -function title (test) { +function title(test) { return test.fullTitle().replace(/#/g, ''); } diff --git a/lib/reporters/xunit.js b/lib/reporters/xunit.js index 30b1f0758f..c1a930d2d8 100644 --- a/lib/reporters/xunit.js +++ b/lib/reporters/xunit.js @@ -42,7 +42,7 @@ exports = module.exports = XUnit; * @api public * @param {Runner} runner */ -function XUnit (runner, options) { +function XUnit(runner, options) { Base.call(this, runner); var stats = this.stats; @@ -72,30 +72,36 @@ function XUnit (runner, options) { // fall back to the default suite name suiteName = suiteName || DEFAULT_SUITE_NAME; - runner.on('pending', function (test) { + runner.on('pending', function(test) { tests.push(test); }); - runner.on('pass', function (test) { + runner.on('pass', function(test) { tests.push(test); }); - runner.on('fail', function (test) { + runner.on('fail', function(test) { tests.push(test); }); - runner.once('end', function () { - self.write(tag('testsuite', { - name: suiteName, - 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(function (t) { + runner.once('end', function() { + self.write( + tag( + 'testsuite', + { + name: suiteName, + 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(function(t) { self.test(t); }); @@ -114,9 +120,9 @@ inherits(XUnit, Base); * @param failures * @param {Function} fn */ -XUnit.prototype.done = function (failures, fn) { +XUnit.prototype.done = function(failures, fn) { if (this.fileStream) { - this.fileStream.end(function () { + this.fileStream.end(function() { fn(failures); }); } else { @@ -129,7 +135,7 @@ XUnit.prototype.done = function (failures, fn) { * * @param {string} line */ -XUnit.prototype.write = function (line) { +XUnit.prototype.write = function(line) { if (this.fileStream) { this.fileStream.write(line + '\n'); } else if (typeof process === 'object' && process.stdout) { @@ -144,16 +150,28 @@ XUnit.prototype.write = function (line) { * * @param {Test} test */ -XUnit.prototype.test = function (test) { +XUnit.prototype.test = function(test) { var attrs = { classname: test.parent.fullTitle(), name: test.title, - time: (test.duration / 1000) || 0 + time: test.duration / 1000 || 0 }; if (test.state === 'failed') { var err = test.err; - this.write(tag('testcase', attrs, false, tag('failure', {}, false, escape(err.message) + '\n' + escape(err.stack)))); + this.write( + tag( + 'testcase', + attrs, + false, + tag( + 'failure', + {}, + false, + escape(err.message) + '\n' + escape(err.stack) + ) + ) + ); } else if (test.isPending()) { this.write(tag('testcase', attrs, false, tag('skipped', {}, true))); } else { @@ -170,7 +188,7 @@ XUnit.prototype.test = function (test) { * @param content * @return {string} */ -function tag (name, attrs, close, content) { +function tag(name, attrs, close, content) { var end = close ? '/>' : '>'; var pairs = []; var tag; diff --git a/lib/runnable.js b/lib/runnable.js index f212d6715b..73da817793 100644 --- a/lib/runnable.js +++ b/lib/runnable.js @@ -29,7 +29,7 @@ module.exports = Runnable; * @param {String} title * @param {Function} fn */ -function Runnable (title, fn) { +function Runnable(title, fn) { this.title = title; this.fn = fn; this.body = (fn || '').toString(); @@ -56,7 +56,7 @@ utils.inherits(Runnable, EventEmitter); * @param {number|string} ms * @return {Runnable|number} ms or Runnable instance. */ -Runnable.prototype.timeout = function (ms) { +Runnable.prototype.timeout = function(ms) { if (!arguments.length) { return this._timeout; } @@ -82,7 +82,7 @@ Runnable.prototype.timeout = function (ms) { * @param {number|string} ms * @return {Runnable|number} ms or Runnable instance. */ -Runnable.prototype.slow = function (ms) { +Runnable.prototype.slow = function(ms) { if (!arguments.length || typeof ms === 'undefined') { return this._slow; } @@ -101,7 +101,7 @@ Runnable.prototype.slow = function (ms) { * @param {boolean} enabled * @return {Runnable|boolean} enabled or Runnable instance. */ -Runnable.prototype.enableTimeouts = function (enabled) { +Runnable.prototype.enableTimeouts = function(enabled) { if (!arguments.length) { return this._enableTimeouts; } @@ -117,7 +117,7 @@ Runnable.prototype.enableTimeouts = function (enabled) { * @public * @api public */ -Runnable.prototype.skip = function () { +Runnable.prototype.skip = function() { throw new Pending('sync skip'); }; @@ -126,7 +126,7 @@ Runnable.prototype.skip = function () { * * @api private */ -Runnable.prototype.isPending = function () { +Runnable.prototype.isPending = function() { return this.pending || (this.parent && this.parent.isPending()); }; @@ -135,7 +135,7 @@ Runnable.prototype.isPending = function () { * @return {boolean} * @private */ -Runnable.prototype.isFailed = function () { +Runnable.prototype.isFailed = function() { return !this.isPending() && this.state === 'failed'; }; @@ -144,7 +144,7 @@ Runnable.prototype.isFailed = function () { * @return {boolean} * @private */ -Runnable.prototype.isPassed = function () { +Runnable.prototype.isPassed = function() { return !this.isPending() && this.state === 'passed'; }; @@ -153,7 +153,7 @@ Runnable.prototype.isPassed = function () { * * @api private */ -Runnable.prototype.retries = function (n) { +Runnable.prototype.retries = function(n) { if (!arguments.length) { return this._retries; } @@ -165,7 +165,7 @@ Runnable.prototype.retries = function (n) { * * @api private */ -Runnable.prototype.currentRetry = function (n) { +Runnable.prototype.currentRetry = function(n) { if (!arguments.length) { return this._currentRetry; } @@ -181,7 +181,7 @@ Runnable.prototype.currentRetry = function (n) { * @api public * @return {string} */ -Runnable.prototype.fullTitle = function () { +Runnable.prototype.fullTitle = function() { return this.titlePath().join(' '); }; @@ -193,7 +193,7 @@ Runnable.prototype.fullTitle = function () { * @api public * @return {string} */ -Runnable.prototype.titlePath = function () { +Runnable.prototype.titlePath = function() { return this.parent.titlePath().concat([this.title]); }; @@ -202,7 +202,7 @@ Runnable.prototype.titlePath = function () { * * @api private */ -Runnable.prototype.clearTimeout = function () { +Runnable.prototype.clearTimeout = function() { clearTimeout(this.timer); }; @@ -212,19 +212,23 @@ Runnable.prototype.clearTimeout = function () { * @api private * @return {string} */ -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); +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 + ); }; /** @@ -232,7 +236,7 @@ Runnable.prototype.inspect = function () { * * @api private */ -Runnable.prototype.resetTimeout = function () { +Runnable.prototype.resetTimeout = function() { var self = this; var ms = this.timeout() || 1e9; @@ -240,7 +244,7 @@ Runnable.prototype.resetTimeout = function () { return; } this.clearTimeout(); - this.timer = setTimeout(function () { + this.timer = setTimeout(function() { if (!self._enableTimeouts) { return; } @@ -255,7 +259,7 @@ Runnable.prototype.resetTimeout = function () { * @api private * @param {string[]} globals */ -Runnable.prototype.globals = function (globals) { +Runnable.prototype.globals = function(globals) { if (!arguments.length) { return this._allowedGlobals; } @@ -268,7 +272,7 @@ Runnable.prototype.globals = function (globals) { * @param {Function} fn * @api private */ -Runnable.prototype.run = function (fn) { +Runnable.prototype.run = function(fn) { var self = this; var start = new Date(); var ctx = this.ctx; @@ -281,7 +285,7 @@ Runnable.prototype.run = function (fn) { } // called multiple times - function multiple (err) { + function multiple(err) { if (emitted) { return; } @@ -296,7 +300,7 @@ Runnable.prototype.run = function (fn) { } // finished - function done (err) { + function done(err) { var ms = self.timeout(); if (self.timedOut) { return; @@ -323,7 +327,7 @@ Runnable.prototype.run = function (fn) { this.resetTimeout(); // allows skip() to be used in an explicit async context - this.skip = function asyncSkip () { + this.skip = function asyncSkip() { done(new Pending('async skip call')); // halt execution. the Runnable will be marked pending // by the previous call, and the uncaught handler will ignore @@ -364,43 +368,53 @@ Runnable.prototype.run = function (fn) { done(utils.getError(err)); } - function callFn (fn) { + function callFn(fn) { var result = fn.call(ctx); if (result && typeof result.then === 'function') { self.resetTimeout(); - result - .then(function () { + result.then( + function() { done(); // Return null so libraries like bluebird do not warn about // subsequently constructed Promises. return null; }, - function (reason) { + function(reason) { done(reason || new Error('Promise rejected with no or falsy reason')); - }); + } + ); } else { if (self.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()` or returning a promise')); + return done( + new Error( + '--async-only option in use without declaring `done()` or returning a promise' + ) + ); } done(); } } - function callFnAsync (fn) { - var result = fn.call(ctx, function (err) { + function callFnAsync(fn) { + var result = fn.call(ctx, function(err) { if (err instanceof Error || toString.call(err) === '[object Error]') { return done(err); } if (err) { if (Object.prototype.toString.call(err) === '[object Object]') { - return done(new Error('done() invoked with non-Error: ' + - JSON.stringify(err))); + return done( + new Error('done() invoked with non-Error: ' + JSON.stringify(err)) + ); } return done(new Error('done() invoked with non-Error: ' + err)); } if (result && utils.isPromise(result)) { - return done(new Error('Resolution method is overspecified. Specify a callback *or* return a Promise; not both.')); + return done( + new Error( + 'Resolution method is overspecified. Specify a callback *or* return a Promise; not both.' + ) + ); } done(); @@ -415,8 +429,11 @@ Runnable.prototype.run = function (fn) { * @returns {Error} a "timeout" error * @private */ -Runnable.prototype._timeoutError = function (ms) { - var msg = 'Timeout of ' + ms + 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.'; +Runnable.prototype._timeoutError = function(ms) { + var msg = + 'Timeout of ' + + ms + + 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.'; if (this.file) { msg += ' (' + this.file + ')'; } diff --git a/lib/runner.js b/lib/runner.js index d16934142a..565d47d6e5 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -63,7 +63,7 @@ module.exports = Runner; * @param {boolean} [delay] Whether or not to delay execution of root suite * until ready. */ -function Runner (suite, delay) { +function Runner(suite, delay) { var self = this; this._globals = []; this._abort = false; @@ -72,10 +72,10 @@ function Runner (suite, delay) { this.started = false; this.total = suite.total(); this.failures = 0; - this.on('test end', function (test) { + this.on('test end', function(test) { self.checkGlobals(test); }); - this.on('hook end', function (hook) { + this.on('hook end', function(hook) { self.checkGlobals(hook); }); this._defaultGrep = /.*/; @@ -107,7 +107,7 @@ inherits(Runner, EventEmitter); * @param {boolean} invert * @return {Runner} Runner instance. */ -Runner.prototype.grep = function (re, invert) { +Runner.prototype.grep = function(re, invert) { debug('grep %s', re); this._grep = re; this._invert = invert; @@ -125,11 +125,11 @@ Runner.prototype.grep = function (re, invert) { * @param {Suite} suite * @return {number} */ -Runner.prototype.grepTotal = function (suite) { +Runner.prototype.grepTotal = function(suite) { var self = this; var total = 0; - suite.eachTest(function (test) { + suite.eachTest(function(test) { var match = self._grep.test(test.fullTitle()); if (self._invert) { match = !match; @@ -148,7 +148,7 @@ Runner.prototype.grepTotal = function (suite) { * @return {Array} * @api private */ -Runner.prototype.globalProps = function () { +Runner.prototype.globalProps = function() { var props = Object.keys(global); // non-enumerables @@ -171,7 +171,7 @@ Runner.prototype.globalProps = function () { * @param {Array} arr * @return {Runner} Runner instance. */ -Runner.prototype.globals = function (arr) { +Runner.prototype.globals = function(arr) { if (!arguments.length) { return this._globals; } @@ -185,7 +185,7 @@ Runner.prototype.globals = function (arr) { * * @api private */ -Runner.prototype.checkGlobals = function (test) { +Runner.prototype.checkGlobals = function(test) { if (this.ignoreLeaks) { return; } @@ -207,7 +207,10 @@ Runner.prototype.checkGlobals = function (test) { this._globals = this._globals.concat(leaks); if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); + this.fail( + test, + new Error('global leaks detected: ' + leaks.join(', ') + '') + ); } else if (leaks.length) { this.fail(test, new Error('global leak detected: ' + leaks[0])); } @@ -220,7 +223,7 @@ Runner.prototype.checkGlobals = function (test) { * @param {Test} test * @param {Error} err */ -Runner.prototype.fail = function (test, err) { +Runner.prototype.fail = function(test, err) { if (test.isPending()) { return; } @@ -229,13 +232,18 @@ Runner.prototype.fail = function (test, err) { test.state = 'failed'; if (!(err instanceof Error || (err && typeof err.message === 'string'))) { - err = new Error('the ' + type(err) + ' ' + stringify(err) + ' was thrown, throw an Error :)'); + err = new Error( + 'the ' + + type(err) + + ' ' + + stringify(err) + + ' was thrown, throw an Error :)' + ); } try { - err.stack = (this.fullStackTrace || !err.stack) - ? err.stack - : stackFilter(err.stack); + err.stack = + this.fullStackTrace || !err.stack ? err.stack : stackFilter(err.stack); } catch (ignored) { // some environments do not take kindly to monkeying with the stack } @@ -263,10 +271,11 @@ Runner.prototype.fail = function (test, err) { * @param {Hook} hook * @param {Error} err */ -Runner.prototype.failHook = function (hook, err) { +Runner.prototype.failHook = function(hook, err) { if (hook.ctx && hook.ctx.currentTest) { hook.originalTitle = hook.originalTitle || hook.title; - hook.title = hook.originalTitle + ' for "' + hook.ctx.currentTest.title + '"'; + hook.title = + hook.originalTitle + ' for "' + hook.ctx.currentTest.title + '"'; } if (this.suite.bail()) { @@ -283,12 +292,12 @@ Runner.prototype.failHook = function (hook, err) { * @param {Function} fn */ -Runner.prototype.hook = function (name, fn) { +Runner.prototype.hook = function(name, fn) { var suite = this.suite; var hooks = suite['_' + name]; var self = this; - function next (i) { + function next(i) { var hook = hooks[i]; if (!hook) { return fn(); @@ -300,12 +309,12 @@ Runner.prototype.hook = function (name, fn) { self.emit('hook', hook); if (!hook.listeners('error').length) { - hook.on('error', function (err) { + hook.on('error', function(err) { self.failHook(hook, err); }); } - hook.run(function (err) { + hook.run(function(err) { var testError = hook.error(); if (testError) { self.fail(self.test, testError); @@ -315,7 +324,7 @@ Runner.prototype.hook = function (name, fn) { if (name === 'beforeEach' || name === 'afterEach') { self.test.pending = true; } else { - suite.tests.forEach(function (test) { + suite.tests.forEach(function(test) { test.pending = true; }); // a pending hook won't be executed twice. @@ -334,7 +343,7 @@ Runner.prototype.hook = function (name, fn) { }); } - Runner.immediately(function () { + Runner.immediately(function() { next(0); }); }; @@ -348,11 +357,11 @@ Runner.prototype.hook = function (name, fn) { * @param {Array} suites * @param {Function} fn */ -Runner.prototype.hooks = function (name, suites, fn) { +Runner.prototype.hooks = function(name, suites, fn) { var self = this; var orig = this.suite; - function next (suite) { + function next(suite) { self.suite = suite; if (!suite) { @@ -360,7 +369,7 @@ Runner.prototype.hooks = function (name, suites, fn) { return fn(); } - self.hook(name, function (err) { + self.hook(name, function(err) { if (err) { var errSuite = self.suite; self.suite = orig; @@ -381,7 +390,7 @@ Runner.prototype.hooks = function (name, suites, fn) { * @param {Function} fn * @api private */ -Runner.prototype.hookUp = function (name, fn) { +Runner.prototype.hookUp = function(name, fn) { var suites = [this.suite].concat(this.parents()).reverse(); this.hooks(name, suites, fn); }; @@ -393,7 +402,7 @@ Runner.prototype.hookUp = function (name, fn) { * @param {Function} fn * @api private */ -Runner.prototype.hookDown = function (name, fn) { +Runner.prototype.hookDown = function(name, fn) { var suites = [this.suite].concat(this.parents()); this.hooks(name, suites, fn); }; @@ -405,7 +414,7 @@ Runner.prototype.hookDown = function (name, fn) { * @return {Array} * @api private */ -Runner.prototype.parents = function () { +Runner.prototype.parents = function() { var suite = this.suite; var suites = []; while (suite.parent) { @@ -421,7 +430,7 @@ Runner.prototype.parents = function () { * @param {Function} fn * @api private */ -Runner.prototype.runTest = function (fn) { +Runner.prototype.runTest = function(fn) { var self = this; var test = this.test; @@ -435,7 +444,7 @@ Runner.prototype.runTest = function (fn) { if (this.asyncOnly) { test.asyncOnly = true; } - test.on('error', function (err) { + test.on('error', function(err) { self.fail(test, err); }); if (this.allowUncaught) { @@ -456,12 +465,12 @@ Runner.prototype.runTest = function (fn) { * @param {Suite} suite * @param {Function} fn */ -Runner.prototype.runTests = function (suite, fn) { +Runner.prototype.runTests = function(suite, fn) { var self = this; var tests = suite.tests.slice(); var test; - function hookErr (_, errSuite, after) { + function hookErr(_, errSuite, after) { // before/after Each hook for errSuite failed: var orig = self.suite; @@ -471,7 +480,7 @@ Runner.prototype.runTests = function (suite, fn) { if (self.suite) { // call hookUp afterEach - self.hookUp('afterEach', function (err2, errSuite2) { + self.hookUp('afterEach', function(err2, errSuite2) { self.suite = orig; // some hooks may fail even now if (err2) { @@ -487,7 +496,7 @@ Runner.prototype.runTests = function (suite, fn) { } } - function next (err, errSuite) { + function next(err, errSuite) { // if we bail after first err if (self.failures && suite._bail) { return fn(); @@ -544,8 +553,8 @@ Runner.prototype.runTests = function (suite, fn) { } // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function (err, errSuite) { + self.emit('test', (self.test = test)); + self.hookDown('beforeEach', function(err, errSuite) { if (test.isPending()) { if (self.forbidPending) { test.isPending = alwaysFalse; @@ -561,7 +570,7 @@ Runner.prototype.runTests = function (suite, fn) { return hookErr(err, errSuite, false); } self.currentRunnable = self.test; - self.runTest(function (err) { + self.runTest(function(err) { test = self.test; if (err) { var retry = test.currentRetry(); @@ -603,7 +612,7 @@ Runner.prototype.runTests = function (suite, fn) { next(); }; -function alwaysFalse () { +function alwaysFalse() { return false; } @@ -614,7 +623,7 @@ function alwaysFalse () { * @param {Suite} suite * @param {Function} fn */ -Runner.prototype.runSuite = function (suite, fn) { +Runner.prototype.runSuite = function(suite, fn) { var i = 0; var self = this; var total = this.grepTotal(suite); @@ -626,9 +635,9 @@ Runner.prototype.runSuite = function (suite, fn) { return fn(); } - this.emit('suite', this.suite = suite); + this.emit('suite', (this.suite = suite)); - function next (errSuite) { + function next(errSuite) { if (errSuite) { // current suite failed on a hook from errSuite if (errSuite === suite) { @@ -654,7 +663,7 @@ Runner.prototype.runSuite = function (suite, fn) { // huge recursive loop and thus a maximum call stack error. // See comment in `this.runTests()` for more information. if (self._grep !== self._defaultGrep) { - Runner.immediately(function () { + Runner.immediately(function() { self.runSuite(curr, next); }); } else { @@ -662,7 +671,7 @@ Runner.prototype.runSuite = function (suite, fn) { } } - function done (errSuite) { + function done(errSuite) { self.suite = suite; self.nextSuite = next; @@ -676,7 +685,7 @@ Runner.prototype.runSuite = function (suite, fn) { // remove reference to test delete self.test; - self.hook('afterAll', function () { + self.hook('afterAll', function() { self.emit('suite end', suite); fn(errSuite); }); @@ -685,7 +694,7 @@ Runner.prototype.runSuite = function (suite, fn) { this.nextSuite = next; - this.hook('beforeAll', function (err) { + this.hook('beforeAll', function(err) { if (err) { return done(); } @@ -699,11 +708,17 @@ Runner.prototype.runSuite = function (suite, fn) { * @param {Error} err * @api private */ -Runner.prototype.uncaught = function (err) { +Runner.prototype.uncaught = function(err) { if (err) { - debug('uncaught exception %s', err === (function () { - return this; - }.call(err)) ? (err.message || err) : err); + debug( + 'uncaught exception %s', + err === + function() { + return this; + }.call(err) + ? err.message || err + : err + ); } else { debug('uncaught undefined exception'); err = undefinedError(); @@ -776,8 +791,8 @@ Runner.prototype.uncaught = function (err) { * * @param {Suite} suite */ -function cleanSuiteReferences (suite) { - function cleanArrReferences (arr) { +function cleanSuiteReferences(suite) { + function cleanArrReferences(arr) { for (var i = 0; i < arr.length; i++) { delete arr[i].fn; } @@ -814,24 +829,24 @@ function cleanSuiteReferences (suite) { * @param {Function} fn * @return {Runner} Runner instance. */ -Runner.prototype.run = function (fn) { +Runner.prototype.run = function(fn) { var self = this; var rootSuite = this.suite; - fn = fn || function () {}; + fn = fn || function() {}; - function uncaught (err) { + function uncaught(err) { self.uncaught(err); } - function start () { + function start() { // If there is an `only` filter if (hasOnly(rootSuite)) { filterOnly(rootSuite); } self.started = true; self.emit('start'); - self.runSuite(rootSuite, function () { + self.runSuite(rootSuite, function() { debug('finished running'); self.emit('end'); }); @@ -843,7 +858,7 @@ Runner.prototype.run = function (fn) { this.on('suite end', cleanSuiteReferences); // callback - this.on('end', function () { + this.on('end', function() { debug('end'); process.removeListener('uncaughtException', uncaught); fn(self.failures); @@ -872,7 +887,7 @@ Runner.prototype.run = function (fn) { * @api public * @return {Runner} Runner instance. */ -Runner.prototype.abort = function () { +Runner.prototype.abort = function() { debug('aborting'); this._abort = true; @@ -886,7 +901,7 @@ Runner.prototype.abort = function () { * @returns {Boolean} * @api private */ -function filterOnly (suite) { +function filterOnly(suite) { if (suite._onlyTests.length) { // If the suite contains `only` tests, run those and ignore any nested suites. suite.tests = suite._onlyTests; @@ -894,7 +909,7 @@ function filterOnly (suite) { } else { // Otherwise, do not run any of the tests in this suite. suite.tests = []; - suite._onlySuites.forEach(function (onlySuite) { + suite._onlySuites.forEach(function(onlySuite) { // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite. // Otherwise, all of the tests on this `only` suite should be run, so don't filter it. if (hasOnly(onlySuite)) { @@ -902,8 +917,10 @@ function filterOnly (suite) { } }); // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants. - suite.suites = suite.suites.filter(function (childSuite) { - return suite._onlySuites.indexOf(childSuite) !== -1 || filterOnly(childSuite); + suite.suites = suite.suites.filter(function(childSuite) { + return ( + suite._onlySuites.indexOf(childSuite) !== -1 || filterOnly(childSuite) + ); }); } // Keep the suite only if there is something to run @@ -917,8 +934,12 @@ function filterOnly (suite) { * @returns {Boolean} * @api private */ -function hasOnly (suite) { - return suite._onlyTests.length || suite._onlySuites.length || suite.suites.some(hasOnly); +function hasOnly(suite) { + return ( + suite._onlyTests.length || + suite._onlySuites.length || + suite.suites.some(hasOnly) + ); } /** @@ -929,8 +950,8 @@ function hasOnly (suite) { * @param {Array} globals * @return {Array} */ -function filterLeaks (ok, globals) { - return globals.filter(function (key) { +function filterLeaks(ok, globals) { + return globals.filter(function(key) { // Firefox and Chrome exposes iframes as index inside the window object if (/^\d+/.test(key)) { return false; @@ -939,13 +960,13 @@ function filterLeaks (ok, globals) { // 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)) { + 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)) { + if (global.navigator && /^\d+/.test(key)) { return false; } @@ -954,7 +975,7 @@ function filterLeaks (ok, globals) { return false; } - var matched = ok.filter(function (ok) { + var matched = ok.filter(function(ok) { if (~ok.indexOf('*')) { return key.indexOf(ok.split('*')[0]) === 0; } @@ -970,16 +991,16 @@ function filterLeaks (ok, globals) { * @return {Array} * @api private */ -function extraGlobals () { +function extraGlobals() { if (typeof process === 'object' && typeof process.version === 'string') { var parts = process.version.split('.'); - var nodeVersion = parts.reduce(function (a, v) { - return a << 8 | v; + var nodeVersion = parts.reduce(function(a, v) { + return (a << 8) | v; }); // 'errno' was renamed to process._errno in v0.9.11. - if (nodeVersion < 0x00090B) { + if (nodeVersion < 0x00090b) { return ['errno']; } } diff --git a/lib/suite.js b/lib/suite.js index f0db595973..91832ba3ad 100644 --- a/lib/suite.js +++ b/lib/suite.js @@ -31,7 +31,7 @@ exports = module.exports = Suite; * @param {string} title * @return {Suite} */ -exports.create = function (parent, title) { +exports.create = function(parent, title) { var suite = new Suite(title, parent.ctx); suite.parent = parent; title = suite.fullTitle(); @@ -48,12 +48,16 @@ exports.create = function (parent, title) { * @param {string} title * @param {Context} parentContext */ -function Suite (title, parentContext) { +function Suite(title, parentContext) { if (!utils.isString(title)) { - throw new Error('Suite `title` should be a "string" but "' + typeof title + '" was given instead.'); + throw new Error( + 'Suite `title` should be a "string" but "' + + typeof title + + '" was given instead.' + ); } this.title = title; - function Context () {} + function Context() {} Context.prototype = parentContext; this.ctx = new Context(); this.suites = []; @@ -85,7 +89,7 @@ inherits(Suite, EventEmitter); * @api private * @return {Suite} */ -Suite.prototype.clone = function () { +Suite.prototype.clone = function() { var suite = new Suite(this.title); debug('clone'); suite.ctx = this.ctx; @@ -104,7 +108,7 @@ Suite.prototype.clone = function () { * @param {number|string} ms * @return {Suite|number} for chaining */ -Suite.prototype.timeout = function (ms) { +Suite.prototype.timeout = function(ms) { if (!arguments.length) { return this._timeout; } @@ -126,7 +130,7 @@ Suite.prototype.timeout = function (ms) { * @param {number|string} n * @return {Suite|number} for chaining */ -Suite.prototype.retries = function (n) { +Suite.prototype.retries = function(n) { if (!arguments.length) { return this._retries; } @@ -136,13 +140,13 @@ Suite.prototype.retries = function (n) { }; /** - * Set or get timeout to `enabled`. - * - * @api private - * @param {boolean} enabled - * @return {Suite|boolean} self or enabled - */ -Suite.prototype.enableTimeouts = function (enabled) { + * Set or get timeout to `enabled`. + * + * @api private + * @param {boolean} enabled + * @return {Suite|boolean} self or enabled + */ +Suite.prototype.enableTimeouts = function(enabled) { if (!arguments.length) { return this._enableTimeouts; } @@ -158,7 +162,7 @@ Suite.prototype.enableTimeouts = function (enabled) { * @param {number|string} ms * @return {Suite|number} for chaining */ -Suite.prototype.slow = function (ms) { +Suite.prototype.slow = function(ms) { if (!arguments.length) { return this._slow; } @@ -177,7 +181,7 @@ Suite.prototype.slow = function (ms) { * @param {boolean} bail * @return {Suite|number} for chaining */ -Suite.prototype.bail = function (bail) { +Suite.prototype.bail = function(bail) { if (!arguments.length) { return this._bail; } @@ -191,7 +195,7 @@ Suite.prototype.bail = function (bail) { * * @api private */ -Suite.prototype.isPending = function () { +Suite.prototype.isPending = function() { return this.pending || (this.parent && this.parent.isPending()); }; @@ -202,7 +206,7 @@ Suite.prototype.isPending = function () { * @param {Function} fn - Hook callback * @returns {Hook} A new hook */ -Suite.prototype._createHook = function (title, fn) { +Suite.prototype._createHook = function(title, fn) { var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); @@ -222,7 +226,7 @@ Suite.prototype._createHook = function (title, fn) { * @param {Function} fn * @return {Suite} for chaining */ -Suite.prototype.beforeAll = function (title, fn) { +Suite.prototype.beforeAll = function(title, fn) { if (this.isPending()) { return this; } @@ -246,7 +250,7 @@ Suite.prototype.beforeAll = function (title, fn) { * @param {Function} fn * @return {Suite} for chaining */ -Suite.prototype.afterAll = function (title, fn) { +Suite.prototype.afterAll = function(title, fn) { if (this.isPending()) { return this; } @@ -270,7 +274,7 @@ Suite.prototype.afterAll = function (title, fn) { * @param {Function} fn * @return {Suite} for chaining */ -Suite.prototype.beforeEach = function (title, fn) { +Suite.prototype.beforeEach = function(title, fn) { if (this.isPending()) { return this; } @@ -294,7 +298,7 @@ Suite.prototype.beforeEach = function (title, fn) { * @param {Function} fn * @return {Suite} for chaining */ -Suite.prototype.afterEach = function (title, fn) { +Suite.prototype.afterEach = function(title, fn) { if (this.isPending()) { return this; } @@ -317,7 +321,7 @@ Suite.prototype.afterEach = function (title, fn) { * @param {Suite} suite * @return {Suite} for chaining */ -Suite.prototype.addSuite = function (suite) { +Suite.prototype.addSuite = function(suite) { suite.parent = this; suite.timeout(this.timeout()); suite.retries(this.retries()); @@ -336,7 +340,7 @@ Suite.prototype.addSuite = function (suite) { * @param {Test} test * @return {Suite} for chaining */ -Suite.prototype.addTest = function (test) { +Suite.prototype.addTest = function(test) { test.parent = this; test.timeout(this.timeout()); test.retries(this.retries()); @@ -357,7 +361,7 @@ Suite.prototype.addTest = function (test) { * @api public * @return {string} */ -Suite.prototype.fullTitle = function () { +Suite.prototype.fullTitle = function() { return this.titlePath().join(' '); }; @@ -370,7 +374,7 @@ Suite.prototype.fullTitle = function () { * @api public * @return {string} */ -Suite.prototype.titlePath = function () { +Suite.prototype.titlePath = function() { var result = []; if (this.parent) { result = result.concat(this.parent.titlePath()); @@ -389,10 +393,12 @@ Suite.prototype.titlePath = function () { * @api public * @return {number} */ -Suite.prototype.total = function () { - return this.suites.reduce(function (sum, suite) { - return sum + suite.total(); - }, 0) + this.tests.length; +Suite.prototype.total = function() { + return ( + this.suites.reduce(function(sum, suite) { + return sum + suite.total(); + }, 0) + this.tests.length + ); }; /** @@ -403,9 +409,9 @@ Suite.prototype.total = function () { * @param {Function} fn * @return {Suite} */ -Suite.prototype.eachTest = function (fn) { +Suite.prototype.eachTest = function(fn) { this.tests.forEach(fn); - this.suites.forEach(function (suite) { + this.suites.forEach(function(suite) { suite.eachTest(fn); }); return this; @@ -414,7 +420,7 @@ Suite.prototype.eachTest = function (fn) { /** * This will run the root suite if we happen to be running in delayed mode. */ -Suite.prototype.run = function run () { +Suite.prototype.run = function run() { if (this.root) { this.emit('run'); } diff --git a/lib/test.js b/lib/test.js index 0b59ea82cd..d8233a3571 100644 --- a/lib/test.js +++ b/lib/test.js @@ -13,9 +13,13 @@ module.exports = Test; * @param {String} title * @param {Function} fn */ -function Test (title, fn) { +function Test(title, fn) { if (!isString(title)) { - throw new Error('Test `title` should be a "string" but "' + typeof title + '" was given instead.'); + throw new Error( + 'Test `title` should be a "string" but "' + + typeof title + + '" was given instead.' + ); } Runnable.call(this, title, fn); this.pending = !fn; @@ -27,7 +31,7 @@ function Test (title, fn) { */ utils.inherits(Test, Runnable); -Test.prototype.clone = function () { +Test.prototype.clone = function() { var test = new Test(this.title, this.fn); test.timeout(this.timeout()); test.slow(this.slow()); diff --git a/lib/utils.js b/lib/utils.js index d6bb2bd8e9..37282d3ce7 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -30,8 +30,8 @@ exports.inherits = require('util').inherits; * @param {string} html * @return {string} */ -exports.escape = function (html) { - return he.encode(String(html), { useNamedReferences: false }); +exports.escape = function(html) { + return he.encode(String(html), {useNamedReferences: false}); }; /** @@ -41,7 +41,7 @@ exports.escape = function (html) { * @param {Object} obj * @return {boolean} */ -exports.isString = function (obj) { +exports.isString = function(obj) { return typeof obj === 'string'; }; @@ -53,11 +53,11 @@ exports.isString = function (obj) { * @param {Array} files * @param {Function} fn */ -exports.watch = function (files, fn) { - var options = { interval: 100 }; - files.forEach(function (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) { + fs.watchFile(file, options, function(curr, prev) { if (prev.mtime < curr.mtime) { fn(file); } @@ -72,7 +72,7 @@ exports.watch = function (files, fn) { * @param {string} path * @return {boolean} */ -function ignored (path) { +function ignored(path) { return !~ignore.indexOf(path); } @@ -85,15 +85,16 @@ function ignored (path) { * @param {Array} [ret=[]] * @return {Array} */ -exports.files = function (dir, ext, ret) { +exports.files = function(dir, ext, ret) { ret = ret || []; ext = ext || ['js']; var re = new RegExp('\\.(' + ext.join('|') + ')$'); - fs.readdirSync(dir) + fs + .readdirSync(dir) .filter(ignored) - .forEach(function (path) { + .forEach(function(path) { path = join(dir, path); if (fs.lstatSync(path).isDirectory()) { exports.files(path, ext, ret); @@ -112,7 +113,7 @@ exports.files = function (dir, ext, ret) { * @param {string} str * @return {string} */ -exports.slug = function (str) { +exports.slug = function(str) { return str .toLowerCase() .replace(/ +/g, '-') @@ -125,15 +126,22 @@ exports.slug = function (str) { * @param {string} str * @return {string} */ -exports.clean = function (str) { +exports.clean = function(str) { str = str - .replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '') + .replace(/\r\n?|[\n\u2028\u2029]/g, '\n') + .replace(/^\uFEFF/, '') // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content - .replace(/^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, '$1$2$3'); + .replace( + /^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, + '$1$2$3' + ); 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'); + var re = new RegExp( + '^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}', + 'gm' + ); str = str.replace(re, ''); @@ -147,17 +155,20 @@ exports.clean = function (str) { * @param {string} qs * @return {Object} */ -exports.parseQuery = function (qs) { - return qs.replace('?', '').split('&').reduce(function (obj, pair) { - var i = pair.indexOf('='); - var key = pair.slice(0, i); - var val = pair.slice(++i); - - // Due to how the URLSearchParams API treats spaces - obj[key] = decodeURIComponent(val.replace(/\+/g, '%20')); - - return obj; - }, {}); +exports.parseQuery = function(qs) { + return qs + .replace('?', '') + .split('&') + .reduce(function(obj, pair) { + var i = pair.indexOf('='); + var key = pair.slice(0, i); + var val = pair.slice(++i); + + // Due to how the URLSearchParams API treats spaces + obj[key] = decodeURIComponent(val.replace(/\+/g, '%20')); + + return obj; + }, {}); }; /** @@ -167,7 +178,7 @@ exports.parseQuery = function (qs) { * @param {string} js * @return {string} */ -function highlight (js) { +function highlight(js) { return js .replace(//g, '>') @@ -175,8 +186,14 @@ function highlight (js) { .replace(/('.*?')/gm, '$1') .replace(/(\d+\.\d+)/gm, '$1') .replace(/(\d+)/gm, '$1') - .replace(/\bnew[ \t]+(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1'); + .replace( + /\bnew[ \t]+(\w+)/gm, + 'new $1' + ) + .replace( + /\b(function|new|throw|return|var|if|else)\b/gm, + '$1' + ); } /** @@ -185,7 +202,7 @@ function highlight (js) { * @api private * @param {string} name */ -exports.highlightTags = function (name) { +exports.highlightTags = function(name) { var code = document.getElementById('mocha').getElementsByTagName(name); for (var i = 0, len = code.length; i < len; ++i) { code[i].innerHTML = highlight(code[i].innerHTML); @@ -206,7 +223,7 @@ exports.highlightTags = function (name) { * @param {string} typeHint The type of the value * @returns {string} */ -function emptyRepresentation (value, typeHint) { +function emptyRepresentation(value, typeHint) { switch (typeHint) { case 'function': return '[Function]'; @@ -240,7 +257,7 @@ function emptyRepresentation (value, typeHint) { * type(global) // 'global' * type(new String('foo') // 'object' */ -var type = exports.type = function type (value) { +var type = (exports.type = function type(value) { if (value === undefined) { return 'undefined'; } else if (value === null) { @@ -248,10 +265,11 @@ var type = exports.type = function type (value) { } else if (Buffer.isBuffer(value)) { return 'buffer'; } - return Object.prototype.toString.call(value) + return Object.prototype.toString + .call(value) .replace(/^\[.+\s(.+?)]$/, '$1') .toLowerCase(); -}; +}); /** * Stringify `value`. Different behavior depending on type of value: @@ -268,21 +286,23 @@ var type = exports.type = function type (value) { * @param {*} value * @return {string} */ -exports.stringify = function (value) { +exports.stringify = function(value) { var typeHint = type(value); if (!~['object', 'array', 'function'].indexOf(typeHint)) { if (typeHint === 'buffer') { var json = Buffer.prototype.toJSON.call(value); // Based on the toJSON result - return jsonStringify(json.data && json.type ? json.data : json, 2) - .replace(/,(\n|$)/g, '$1'); + return jsonStringify( + json.data && json.type ? json.data : json, + 2 + ).replace(/,(\n|$)/g, '$1'); } // IE7/IE8 has a bizarre String constructor; needs to be coerced // into an array and back to obj. if (typeHint === 'string' && typeof value === 'object') { - value = value.split('').reduce(function (acc, char, idx) { + value = value.split('').reduce(function(acc, char, idx) { acc[idx] = char; return acc; }, {}); @@ -294,7 +314,10 @@ exports.stringify = function (value) { for (var prop in value) { if (Object.prototype.hasOwnProperty.call(value, prop)) { - return jsonStringify(exports.canonicalize(value, null, typeHint), 2).replace(/,(\n|$)/g, '$1'); + return jsonStringify( + exports.canonicalize(value, null, typeHint), + 2 + ).replace(/,(\n|$)/g, '$1'); } } @@ -310,7 +333,7 @@ exports.stringify = function (value) { * @param {number=} depth * @returns {*} */ -function jsonStringify (object, spaces, depth) { +function jsonStringify(object, spaces, depth) { if (typeof spaces === 'undefined') { // primitive types return _stringify(object); @@ -320,13 +343,16 @@ function jsonStringify (object, spaces, depth) { var space = spaces * depth; var str = Array.isArray(object) ? '[' : '{'; var end = Array.isArray(object) ? ']' : '}'; - var length = typeof object.length === 'number' ? object.length : Object.keys(object).length; + var length = + typeof object.length === 'number' + ? object.length + : Object.keys(object).length; // `.repeat()` polyfill - function repeat (s, n) { + function repeat(s, n) { return new Array(n).join(s); } - function _stringify (val) { + function _stringify(val) { switch (type(val)) { case 'null': case 'undefined': @@ -340,9 +366,10 @@ function jsonStringify (object, spaces, depth) { case 'regexp': case 'symbol': case 'number': - val = val === 0 && (1 / val) === -Infinity // `-0` - ? '-0' - : val.toString(); + val = + val === 0 && 1 / val === -Infinity // `-0` + ? '-0' + : val.toString(); break; case 'date': var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString(); @@ -355,9 +382,10 @@ function jsonStringify (object, spaces, depth) { val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; break; default: - val = (val === '[Function]' || val === '[Circular]') - ? val - : JSON.stringify(val); // string + val = + val === '[Function]' || val === '[Circular]' + ? val + : JSON.stringify(val); // string } return val; } @@ -367,15 +395,19 @@ function jsonStringify (object, spaces, depth) { continue; // not my business } --length; - str += '\n ' + repeat(' ', space) + + str += + '\n ' + + repeat(' ', space) + (Array.isArray(object) ? '' : '"' + i + '": ') + // key _stringify(object[i]) + // value (length ? ',' : ''); // comma } - return str + + return ( + str + // [], {} - (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end); + (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end) + ); } /** @@ -397,13 +429,13 @@ function jsonStringify (object, spaces, depth) { * @param {string} [typeHint] Type hint * @return {(Object|Array|Function|string|undefined)} */ -exports.canonicalize = function canonicalize (value, stack, typeHint) { +exports.canonicalize = function canonicalize(value, stack, typeHint) { var canonicalizedObj; /* eslint-disable no-unused-vars */ var prop; /* eslint-enable no-unused-vars */ typeHint = typeHint || type(value); - function withStack (value, fn) { + function withStack(value, fn) { stack.push(value); fn(); stack.pop(); @@ -422,8 +454,8 @@ exports.canonicalize = function canonicalize (value, stack, typeHint) { canonicalizedObj = value; break; case 'array': - withStack(value, function () { - canonicalizedObj = value.map(function (item) { + withStack(value, function() { + canonicalizedObj = value.map(function(item) { return exports.canonicalize(item, stack); }); }); @@ -442,10 +474,12 @@ exports.canonicalize = function canonicalize (value, stack, typeHint) { /* falls through */ case 'object': canonicalizedObj = canonicalizedObj || {}; - withStack(value, function () { - Object.keys(value).sort().forEach(function (key) { - canonicalizedObj[key] = exports.canonicalize(value[key], stack); - }); + withStack(value, function() { + Object.keys(value) + .sort() + .forEach(function(key) { + canonicalizedObj[key] = exports.canonicalize(value[key], stack); + }); }); break; case 'date': @@ -473,7 +507,7 @@ exports.canonicalize = function canonicalize (value, stack, typeHint) { * @param {boolean} recursive Whether or not to recurse into subdirectories. * @return {string[]} An array of paths. */ -exports.lookupFiles = function lookupFiles (filepath, extensions, recursive) { +exports.lookupFiles = function lookupFiles(filepath, extensions, recursive) { var files = []; if (!fs.existsSync(filepath)) { @@ -498,7 +532,7 @@ exports.lookupFiles = function lookupFiles (filepath, extensions, recursive) { return; } - fs.readdirSync(filepath).forEach(function (file) { + fs.readdirSync(filepath).forEach(function(file) { file = path.join(filepath, file); try { var stat = fs.statSync(file); @@ -528,8 +562,10 @@ exports.lookupFiles = function lookupFiles (filepath, extensions, recursive) { * @return {Error} */ -exports.undefinedError = function () { - return new Error('Caught undefined error, did you throw without specifying what?'); +exports.undefinedError = function() { + return new Error( + 'Caught undefined error, did you throw without specifying what?' + ); }; /** @@ -539,7 +575,7 @@ exports.undefinedError = function () { * @return {Error} */ -exports.getError = function (err) { +exports.getError = function(err) { return err || exports.undefinedError(); }; @@ -552,9 +588,9 @@ exports.getError = function (err) { * (i.e: strip Mocha and internal node functions from stack trace). * @returns {Function} */ -exports.stackTraceFilter = function () { +exports.stackTraceFilter = function() { // TODO: Replace with `process.browser` - var is = typeof document === 'undefined' ? { node: true } : { browser: true }; + var is = typeof document === 'undefined' ? {node: true} : {browser: true}; var slash = path.sep; var cwd; if (is.node) { @@ -562,30 +598,35 @@ exports.stackTraceFilter = function () { } else { cwd = (typeof location === 'undefined' ? window.location - : location).href.replace(/\/[^/]*$/, '/'); + : location + ).href.replace(/\/[^/]*$/, '/'); slash = '/'; } - function isMochaInternal (line) { - return (~line.indexOf('node_modules' + slash + 'mocha' + slash)) || - (~line.indexOf('node_modules' + slash + 'mocha.js')) || - (~line.indexOf('bower_components' + slash + 'mocha.js')) || - (~line.indexOf(slash + 'mocha.js')); + function isMochaInternal(line) { + return ( + ~line.indexOf('node_modules' + slash + 'mocha' + slash) || + ~line.indexOf('node_modules' + slash + 'mocha.js') || + ~line.indexOf('bower_components' + slash + 'mocha.js') || + ~line.indexOf(slash + 'mocha.js') + ); } - function isNodeInternal (line) { - return (~line.indexOf('(timers.js:')) || - (~line.indexOf('(events.js:')) || - (~line.indexOf('(node.js:')) || - (~line.indexOf('(module.js:')) || - (~line.indexOf('GeneratorFunctionPrototype.next (native)')) || - false; + function isNodeInternal(line) { + return ( + ~line.indexOf('(timers.js:') || + ~line.indexOf('(events.js:') || + ~line.indexOf('(node.js:') || + ~line.indexOf('(module.js:') || + ~line.indexOf('GeneratorFunctionPrototype.next (native)') || + false + ); } - return function (stack) { + return function(stack) { stack = stack.split('\n'); - stack = stack.reduce(function (list, line) { + stack = stack.reduce(function(list, line) { if (isMochaInternal(line)) { return list; } @@ -613,7 +654,7 @@ exports.stackTraceFilter = function () { * @param {*} value * @returns {boolean} Whether or not `value` is a Promise */ -exports.isPromise = function isPromise (value) { +exports.isPromise = function isPromise(value) { return typeof value === 'object' && typeof value.then === 'function'; }; @@ -621,4 +662,4 @@ exports.isPromise = function isPromise (value) { * It's a noop. * @api */ -exports.noop = function () {}; +exports.noop = function() {}; diff --git a/package-scripts.js b/package-scripts.js index ab236890a6..7a1099bc53 100644 --- a/package-scripts.js +++ b/package-scripts.js @@ -9,10 +9,12 @@ const path = require('path'); * @param {string} mochaParams Parameters for the mocha CLI to execute the desired test. * @returns {string} Command string to be executed by nps. */ -function test (testName, mochaParams) { +function test(testName, mochaParams) { const coverageCommand = `nyc --no-clean --report-dir coverage/reports/${testName}`; const mochaCommand = `node ${path.join('bin', 'mocha')}`; // Include 'node' and path.join for Windows compatibility - return `${process.env.COVERAGE ? coverageCommand : ''} ${mochaCommand} ${mochaParams}`.trim(); + return `${ + process.env.COVERAGE ? coverageCommand : '' + } ${mochaCommand} ${mochaParams}`.trim(); } module.exports = { @@ -87,11 +89,17 @@ module.exports = { hiddenFromHelp: true }, unit: { - script: test('unit', '"test/unit/*.spec.js" "test/node-unit/*.spec.js" --growl'), + script: test( + 'unit', + '"test/unit/*.spec.js" "test/node-unit/*.spec.js" --growl' + ), description: 'Run Node.js unit tests' }, integration: { - script: test('integration', '--timeout 5000 --slow 500 "test/integration/*.spec.js"'), + script: test( + 'integration', + '--timeout 5000 --slow 500 "test/integration/*.spec.js"' + ), description: 'Run Node.js integration tests', hiddenFromHelp: true }, @@ -102,33 +110,51 @@ module.exports = { }, compilers: { default: { - script: 'nps test.node.compilers.coffee test.node.compilers.custom test.node.compilers.multiple', + script: + 'nps test.node.compilers.coffee test.node.compilers.custom test.node.compilers.multiple', description: 'Run Node.js --compilers flag tests (deprecated)', hiddenFromHelp: true }, coffee: { - script: test('compilers-coffee', '--compilers coffee:coffee-script/register test/compiler'), - description: 'Run Node.js coffeescript compiler tests using --compilers flag (deprecated)', + script: test( + 'compilers-coffee', + '--compilers coffee:coffee-script/register test/compiler' + ), + description: + 'Run Node.js coffeescript compiler tests using --compilers flag (deprecated)', hiddenFromHelp: true }, custom: { - script: test('compilers-custom', '--compilers foo:./test/compiler-fixtures/foo.fixture test/compiler'), - description: 'Run Node.js custom compiler tests using --compilers flag (deprecated)', + script: test( + 'compilers-custom', + '--compilers foo:./test/compiler-fixtures/foo.fixture test/compiler' + ), + description: + 'Run Node.js custom compiler tests using --compilers flag (deprecated)', hiddenFromHelp: true }, multiple: { - script: test('compilers-multiple', '--compilers coffee:coffee-script/register,foo:./test/compiler-fixtures/foo.fixture test/compiler'), - description: 'Run Node.js multiple compiler tests using--compilers flag (deprecated)', + script: test( + 'compilers-multiple', + '--compilers coffee:coffee-script/register,foo:./test/compiler-fixtures/foo.fixture test/compiler' + ), + description: + 'Run Node.js multiple compiler tests using--compilers flag (deprecated)', hiddenFromHelp: true } }, requires: { - script: test('requires', ['--require coffee-script/register', - '--require test/require/a.js', - '--require test/require/b.coffee', - '--require test/require/c.js', - '--require test/require/d.coffee', - 'test/require/require.spec.js'].join(' ')), + script: test( + 'requires', + [ + '--require coffee-script/register', + '--require test/require/a.js', + '--require test/require/b.coffee', + '--require test/require/c.js', + '--require test/require/d.coffee', + 'test/require/require.spec.js' + ].join(' ') + ), description: 'Run Node.js --require flag tests', hiddenFromHelp: true }, @@ -161,22 +187,34 @@ module.exports = { hiddenFromHelp: true }, bddRequire: { - script: test('only-bdd-require', '--ui qunit test/only/bdd-require.spec'), + script: test( + 'only-bdd-require', + '--ui qunit test/only/bdd-require.spec' + ), description: 'Run Node.js "only" w/ QUnit interface tests', hiddenFromHelp: true }, globalBdd: { - script: test('global-only-bdd', '--ui bdd test/only/global/bdd.spec'), + script: test( + 'global-only-bdd', + '--ui bdd test/only/global/bdd.spec' + ), description: 'Run Node.js "global only" w/ BDD interface tests', hiddenFromHelp: true }, globalTdd: { - script: test('global-only-tdd', '--ui tdd test/only/global/tdd.spec'), + script: test( + 'global-only-tdd', + '--ui tdd test/only/global/tdd.spec' + ), description: 'Run Node.js "global only" w/ TDD interface tests', hiddenFromHelp: true }, globalQunit: { - script: test('global-only-qunit', '--ui qunit test/only/global/qunit.spec'), + script: test( + 'global-only-qunit', + '--ui qunit test/only/global/qunit.spec' + ), description: 'Run Node.js "global only" w/ QUnit interface tests', hiddenFromHelp: true } @@ -184,7 +222,8 @@ module.exports = { }, browser: { default: { - script: 'nps clean build test.browser.unit test.browser.bdd test.browser.tdd test.browser.qunit test.browser.esm', + script: + 'nps clean build test.browser.unit test.browser.bdd test.browser.tdd test.browser.qunit test.browser.esm', description: 'Run browser tests' }, unit: { @@ -231,16 +270,19 @@ module.exports = { }, docs: { default: { - script: 'nps docs.prebuild && bundle exec jekyll build --source ./docs --destination ./docs/_site --config ./docs/_config.yml --safe --drafts && nps docs.postbuild', + script: + 'nps docs.prebuild && bundle exec jekyll build --source ./docs --destination ./docs/_site --config ./docs/_config.yml --safe --drafts && nps docs.postbuild', description: 'Build documentation' }, prebuild: { - script: 'rimraf docs/_dist docs/api && node scripts/docs-update-toc.js && nps docs.api', + script: + 'rimraf docs/_dist docs/api && node scripts/docs-update-toc.js && nps docs.api', description: 'Prepare system for doc building', hiddenFromHelp: true }, postbuild: { - script: 'buildProduction docs/_site/index.html --outroot docs/_dist --canonicalroot https://mochajs.org/ --optimizeimages --svgo --inlinehtmlimage 9400 --inlinehtmlscript 0 --asyncscripts && cp docs/_headers docs/_dist/_headers && node scripts/netlify-headers.js >> docs/_dist/_headers', + script: + 'buildProduction docs/_site/index.html --outroot docs/_dist --canonicalroot https://mochajs.org/ --optimizeimages --svgo --inlinehtmlimage 9400 --inlinehtmlscript 0 --asyncscripts && cp docs/_headers docs/_dist/_headers && node scripts/netlify-headers.js >> docs/_dist/_headers', description: 'Post-process docs after build', hiddenFromHelp: true }, @@ -250,11 +292,13 @@ module.exports = { hiddenFromHelp: true }, watch: { - script: 'nps docs.prewatch && bundle exec jekyll serve --source ./docs --destination ./docs/_site --config ./docs/_config.yml --safe --drafts --watch', + script: + 'nps docs.prewatch && bundle exec jekyll serve --source ./docs --destination ./docs/_site --config ./docs/_config.yml --safe --drafts --watch', description: 'Watch docs for changes & build' }, api: { - script: 'mkdirp docs/api && jsdoc -c jsdoc.conf.json && cp LICENSE docs/api', + script: + 'mkdirp docs/api && jsdoc -c jsdoc.conf.json && cp LICENSE docs/api', description: 'build api docs' } }, diff --git a/scripts/dedefine.js b/scripts/dedefine.js index cd21b623c1..e563c629bf 100644 --- a/scripts/dedefine.js +++ b/scripts/dedefine.js @@ -7,10 +7,9 @@ const through = require('through2'); const defineRx = /typeof\s+define\s*===?\s*['"]function['"]\s*&&\s*(?:define\.amd|typeof\s+define\.amd\s*===?\s*['"]object['"]\s*&&\s*define\.amd)/g; -function createStream () { - return through.obj(function (chunk, enc, next) { - this.push(String(chunk) - .replace(defineRx, 'false')); +function createStream() { + return through.obj(function(chunk, enc, next) { + this.push(String(chunk).replace(defineRx, 'false')); next(); }); } diff --git a/scripts/docs-update-toc.js b/scripts/docs-update-toc.js index 93da9aadca..5deef94c19 100755 --- a/scripts/docs-update-toc.js +++ b/scripts/docs-update-toc.js @@ -16,7 +16,8 @@ const docsFilepath = path.join(__dirname, '..', 'docs', 'index.md'); console.log('Updating TOC...'); -fs.createReadStream(docsFilepath) +fs + .createReadStream(docsFilepath) .on('error', err => { console.log(err); process.exit(1); @@ -24,10 +25,14 @@ fs.createReadStream(docsFilepath) .on('close', () => { console.log('Done.'); }) - .pipe(utils.concat(input => { - const output = toc.insert(String(input), { - bullets: '-', - maxdepth: 2 - }).replace(/\n\n$/, '\n'); - return fs.writeFileSync(docsFilepath, output); - })); + .pipe( + utils.concat(input => { + const output = toc + .insert(String(input), { + bullets: '-', + maxdepth: 2 + }) + .replace(/\n\n$/, '\n'); + return fs.writeFileSync(docsFilepath, output); + }) + ); diff --git a/scripts/netlify-headers.js b/scripts/netlify-headers.js index d551b6374c..c99c868bc1 100644 --- a/scripts/netlify-headers.js +++ b/scripts/netlify-headers.js @@ -2,9 +2,7 @@ const AssetGraph = require('assetgraph'); -const headers = [ - 'Content-Security-Policy' -]; +const headers = ['Content-Security-Policy']; const resourceHintTypeMap = { HtmlPreloadLink: 'preload', @@ -13,8 +11,10 @@ const resourceHintTypeMap = { HtmlDnsPrefetchLink: 'dns-prefetch' }; -function getHeaderForRelation (rel) { - let header = `Link: <${rel.href}>; rel=${resourceHintTypeMap[rel.type]}; as=${rel.as}; type=${rel.to.contentType}`; +function getHeaderForRelation(rel) { + let header = `Link: <${rel.href}>; rel=${resourceHintTypeMap[rel.type]}; as=${ + rel.as + }; type=${rel.to.contentType}`; if (rel.as === 'font') { header = `${header}; crossorigin=anonymous`; @@ -23,24 +23,31 @@ function getHeaderForRelation (rel) { return header; } -new AssetGraph({ root: 'docs/_dist' }) +new AssetGraph({root: 'docs/_dist'}) .loadAssets('*.html') .populate({ - followRelations: { type: 'HtmlAnchor', crossorigin: false } + followRelations: {type: 'HtmlAnchor', crossorigin: false} }) - .queue(function (assetGraph) { - const assets = assetGraph.findAssets({ type: 'Html', isInline: false }); + .queue(function(assetGraph) { + const assets = assetGraph.findAssets({type: 'Html', isInline: false}); const headerMap = {}; - assets.forEach(function (asset) { - const url = '/' + asset.url.replace(assetGraph.root, '').replace(/#.*/, '').replace('index.html', ''); + assets.forEach(function(asset) { + const url = + '/' + + asset.url + .replace(assetGraph.root, '') + .replace(/#.*/, '') + .replace('index.html', ''); if (!headerMap[url]) { headerMap[url] = []; } - headers.forEach(function (header) { - const node = asset.parseTree.querySelector('meta[http-equiv=' + header + ']'); + headers.forEach(function(header) { + const node = asset.parseTree.querySelector( + 'meta[http-equiv=' + header + ']' + ); if (node) { headerMap[url].push(`${header}: ${node.getAttribute('content')}`); @@ -51,9 +58,11 @@ new AssetGraph({ root: 'docs/_dist' }) }); const firstCssRel = asset.outgoingRelations.filter(r => { - return r.type === 'HtmlStyle' && - r.crossorigin === false && - r.href !== undefined; + return ( + r.type === 'HtmlStyle' && + r.crossorigin === false && + r.href !== undefined + ); })[0]; if (firstCssRel) { @@ -62,7 +71,9 @@ new AssetGraph({ root: 'docs/_dist' }) headerMap[url].push(header); } - const resourceHintRelations = asset.outgoingRelations.filter(r => ['HtmlPreloadLink', 'HtmlPrefetchLink'].includes(r.type)); + const resourceHintRelations = asset.outgoingRelations.filter(r => + ['HtmlPreloadLink', 'HtmlPrefetchLink'].includes(r.type) + ); resourceHintRelations.forEach(rel => { headerMap[url].push(getHeaderForRelation(rel)); @@ -70,7 +81,9 @@ new AssetGraph({ root: 'docs/_dist' }) rel.detach(); }); - const preconnectRelations = asset.outgoingRelations.filter(r => ['HtmlPreconnectLink'].includes(r.type)); + const preconnectRelations = asset.outgoingRelations.filter(r => + ['HtmlPreconnectLink'].includes(r.type) + ); preconnectRelations.forEach(rel => { let header = `Link: <${rel.href}>; rel=preconnect`; @@ -83,17 +96,17 @@ new AssetGraph({ root: 'docs/_dist' }) console.log('\n## Autogenerated headers:\n'); - Object.keys(headerMap).forEach(function (url) { + Object.keys(headerMap).forEach(function(url) { console.log(url); const httpHeaders = headerMap[url]; - httpHeaders.forEach(function (header) { + httpHeaders.forEach(function(header) { console.log(` ${header}`); }); console.log(''); }); }) - .writeAssetsToDisc({ isLoaded: true }) + .writeAssetsToDisc({isLoaded: true}) .run(); diff --git a/test/browser-specific/esm.spec.js b/test/browser-specific/esm.spec.js index d7460f8090..2af61d3135 100644 --- a/test/browser-specific/esm.spec.js +++ b/test/browser-specific/esm.spec.js @@ -1,5 +1,5 @@ 'use strict'; -it('should register a global if it did not fail', function () { +it('should register a global if it did not fail', function() { expect(window.MOCHA_IS_OK).to.be.ok(); }); diff --git a/test/browser/array.spec.js b/test/browser/array.spec.js index b831f61717..bd44d4b6f4 100644 --- a/test/browser/array.spec.js +++ b/test/browser/array.spec.js @@ -1,8 +1,8 @@ 'use strict'; -describe('Array', function () { - describe('#push()', function () { - it('should append a value', function () { +describe('Array', function() { + describe('#push()', function() { + it('should append a value', function() { var arr = []; arr.push('foo'); arr.push('bar'); @@ -12,7 +12,7 @@ describe('Array', function () { assert(arr[2] === 'baz'); }); - it('should return the length', function () { + it('should return the length', function() { var arr = []; assert(arr.push('foo') === 1); assert(arr.push('bar') === 2); @@ -21,16 +21,16 @@ describe('Array', function () { }); }); -describe('Array', function () { - describe('#pop()', function () { - it('should remove and return the last value with expected error', function () { +describe('Array', function() { + describe('#pop()', function() { + it('should remove and return the last value with expected error', function() { var arr = [1, 2, 3]; assert(arr.pop() === 3); assert(arr.pop() === 2); assert(arr.pop() === -1); }); - it('should adjust .length', function () { + it('should adjust .length', function() { var arr = [1, 2, 3]; arr.pop(); assert(arr.length === 2); diff --git a/test/browser/grep.spec.js b/test/browser/grep.spec.js index 6c5a83aeb5..45041a7cda 100644 --- a/test/browser/grep.spec.js +++ b/test/browser/grep.spec.js @@ -1,110 +1,110 @@ 'use strict'; // numbers -describe('21', function () { - it('1', function () { +describe('21', function() { + it('1', function() { assert(true); }); - it('2', function () { + it('2', function() { assert(true); }); }); // symbols -describe('@Array', function () { - it('.pop()', function () { +describe('@Array', function() { + it('.pop()', function() { assert(true); }); - it('.push()', function () { + it('.push()', function() { assert(true); }); - it('.length', function () { + it('.length', function() { assert(true); }); }); -describe('@Function', function () { - it('.call()', function () { +describe('@Function', function() { + it('.call()', function() { assert(true); }); - it('.apply()', function () { + it('.apply()', function() { assert(true); }); - it('.length', function () { + it('.length', function() { assert(true); }); - it('.name', function () { + it('.name', function() { assert(true); }); - it('.prototype', function () { + it('.prototype', function() { assert(true); }); }); // url with hashtags -describe('#Services', function () { - describe('#http', function () { - it('.createClient()', function () { +describe('#Services', function() { + describe('#http', function() { + it('.createClient()', function() { assert(true); }); - it('.Server()', function () { + it('.Server()', function() { assert(true); }); }); - describe('#crypto', function () { - it('.randomBytes()', function () { + describe('#crypto', function() { + it('.randomBytes()', function() { assert(true); }); - it('.Hmac()', function () { + it('.Hmac()', function() { assert(true); }); }); }); // Uppercase -describe('CONSTANTS', function () { - it('.STATUS_CODES', function () { +describe('CONSTANTS', function() { + it('.STATUS_CODES', function() { assert(true); }); }); // Dates -describe('Date:', function () { - it('01/02/2015', function () { +describe('Date:', function() { + it('01/02/2015', function() { assert(true); }); - it('01/03/2015', function () { + it('01/03/2015', function() { assert(true); }); - it('01/06/2015', function () { + it('01/06/2015', function() { assert(true); }); }); // etc.. -describe('booking/summary', function () { - it('should be run last', function () { +describe('booking/summary', function() { + it('should be run last', function() { assert(true); }); }); -describe('component/booking/summary', function () { - it('should be run second', function () { +describe('component/booking/summary', function() { + it('should be run second', function() { assert(true); }); }); -describe('component/booking/intro', function () { - it('should be run first', function () { +describe('component/booking/intro', function() { + it('should be run first', function() { assert(true); }); }); -describe('contains numbers', function () { - it('should run if the number 92 matching', function () { +describe('contains numbers', function() { + it('should run if the number 92 matching', function() { assert(true); }); - it('should run if the number 8 matching', function () { + it('should run if the number 8 matching', function() { assert(true); }); }); diff --git a/test/browser/large.spec.js b/test/browser/large.spec.js index 7dfa62f2a2..3b26cc2860 100644 --- a/test/browser/large.spec.js +++ b/test/browser/large.spec.js @@ -2,19 +2,19 @@ var n = 30; while (n--) { - describe('Array ' + n, function () { + describe('Array ' + n, function() { var arr; - beforeEach(function () { + beforeEach(function() { arr = [1, 2, 3]; }); - describe('#indexOf()', function () { - it('should return -1 when the value is not present', function () { + describe('#indexOf()', function() { + it('should return -1 when the value is not present', function() { assert(arr.indexOf(5) === -1); }); - it('should return the correct index when the value is present', function (done) { + it('should return the correct index when the value is present', function(done) { assert(arr.indexOf(1) === 0); assert(arr.indexOf(2) === 1); done(); @@ -23,16 +23,16 @@ while (n--) { }); } -describe('something', function () { - it('should provide a useful error', function (done) { - setTimeout(function () { +describe('something', function() { + it('should provide a useful error', function(done) { + setTimeout(function() { throw new Error('boom'); }, 1); }); - it('should provide an even better error on phantomjs', function (done) { - setTimeout(function () { - var AssertionError = function (message, actual, expected) { + it('should provide an even better error on phantomjs', function(done) { + setTimeout(function() { + var AssertionError = function(message, actual, expected) { this.message = message; this.actual = actual; this.expected = expected; @@ -42,7 +42,9 @@ describe('something', function () { AssertionError.prototype.name = 'AssertionError'; AssertionError.prototype.constructor = AssertionError; - mocha.throwError(new AssertionError('kabooom', 'text with a typo', 'text without a typo')); + mocha.throwError( + new AssertionError('kabooom', 'text with a typo', 'text without a typo') + ); done(); }, 1); }); diff --git a/test/browser/multiple-done.spec.js b/test/browser/multiple-done.spec.js index ddb536735e..2a84e777e9 100644 --- a/test/browser/multiple-done.spec.js +++ b/test/browser/multiple-done.spec.js @@ -1,17 +1,17 @@ 'use strict'; -describe('Multiple Done calls', function () { - it('should report an error if done was called more than once', function (done) { +describe('Multiple Done calls', function() { + it('should report an error if done was called more than once', function(done) { done(); done(); }); - it('should report an error if an exception happened async after done was called', function (done) { + it('should report an error if an exception happened async after done was called', function(done) { done(); setTimeout(done, 50); }); - it('should report an error if an exception happened after done was called', function (done) { + it('should report an error if an exception happened after done was called', function(done) { done(); throw new Error('thrown error'); }); diff --git a/test/browser/opts.spec.js b/test/browser/opts.spec.js index 7b93f22615..78e6fbd333 100644 --- a/test/browser/opts.spec.js +++ b/test/browser/opts.spec.js @@ -1,7 +1,7 @@ 'use strict'; -describe('Options', function () { - it('should set timeout value', function () { +describe('Options', function() { + it('should set timeout value', function() { assert(this.test._timeout === 1500); }); }); diff --git a/test/browser/stack-trace.spec.js b/test/browser/stack-trace.spec.js index a4801bf32f..b10acf604b 100644 --- a/test/browser/stack-trace.spec.js +++ b/test/browser/stack-trace.spec.js @@ -1,6 +1,6 @@ 'use strict'; -describe('Stack trace', function () { - it('should prettify the stack-trace', function () { +describe('Stack trace', function() { + it('should prettify the stack-trace', function() { var err = new Error(); // We do this fake stack-trace because we under development, // and our root isn't `node_modules`, `bower` or `components` diff --git a/test/browser/ui.spec.js b/test/browser/ui.spec.js index 9b2addc92a..4247c30302 100644 --- a/test/browser/ui.spec.js +++ b/test/browser/ui.spec.js @@ -3,31 +3,29 @@ // test titles containing regex-conflicting characters // leading $ -describe('$.jQuery', function () { +describe('$.jQuery', function() { // parens - describe('.on()', function () { - it('should set an event', function () { + describe('.on()', function() { + it('should set an event', function() { assert(true); }); }); - describe('.off()', function () { - it('should remove an event', function () { - - }); + describe('.off()', function() { + it('should remove an event', function() {}); }); }); // another generic describe block to verify it is absent // when grepping on $.jQuery -describe('@Array', function () { - it('.pop()', function () { +describe('@Array', function() { + it('.pop()', function() { assert(true); }); - it('.push()', function () { + it('.push()', function() { assert(true); }); - it('.length', function () { + it('.length', function() { assert(true); }); }); diff --git a/test/bundle/amd.spec.js b/test/bundle/amd.spec.js index e42d3dab0b..bb616f02a7 100644 --- a/test/bundle/amd.spec.js +++ b/test/bundle/amd.spec.js @@ -3,10 +3,12 @@ var path = require('path'); var fs = require('fs'); -it('should build a non-broken bundle for AMD', function (done) { +it('should build a non-broken bundle for AMD', function(done) { var bundle = path.join(process.cwd(), 'mocha.js'); - fs.readFile(bundle, 'utf8', function (err, content) { - if (err) { return done(err); } + fs.readFile(bundle, 'utf8', function(err, content) { + if (err) { + return done(err); + } expect(content).not.to.match(/define.amd/); done(); diff --git a/test/integration/compiler-globbing.spec.js b/test/integration/compiler-globbing.spec.js index ee0a7237a5..c459a95bcf 100644 --- a/test/integration/compiler-globbing.spec.js +++ b/test/integration/compiler-globbing.spec.js @@ -4,21 +4,31 @@ var expect = require('expect.js'); var exec = require('child_process').exec; var path = require('path'); -describe('globbing like --compilers', function () { - it('should find a file of each type', function (done) { - exec('"' + process.execPath + '" "' + path.join('bin', 'mocha') + '" -R json --require coffee-script/register --require test/compiler-fixtures/foo.fixture "test/compiler/*.@(coffee|foo)"', { cwd: path.join(__dirname, '..', '..') }, function (error, stdout) { - if (error && !stdout) { return done(error); } - var results = JSON.parse(stdout); - expect(results).to.have.property('tests'); - var titles = []; - for (var index = 0; index < results.tests.length; index += 1) { - expect(results.tests[index]).to.have.property('fullTitle'); - titles.push(results.tests[index].fullTitle); +describe('globbing like --compilers', function() { + it('should find a file of each type', function(done) { + exec( + '"' + + process.execPath + + '" "' + + path.join('bin', 'mocha') + + '" -R json --require coffee-script/register --require test/compiler-fixtures/foo.fixture "test/compiler/*.@(coffee|foo)"', + {cwd: path.join(__dirname, '..', '..')}, + function(error, stdout) { + if (error && !stdout) { + return done(error); + } + var results = JSON.parse(stdout); + expect(results).to.have.property('tests'); + var titles = []; + for (var index = 0; index < results.tests.length; index += 1) { + expect(results.tests[index]).to.have.property('fullTitle'); + titles.push(results.tests[index].fullTitle); + } + expect(titles).to.contain('coffeescript should work'); + expect(titles).to.contain('custom compiler should work'); + expect(titles).to.have.length(2); + done(); } - expect(titles).to.contain('coffeescript should work'); - expect(titles).to.contain('custom compiler should work'); - expect(titles).to.have.length(2); - done(); - }); + ); }); }); diff --git a/test/integration/diffs.spec.js b/test/integration/diffs.spec.js index 88b6f69e0d..9282fc9756 100644 --- a/test/integration/diffs.spec.js +++ b/test/integration/diffs.spec.js @@ -6,20 +6,28 @@ var run = helpers.runMocha; var fs = require('fs'); var getDiffs = helpers.getDiffs; -function getExpectedOutput () { - var output = fs.readFileSync('test/integration/fixtures/diffs/output', 'UTF8').replace(/\r\n/g, '\n'); +function getExpectedOutput() { + var output = fs + .readFileSync('test/integration/fixtures/diffs/output', 'UTF8') + .replace(/\r\n/g, '\n'); // Diffs are delimited in file by "// DIFF" - return output.split(/\s*\/\/ DIFF/).slice(1).map(function (diff) { - return diff.split('\n').filter(Boolean).join('\n'); - }); + return output + .split(/\s*\/\/ DIFF/) + .slice(1) + .map(function(diff) { + return diff + .split('\n') + .filter(Boolean) + .join('\n'); + }); } -describe('diffs', function () { +describe('diffs', function() { var diffs, expected; - before(function (done) { - run('diffs/diffs.fixture.js', ['-C'], function (err, res) { + before(function(done) { + run('diffs/diffs.fixture.js', ['-C'], function(err, res) { expected = getExpectedOutput(); diffs = getDiffs(res.output.replace(/\r\n/g, '\n')); done(err); @@ -38,8 +46,8 @@ describe('diffs', function () { 'should work with objects', 'should show value diffs and not be affected by commas', 'should display diff by data and not like an objects' - ].forEach(function (title, i) { - it(title, function () { + ].forEach(function(title, i) { + it(title, function() { assert.equal(diffs[i], expected[i]); }); }); diff --git a/test/integration/fixtures/glob/glob.spec.js b/test/integration/fixtures/glob/glob.spec.js index 235c2f8417..c6c3d26a69 100644 --- a/test/integration/fixtures/glob/glob.spec.js +++ b/test/integration/fixtures/glob/glob.spec.js @@ -1,7 +1,7 @@ 'use strict'; -describe('globbing test', function () { - it('should find this test', function () { +describe('globbing test', function() { + it('should find this test', function() { // see test/integration/glob.spec.js for details }); }); diff --git a/test/integration/fixtures/glob/nested/glob.spec.js b/test/integration/fixtures/glob/nested/glob.spec.js index 235c2f8417..c6c3d26a69 100644 --- a/test/integration/fixtures/glob/nested/glob.spec.js +++ b/test/integration/fixtures/glob/nested/glob.spec.js @@ -1,7 +1,7 @@ 'use strict'; -describe('globbing test', function () { - it('should find this test', function () { +describe('globbing test', function() { + it('should find this test', function() { // see test/integration/glob.spec.js for details }); }); diff --git a/test/integration/fixtures/options/forbid-only/only-suite.js b/test/integration/fixtures/options/forbid-only/only-suite.js index ba15a5a2df..372cefbd9f 100644 --- a/test/integration/fixtures/options/forbid-only/only-suite.js +++ b/test/integration/fixtures/options/forbid-only/only-suite.js @@ -1,5 +1,5 @@ 'use strict'; -describe.only('forbid only - suite marked with only', function () { - it('test1', function () {}); +describe.only('forbid only - suite marked with only', function() { + it('test1', function() {}); }); diff --git a/test/integration/fixtures/options/forbid-only/only.js b/test/integration/fixtures/options/forbid-only/only.js index c09e804126..1019808760 100644 --- a/test/integration/fixtures/options/forbid-only/only.js +++ b/test/integration/fixtures/options/forbid-only/only.js @@ -1,7 +1,7 @@ 'use strict'; -describe('forbid only - test marked with only', function () { - it('test1', function () {}); - it.only('test2', function () {}); - it('test3', function () {}); +describe('forbid only - test marked with only', function() { + it('test1', function() {}); + it.only('test2', function() {}); + it('test3', function() {}); }); diff --git a/test/integration/fixtures/options/forbid-only/passed.js b/test/integration/fixtures/options/forbid-only/passed.js index 6c4d4ac1d4..afa8de7b53 100644 --- a/test/integration/fixtures/options/forbid-only/passed.js +++ b/test/integration/fixtures/options/forbid-only/passed.js @@ -1,7 +1,7 @@ 'use strict'; -describe('forbid only - `.only` is not used', function () { - it('test1', function () {}); - it('test2', function () {}); - it('test3', function () {}); +describe('forbid only - `.only` is not used', function() { + it('test1', function() {}); + it('test2', function() {}); + it('test3', function() {}); }); diff --git a/test/integration/fixtures/options/forbid-pending/before-this.skip.js b/test/integration/fixtures/options/forbid-pending/before-this.skip.js index 7c329dff4a..2147afb77e 100644 --- a/test/integration/fixtures/options/forbid-pending/before-this.skip.js +++ b/test/integration/fixtures/options/forbid-pending/before-this.skip.js @@ -1,6 +1,8 @@ 'use strict'; -describe('forbid pending - before calls `skip()`', function () { - it('test', function () {}); - before(function () { this.skip(); }); +describe('forbid pending - before calls `skip()`', function() { + it('test', function() {}); + before(function() { + this.skip(); + }); }); diff --git a/test/integration/fixtures/options/forbid-pending/beforeEach-this.skip.js b/test/integration/fixtures/options/forbid-pending/beforeEach-this.skip.js index 58fa1fe8a3..d9051f8b17 100644 --- a/test/integration/fixtures/options/forbid-pending/beforeEach-this.skip.js +++ b/test/integration/fixtures/options/forbid-pending/beforeEach-this.skip.js @@ -1,6 +1,8 @@ 'use strict'; -describe('forbid pending - beforeEach calls `skip()`', function () { - it('test', function () {}); - beforeEach(function () { this.skip(); }); +describe('forbid pending - beforeEach calls `skip()`', function() { + it('test', function() {}); + beforeEach(function() { + this.skip(); + }); }); diff --git a/test/integration/fixtures/options/forbid-pending/passed.js b/test/integration/fixtures/options/forbid-pending/passed.js index cd12668f4d..27291cce17 100644 --- a/test/integration/fixtures/options/forbid-pending/passed.js +++ b/test/integration/fixtures/options/forbid-pending/passed.js @@ -1,7 +1,7 @@ 'use strict'; -describe('forbid pending - all test pass', function () { - it('test1', function () {}); - it('test2', function () {}); - it('test3', function () {}); +describe('forbid pending - all test pass', function() { + it('test1', function() {}); + it('test2', function() {}); + it('test3', function() {}); }); diff --git a/test/integration/fixtures/options/forbid-pending/pending.js b/test/integration/fixtures/options/forbid-pending/pending.js index 96abd0bf47..81f6544831 100644 --- a/test/integration/fixtures/options/forbid-pending/pending.js +++ b/test/integration/fixtures/options/forbid-pending/pending.js @@ -1,7 +1,7 @@ 'use strict'; -describe('forbid pending - test without function', function () { - it('test1', function () {}); +describe('forbid pending - test without function', function() { + it('test1', function() {}); it('test2'); - it('test3', function () {}); + it('test3', function() {}); }); diff --git a/test/integration/fixtures/options/forbid-pending/skip-suite.js b/test/integration/fixtures/options/forbid-pending/skip-suite.js index fe0a4578f0..628dc3a853 100644 --- a/test/integration/fixtures/options/forbid-pending/skip-suite.js +++ b/test/integration/fixtures/options/forbid-pending/skip-suite.js @@ -1,5 +1,5 @@ 'use strict'; -describe.skip('forbid pending - suite marked with skip', function () { - it('test1', function () {}); +describe.skip('forbid pending - suite marked with skip', function() { + it('test1', function() {}); }); diff --git a/test/integration/fixtures/options/forbid-pending/skip.js b/test/integration/fixtures/options/forbid-pending/skip.js index c6fd31d303..8b4fcd91c4 100644 --- a/test/integration/fixtures/options/forbid-pending/skip.js +++ b/test/integration/fixtures/options/forbid-pending/skip.js @@ -1,7 +1,7 @@ 'use strict'; -describe('forbid pending - test marked with skip', function () { - it('test1', function () {}); - it.skip('test2', function () {}); - it('test3', function () {}); +describe('forbid pending - test marked with skip', function() { + it('test1', function() {}); + it.skip('test2', function() {}); + it('test3', function() {}); }); diff --git a/test/integration/fixtures/options/forbid-pending/this.skip.js b/test/integration/fixtures/options/forbid-pending/this.skip.js index a920813250..2f76a6fdad 100644 --- a/test/integration/fixtures/options/forbid-pending/this.skip.js +++ b/test/integration/fixtures/options/forbid-pending/this.skip.js @@ -1,7 +1,9 @@ 'use strict'; -describe('forbid pending - test calls `skip()`', function () { - it('test1', function () {}); - it('test2', function () { this.skip(); }); - it('test3', function () {}); +describe('forbid pending - test calls `skip()`', function() { + it('test1', function() {}); + it('test2', function() { + this.skip(); + }); + it('test3', function() {}); }); diff --git a/test/integration/fixtures/regression/1794/simple-ui.js b/test/integration/fixtures/regression/1794/simple-ui.js index 5cfde0465f..b27c623003 100644 --- a/test/integration/fixtures/regression/1794/simple-ui.js +++ b/test/integration/fixtures/regression/1794/simple-ui.js @@ -7,8 +7,8 @@ var Test = require(path + 'test'); /** * A simple UI that only exposes a single function: test */ -module.exports = Mocha.interfaces['simple-ui'] = function (suite) { - suite.on('pre-require', function (context, file, mocha) { +module.exports = Mocha.interfaces['simple-ui'] = function(suite) { + suite.on('pre-require', function(context, file, mocha) { var common = require(path + 'interfaces/common')([suite], context); context.run = mocha.options.delay && common.runWithSuite(suite); @@ -17,7 +17,7 @@ module.exports = Mocha.interfaces['simple-ui'] = function (suite) { * Describes a specification or test-case with the given `title` * and callback `fn` acting as a thunk. */ - context.test = function (title, fn) { + context.test = function(title, fn) { var test = new Test(title, fn); test.file = file; suite.addTest(test); diff --git a/test/integration/fixtures/simple-reporter.js b/test/integration/fixtures/simple-reporter.js index d172b2ae66..d066a84304 100644 --- a/test/integration/fixtures/simple-reporter.js +++ b/test/integration/fixtures/simple-reporter.js @@ -3,26 +3,26 @@ var baseReporter = require('../../../lib/reporters/base'); module.exports = simplereporter; -function simplereporter (runner) { +function simplereporter(runner) { baseReporter.call(this, runner); - runner.on('suite', function (suite) { - console.log('on(\'suite\') called'); + runner.on('suite', function(suite) { + console.log("on('suite') called"); }); - runner.on('fail', function (test, err) { - console.log('on(\'fail\') called'); + runner.on('fail', function(test, err) { + console.log("on('fail') called"); }); - runner.on('pass', function (test) { - console.log('on(\'pass\') called'); + runner.on('pass', function(test) { + console.log("on('pass') called"); }); - runner.on('test end', function (test, err) { - console.log('on(\'test end\') called'); + runner.on('test end', function(test, err) { + console.log("on('test end') called"); }); - runner.on('end', function () { - console.log('on(\'end\') called'); + runner.on('end', function() { + console.log("on('end') called"); }); } diff --git a/test/integration/glob.spec.js b/test/integration/glob.spec.js index 4d1c5a52f4..ebcd6353a6 100644 --- a/test/integration/glob.spec.js +++ b/test/integration/glob.spec.js @@ -6,96 +6,172 @@ var path = require('path'); var node = '"' + process.execPath + '"'; -describe('globbing', function () { - describe('by the shell', function () { - it('should find the first level test', function (done) { - testGlob.shouldSucceed('./*.js', function (results) { - expect(results.stdout).to.contain('["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,'); - }, done); +describe('globbing', function() { + describe('by the shell', function() { + it('should find the first level test', function(done) { + testGlob.shouldSucceed( + './*.js', + function(results) { + expect(results.stdout).to.contain( + '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,' + ); + }, + done + ); }); - it('should not find a non-matching pattern', function (done) { - testGlob.shouldFail('./*-none.js', function (results) { - expect(results.stderr).to.contain('Could not find any test files matching pattern'); - }, done); + it('should not find a non-matching pattern', function(done) { + testGlob.shouldFail( + './*-none.js', + function(results) { + expect(results.stderr).to.contain( + 'Could not find any test files matching pattern' + ); + }, + done + ); }); - it('should handle both matching and non-matching patterns in the same command', function (done) { - testGlob.shouldSucceed('./*.js ./*-none.js', function (results) { - expect(results.stdout).to.contain('["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,'); - expect(results.stderr).to.contain('Could not find any test files matching pattern'); - }, done); + it('should handle both matching and non-matching patterns in the same command', function(done) { + testGlob.shouldSucceed( + './*.js ./*-none.js', + function(results) { + expect(results.stdout).to.contain( + '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,' + ); + expect(results.stderr).to.contain( + 'Could not find any test files matching pattern' + ); + }, + done + ); }); }); - describe('by Mocha', function () { - it('should find the first level test', function (done) { - testGlob.shouldSucceed('"./*.js"', function (results) { - expect(results.stdout).to.contain('["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,'); - }, done); + describe('by Mocha', function() { + it('should find the first level test', function(done) { + testGlob.shouldSucceed( + '"./*.js"', + function(results) { + expect(results.stdout).to.contain( + '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,' + ); + }, + done + ); }); - it('should not find a non-matching pattern', function (done) { - testGlob.shouldFail('"./*-none.js"', function (results) { - expect(results.stderr).to.contain('Could not find any test files matching pattern'); - }, done); + it('should not find a non-matching pattern', function(done) { + testGlob.shouldFail( + '"./*-none.js"', + function(results) { + expect(results.stderr).to.contain( + 'Could not find any test files matching pattern' + ); + }, + done + ); }); - it('should handle both matching and non-matching patterns in the same command', function (done) { - testGlob.shouldSucceed('"./*.js" "./*-none.js"', function (results) { - expect(results.stdout).to.contain('["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,'); - expect(results.stderr).to.contain('Could not find any test files matching pattern'); - }, done); + it('should handle both matching and non-matching patterns in the same command', function(done) { + testGlob.shouldSucceed( + '"./*.js" "./*-none.js"', + function(results) { + expect(results.stdout).to.contain( + '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,' + ); + expect(results.stderr).to.contain( + 'Could not find any test files matching pattern' + ); + }, + done + ); }); - describe('double-starred', function () { - it('should find the tests on multiple levels', function (done) { - testGlob.shouldSucceed('"./**/*.js"', function (results) { - expect(results.stdout).to.contain('["end",{"suites":2,"tests":2,"passes":2,"pending":0,"failures":0,'); - }, done); + describe('double-starred', function() { + it('should find the tests on multiple levels', function(done) { + testGlob.shouldSucceed( + '"./**/*.js"', + function(results) { + expect(results.stdout).to.contain( + '["end",{"suites":2,"tests":2,"passes":2,"pending":0,"failures":0,' + ); + }, + done + ); }); - it('should not find a non-matching pattern', function (done) { - testGlob.shouldFail('"./**/*-none.js"', function (results) { - expect(results.stderr).to.contain('Could not find any test files matching pattern'); - }, done); + it('should not find a non-matching pattern', function(done) { + testGlob.shouldFail( + '"./**/*-none.js"', + function(results) { + expect(results.stderr).to.contain( + 'Could not find any test files matching pattern' + ); + }, + done + ); }); - it('should handle both matching and non-matching patterns in the same command', function (done) { - testGlob.shouldSucceed('"./**/*.js" "./**/*-none.js"', function (results) { - expect(results.stdout).to.contain('["end",{"suites":2,"tests":2,"passes":2,"pending":0,"failures":0,'); - expect(results.stderr).to.contain('Could not find any test files matching pattern'); - }, done); + it('should handle both matching and non-matching patterns in the same command', function(done) { + testGlob.shouldSucceed( + '"./**/*.js" "./**/*-none.js"', + function(results) { + expect(results.stdout).to.contain( + '["end",{"suites":2,"tests":2,"passes":2,"pending":0,"failures":0,' + ); + expect(results.stderr).to.contain( + 'Could not find any test files matching pattern' + ); + }, + done + ); }); }); }); }); var testGlob = { - shouldSucceed: execMochaWith(function shouldNotError (error) { if (error) { throw error; } }), + shouldSucceed: execMochaWith(function shouldNotError(error) { + if (error) { + throw error; + } + }), - shouldFail: execMochaWith(function shouldFailWithStderr (error, stderr) { expect(error && error.message).to.contain(stderr); }) + shouldFail: execMochaWith(function shouldFailWithStderr(error, stderr) { + expect(error && error.message).to.contain(stderr); + }) }; -var isFlakeyNode = (function () { +var isFlakeyNode = (function() { var version = process.versions.node.split('.'); - return version[0] === '0' && version[1] === '10' && process.platform === 'win32'; -}()); + return ( + version[0] === '0' && version[1] === '10' && process.platform === 'win32' + ); +})(); -function execMochaWith (validate) { - return function execMocha (glob, assertOn, done) { - exec(node + ' "' + path.join('..', '..', '..', '..', 'bin', 'mocha') + '" -R json-stream ' + glob, { cwd: path.join(__dirname, 'fixtures', 'glob') }, function (error, stdout, stderr) { - try { - validate(error, stderr); - if (isFlakeyNode && error && (stderr === '')) { - execMocha(glob, assertOn, done); - } else { - assertOn({ stdout: stdout, stderr: stderr }); - done(); +function execMochaWith(validate) { + return function execMocha(glob, assertOn, done) { + exec( + node + + ' "' + + path.join('..', '..', '..', '..', 'bin', 'mocha') + + '" -R json-stream ' + + glob, + {cwd: path.join(__dirname, 'fixtures', 'glob')}, + function(error, stdout, stderr) { + try { + validate(error, stderr); + if (isFlakeyNode && error && stderr === '') { + execMocha(glob, assertOn, done); + } else { + assertOn({stdout: stdout, stderr: stderr}); + done(); + } + } catch (assertion) { + done(assertion); } - } catch (assertion) { - done(assertion); } - }); + ); }; } diff --git a/test/integration/helpers.js b/test/integration/helpers.js index 09ca5deac9..c0f61f7487 100644 --- a/test/integration/helpers.js +++ b/test/integration/helpers.js @@ -25,13 +25,13 @@ module.exports = { * @param {Array} args - Extra args to mocha executable * @param {Function} done - Callback */ - runMocha: function (fixturePath, args, done) { + runMocha: function(fixturePath, args, done) { var path; path = resolveFixturePath(fixturePath); args = args || []; - invokeMocha(args.concat(['-C', path]), function (err, res) { + invokeMocha(args.concat(['-C', path]), function(err, res) { if (err) { return done(err); } @@ -48,13 +48,16 @@ module.exports = { * @param {string[]} args - Array of args * @param {Function} fn - Callback */ - runMochaJSON: function (fixturePath, args, fn) { + runMochaJSON: function(fixturePath, args, fn) { var path; path = resolveFixturePath(fixturePath); args = args || []; - return invokeMocha(args.concat(['--reporter', 'json', path]), function (err, res) { + return invokeMocha(args.concat(['--reporter', 'json', path]), function( + err, + res + ) { if (err) return fn(err); try { @@ -75,11 +78,11 @@ module.exports = { * @param {string} output * returns {string[]} */ - getDiffs: function (output) { + getDiffs: function(output) { var diffs, i, inDiff, inStackTrace; diffs = []; - output.split('\n').forEach(function (line) { + output.split('\n').forEach(function(line) { if (line.match(/^\s{2}\d+\)/)) { // New spec, e.g. "1) spec title" diffs.push([]); @@ -89,7 +92,6 @@ module.exports = { } else if (!diffs.length || inStackTrace) { // Haven't encountered a spec yet // or we're in the middle of a stack trace - } else if (line.indexOf('+ expected - actual') !== -1) { inDiff = true; } else if (line.match(/at Context/)) { @@ -102,7 +104,7 @@ module.exports = { }); // Ignore empty lines before/after diff - return diffs.map(function (diff) { + return diffs.map(function(diff) { return diff.slice(1, -3).join('\n'); }); }, @@ -137,14 +139,14 @@ module.exports = { resolveFixturePath: resolveFixturePath }; -function invokeMocha (args, fn, cwd) { +function invokeMocha(args, fn, cwd) { var output, mocha, listener; output = ''; args = [path.join(__dirname, '..', '..', 'bin', 'mocha')].concat(args); - mocha = spawn(process.execPath, args, { cwd: cwd }); + mocha = spawn(process.execPath, args, {cwd: cwd}); - listener = function (data) { + listener = function(data) { output += data; }; @@ -152,7 +154,7 @@ function invokeMocha (args, fn, cwd) { mocha.stderr.on('data', listener); mocha.on('error', fn); - mocha.on('close', function (code) { + mocha.on('close', function(code) { fn(null, { output: output.split('\n').join('\n'), code: code @@ -162,17 +164,17 @@ function invokeMocha (args, fn, cwd) { return mocha; } -function resolveFixturePath (fixture) { +function resolveFixturePath(fixture) { return path.join('./test/integration/fixtures', fixture); } -function getSummary (res) { - return ['passing', 'pending', 'failing'].reduce(function (summary, type) { +function getSummary(res) { + return ['passing', 'pending', 'failing'].reduce(function(summary, type) { var pattern, match; pattern = new RegExp(' (\\d+) ' + type + '\\s'); match = pattern.exec(res.output); - summary[type] = (match) ? parseInt(match, 10) : 0; + summary[type] = match ? parseInt(match, 10) : 0; return summary; }, res); diff --git a/test/integration/hook-err.spec.js b/test/integration/hook-err.spec.js index 10d0e97c4a..493e91004c 100644 --- a/test/integration/hook-err.spec.js +++ b/test/integration/hook-err.spec.js @@ -5,193 +5,159 @@ var runMocha = require('./helpers').runMocha; var splitRegExp = require('./helpers').splitRegExp; var bang = require('../../lib/reporters/base').symbols.bang; -describe('hook error handling', function () { +describe('hook error handling', function() { var lines; - describe('before hook error', function () { + describe('before hook error', function() { before(run('hooks/before-hook-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - ['before', bang + 'test 3'] - ); + it('should verify results', function() { + assert.deepEqual(lines, ['before', bang + 'test 3']); }); }); - describe('before hook error tip', function () { + describe('before hook error tip', function() { before(run('hooks/before-hook-error-tip.fixture.js', onlyErrorTitle())); - it('should verify results', function () { - assert.deepEqual( - lines, - ['1) spec 2', '"before all" hook:'] - ); + it('should verify results', function() { + assert.deepEqual(lines, ['1) spec 2', '"before all" hook:']); }); }); - describe('before each hook error', function () { + describe('before each hook error', function() { before(run('hooks/beforeEach-hook-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - ['before', bang + 'test 3'] - ); + it('should verify results', function() { + assert.deepEqual(lines, ['before', bang + 'test 3']); }); }); - describe('after hook error', function () { + describe('after hook error', function() { before(run('hooks/after-hook-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - ['test 1', 'test 2', 'after', bang + 'test 3'] - ); + it('should verify results', function() { + assert.deepEqual(lines, ['test 1', 'test 2', 'after', bang + 'test 3']); }); }); - describe('after each hook error', function () { + describe('after each hook error', function() { before(run('hooks/afterEach-hook-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - ['test 1', 'after', bang + 'test 3'] - ); + it('should verify results', function() { + assert.deepEqual(lines, ['test 1', 'after', bang + 'test 3']); }); }); - describe('multiple hook errors', function () { + describe('multiple hook errors', function() { before(run('hooks/multiple-hook-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - [ - 'root before', - '1-1 before', - 'root before each', - '1 before each', - '1-1 before each', - bang + '1-1 after each', - '1 after each', - 'root after each', - '1-1 after', - bang + '1-2 before', - 'root before each', - '1 before each', - '1-2 before each', - '1-2 test 1', - '1-2 after each', - bang + '1 after each', - 'root after each', - '1-2 after', - '1 after', - '2-1 before', - 'root before each', - '2 before each', - bang + '2 after each', - bang + 'root after each', - '2-1 after', - '2 after', - 'root after' - ] - ); + it('should verify results', function() { + assert.deepEqual(lines, [ + 'root before', + '1-1 before', + 'root before each', + '1 before each', + '1-1 before each', + bang + '1-1 after each', + '1 after each', + 'root after each', + '1-1 after', + bang + '1-2 before', + 'root before each', + '1 before each', + '1-2 before each', + '1-2 test 1', + '1-2 after each', + bang + '1 after each', + 'root after each', + '1-2 after', + '1 after', + '2-1 before', + 'root before each', + '2 before each', + bang + '2 after each', + bang + 'root after each', + '2-1 after', + '2 after', + 'root after' + ]); }); }); - describe('async - before hook error', function () { + describe('async - before hook error', function() { before(run('hooks/before-hook-async-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - ['before', bang + 'test 3'] - ); + it('should verify results', function() { + assert.deepEqual(lines, ['before', bang + 'test 3']); }); }); - describe('async - before hook error tip', function () { - before(run('hooks/before-hook-async-error-tip.fixture.js', onlyErrorTitle())); - it('should verify results', function () { - assert.deepEqual( - lines, - ['1) spec 2', '"before all" hook:'] - ); + describe('async - before hook error tip', function() { + before( + run('hooks/before-hook-async-error-tip.fixture.js', onlyErrorTitle()) + ); + it('should verify results', function() { + assert.deepEqual(lines, ['1) spec 2', '"before all" hook:']); }); }); - describe('async - before each hook error', function () { + describe('async - before each hook error', function() { before(run('hooks/beforeEach-hook-async-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - ['before', bang + 'test 3'] - ); + it('should verify results', function() { + assert.deepEqual(lines, ['before', bang + 'test 3']); }); }); - describe('async - after hook error', function () { + describe('async - after hook error', function() { before(run('hooks/after-hook-async-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - ['test 1', 'test 2', 'after', bang + 'test 3'] - ); + it('should verify results', function() { + assert.deepEqual(lines, ['test 1', 'test 2', 'after', bang + 'test 3']); }); }); - describe('async - after each hook error', function () { + describe('async - after each hook error', function() { before(run('hooks/afterEach-hook-async-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - ['test 1', 'after', bang + 'test 3'] - ); + it('should verify results', function() { + assert.deepEqual(lines, ['test 1', 'after', bang + 'test 3']); }); }); - describe('async - multiple hook errors', function () { + describe('async - multiple hook errors', function() { before(run('hooks/multiple-hook-async-error.fixture.js')); - it('should verify results', function () { - assert.deepEqual( - lines, - [ - 'root before', - '1-1 before', - 'root before each', - '1 before each', - '1-1 before each', - bang + '1-1 after each', - '1 after each', - 'root after each', - '1-1 after', - bang + '1-2 before', - 'root before each', - '1 before each', - '1-2 before each', - '1-2 test 1', - '1-2 after each', - bang + '1 after each', - 'root after each', - '1-2 after', - '1 after', - '2-1 before', - 'root before each', - '2 before each', - bang + '2 after each', - bang + 'root after each', - '2-1 after', - '2 after', - 'root after' - ] - ); + it('should verify results', function() { + assert.deepEqual(lines, [ + 'root before', + '1-1 before', + 'root before each', + '1 before each', + '1-1 before each', + bang + '1-1 after each', + '1 after each', + 'root after each', + '1-1 after', + bang + '1-2 before', + 'root before each', + '1 before each', + '1-2 before each', + '1-2 test 1', + '1-2 after each', + bang + '1 after each', + 'root after each', + '1-2 after', + '1 after', + '2-1 before', + 'root before each', + '2 before each', + bang + '2 after each', + bang + 'root after each', + '2-1 after', + '2 after', + 'root after' + ]); }); }); - function run (fnPath, outputFilter) { - return function (done) { - runMocha(fnPath, ['--reporter', 'dot'], function (err, res) { + function run(fnPath, outputFilter) { + return function(done) { + runMocha(fnPath, ['--reporter', 'dot'], function(err, res) { assert.ifError(err); lines = res.output .split(splitRegExp) - .map(function (line) { + .map(function(line) { return line.trim(); }) .filter(outputFilter || onlyConsoleOutput()); @@ -202,25 +168,25 @@ describe('hook error handling', function () { } }); -function onlyConsoleOutput () { +function onlyConsoleOutput() { var foundSummary = false; - return function (line) { + return function(line) { if (!foundSummary) { - foundSummary = !!(/\(\d+ms\)/).exec(line); + foundSummary = !!/\(\d+ms\)/.exec(line); } return !foundSummary && line.length > 0; }; } -function onlyErrorTitle (line) { +function onlyErrorTitle(line) { var foundErrorTitle = false; var foundError = false; - return function (line) { + return function(line) { if (!foundErrorTitle) { - foundErrorTitle = !!(/^1\)/).exec(line); + foundErrorTitle = !!/^1\)/.exec(line); } if (!foundError) { - foundError = (/Error:/).exec(line); + foundError = /Error:/.exec(line); } return foundErrorTitle && !foundError; }; diff --git a/test/integration/hooks.spec.js b/test/integration/hooks.spec.js index e68aa66b64..316d522771 100644 --- a/test/integration/hooks.spec.js +++ b/test/integration/hooks.spec.js @@ -5,9 +5,9 @@ var runMocha = require('./helpers').runMocha; var splitRegExp = require('./helpers').splitRegExp; var args = ['--reporter', 'dot']; -describe('hooks', function () { - it('are ran in correct order', function (done) { - runMocha('cascade.fixture.js', args, function (err, res) { +describe('hooks', function() { + it('are ran in correct order', function(done) { + runMocha('cascade.fixture.js', args, function(err, res) { var lines, expected; if (err) { @@ -15,11 +15,15 @@ describe('hooks', function () { return; } - lines = res.output.split(splitRegExp).map(function (line) { - return line.trim(); - }).filter(function (line) { - return line.length; - }).slice(0, -1); + lines = res.output + .split(splitRegExp) + .map(function(line) { + return line.trim(); + }) + .filter(function(line) { + return line.length; + }) + .slice(0, -1); expected = [ 'before one', @@ -37,7 +41,7 @@ describe('hooks', function () { 'after one' ]; - expected.forEach(function (line, i) { + expected.forEach(function(line, i) { assert.equal(lines[i], line); }); diff --git a/test/integration/multiple-done.spec.js b/test/integration/multiple-done.spec.js index 3ac216e457..781871a631 100644 --- a/test/integration/multiple-done.spec.js +++ b/test/integration/multiple-done.spec.js @@ -4,42 +4,42 @@ var assert = require('assert'); var run = require('./helpers').runMochaJSON; var args = []; -describe('multiple calls to done()', function () { +describe('multiple calls to done()', function() { var res; - describe('from a spec', function () { - before(function (done) { - run('multiple-done.fixture.js', args, function (err, result) { + describe('from a spec', function() { + before(function(done) { + run('multiple-done.fixture.js', args, function(err, result) { res = result; done(err); }); }); - it('results in failures', function () { + it('results in failures', function() { assert.equal(res.stats.pending, 0, 'wrong "pending" count'); assert.equal(res.stats.passes, 1, 'wrong "passes" count'); assert.equal(res.stats.failures, 1, 'wrong "failures" count'); }); - it('throws a descriptive error', function () { + it('throws a descriptive error', function() { assert.equal(res.failures[0].err.message, 'done() called multiple times'); }); }); - describe('with error passed on second call', function () { - before(function (done) { - run('multiple-done-with-error.fixture.js', args, function (err, result) { + describe('with error passed on second call', function() { + before(function(done) { + run('multiple-done-with-error.fixture.js', args, function(err, result) { res = result; done(err); }); }); - it('results in failures', function () { + it('results in failures', function() { assert.equal(res.stats.pending, 0, 'wrong "pending" count'); assert.equal(res.stats.passes, 1, 'wrong "passes" count'); assert.equal(res.stats.failures, 1, 'wrong "failures" count'); }); - it('should throw a descriptive error', function () { + it('should throw a descriptive error', function() { assert.equal( res.failures[0].err.message, "second error (and Mocha's done() called multiple times)" @@ -47,66 +47,66 @@ describe('multiple calls to done()', function () { }); }); - describe('with multiple specs', function () { - before(function (done) { - run('multiple-done-specs.fixture.js', args, function (err, result) { + describe('with multiple specs', function() { + before(function(done) { + run('multiple-done-specs.fixture.js', args, function(err, result) { res = result; done(err); }); }); - it('results in a failure', function () { + it('results in a failure', function() { assert.equal(res.stats.pending, 0); assert.equal(res.stats.passes, 2); assert.equal(res.stats.failures, 1); assert.equal(res.code, 1); }); - it('correctly attributes the error', function () { + it('correctly attributes the error', function() { assert.equal(res.failures[0].fullTitle, 'suite test1'); assert.equal(res.failures[0].err.message, 'done() called multiple times'); }); }); - describe('from a before hook', function () { - before(function (done) { - run('multiple-done-before.fixture.js', args, function (err, result) { + describe('from a before hook', function() { + before(function(done) { + run('multiple-done-before.fixture.js', args, function(err, result) { res = result; done(err); }); }); - it('results in a failure', function () { + it('results in a failure', function() { assert.equal(res.stats.pending, 0); assert.equal(res.stats.passes, 1); assert.equal(res.stats.failures, 1); assert.equal(res.code, 1); }); - it('correctly attributes the error', function () { + it('correctly attributes the error', function() { assert.equal(res.failures[0].fullTitle, 'suite "before all" hook'); assert.equal(res.failures[0].err.message, 'done() called multiple times'); }); }); - describe('from a beforeEach hook', function () { - before(function (done) { - run('multiple-done-beforeEach.fixture.js', args, function (err, result) { + describe('from a beforeEach hook', function() { + before(function(done) { + run('multiple-done-beforeEach.fixture.js', args, function(err, result) { res = result; done(err); }); }); - it('results in a failure', function () { + it('results in a failure', function() { assert.equal(res.stats.pending, 0); assert.equal(res.stats.passes, 2); assert.equal(res.stats.failures, 2); assert.equal(res.code, 2); }); - it('correctly attributes the errors', function () { + it('correctly attributes the errors', function() { assert.equal(res.failures.length, 2); - res.failures.forEach(function (failure) { + res.failures.forEach(function(failure) { assert.equal(failure.fullTitle, 'suite "before each" hook'); assert.equal(failure.err.message, 'done() called multiple times'); }); diff --git a/test/integration/no-diff.spec.js b/test/integration/no-diff.spec.js index 10bb53c2d7..acde326f65 100644 --- a/test/integration/no-diff.spec.js +++ b/test/integration/no-diff.spec.js @@ -3,10 +3,10 @@ var helpers = require('./helpers'); var run = helpers.runMocha; -describe('no-diff', function () { - describe('when enabled', function () { - it('should not display a diff', function (done) { - run('no-diff.fixture.js', ['--no-diff'], function (err, res) { +describe('no-diff', function() { + describe('when enabled', function() { + it('should not display a diff', function(done) { + run('no-diff.fixture.js', ['--no-diff'], function(err, res) { if (err) { done(err); return; @@ -18,9 +18,9 @@ describe('no-diff', function () { }); }); - describe('when disabled', function () { - it('should display a diff', function (done) { - run('no-diff.fixture.js', ['--diff'], function (err, res) { + describe('when disabled', function() { + it('should display a diff', function(done) { + run('no-diff.fixture.js', ['--diff'], function(err, res) { if (err) { done(err); return; diff --git a/test/integration/only.spec.js b/test/integration/only.spec.js index 098af6786c..f3bbbd1eab 100644 --- a/test/integration/only.spec.js +++ b/test/integration/only.spec.js @@ -3,10 +3,10 @@ var run = require('./helpers').runMochaJSON; var assert = require('assert'); -describe('.only()', function () { - describe('bdd', function () { - it('should run only tests that marked as `only`', function (done) { - run('options/only/bdd.fixture.js', ['--ui', 'bdd'], function (err, res) { +describe('.only()', function() { + describe('bdd', function() { + it('should run only tests that marked as `only`', function(done) { + run('options/only/bdd.fixture.js', ['--ui', 'bdd'], function(err, res) { if (err) { done(err); return; @@ -20,9 +20,9 @@ describe('.only()', function () { }); }); - describe('tdd', function () { - it('should run only tests that marked as `only`', function (done) { - run('options/only/tdd.fixture.js', ['--ui', 'tdd'], function (err, res) { + describe('tdd', function() { + it('should run only tests that marked as `only`', function(done) { + run('options/only/tdd.fixture.js', ['--ui', 'tdd'], function(err, res) { if (err) { done(err); return; @@ -36,9 +36,12 @@ describe('.only()', function () { }); }); - describe('qunit', function () { - it('should run only tests that marked as `only`', function (done) { - run('options/only/qunit.fixture.js', ['--ui', 'qunit'], function (err, res) { + describe('qunit', function() { + it('should run only tests that marked as `only`', function(done) { + run('options/only/qunit.fixture.js', ['--ui', 'qunit'], function( + err, + res + ) { if (err) { done(err); return; diff --git a/test/integration/options.spec.js b/test/integration/options.spec.js index 5cc63b42d5..a8119db695 100644 --- a/test/integration/options.spec.js +++ b/test/integration/options.spec.js @@ -8,14 +8,14 @@ var directInvoke = helpers.invokeMocha; var resolvePath = helpers.resolveFixturePath; var args = []; -describe('options', function () { - describe('--async-only', function () { - before(function () { +describe('options', function() { + describe('--async-only', function() { + before(function() { args = ['--async-only']; }); - it('should fail synchronous specs', function (done) { - run('options/async-only-sync.fixture.js', args, function (err, res) { + it('should fail synchronous specs', function(done) { + run('options/async-only-sync.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -30,8 +30,8 @@ describe('options', function () { }); }); - it('should allow asynchronous specs', function (done) { - run('options/async-only-async.fixture.js', args, function (err, res) { + it('should allow asynchronous specs', function(done) { + run('options/async-only-async.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -47,13 +47,13 @@ describe('options', function () { }); }); - describe('--bail', function () { - before(function () { + describe('--bail', function() { + before(function() { args = ['--bail']; }); - it('should stop after the first error', function (done) { - run('options/bail.fixture.js', args, function (err, res) { + it('should stop after the first error', function(done) { + run('options/bail.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -69,8 +69,8 @@ describe('options', function () { }); }); - it('should stop all hooks after the first error', function (done) { - run('options/bail-with-after.fixture.js', args, function (err, res) { + it('should stop all hooks after the first error', function(done) { + run('options/bail-with-after.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -86,13 +86,13 @@ describe('options', function () { }); }); - describe('--sort', function () { - before(function () { + describe('--sort', function() { + before(function() { args = ['--sort']; }); - it('should sort tests in alphabetical order', function (done) { - run('options/sort*', args, function (err, res) { + it('should sort tests in alphabetical order', function(done) { + run('options/sort*', args, function(err, res) { if (err) { done(err); return; @@ -101,19 +101,18 @@ describe('options', function () { assert.equal(res.stats.passes, 2); assert.equal(res.stats.failures, 0); - assert.equal(res.passes[0].fullTitle, - 'alpha should be executed first'); + assert.equal(res.passes[0].fullTitle, 'alpha should be executed first'); assert.equal(res.code, 0); done(); }); }); }); - describe('--file', function () { - it('should run tests passed via file first', function (done) { + describe('--file', function() { + it('should run tests passed via file first', function(done) { args = ['--file', resolvePath('options/file-alpha.fixture.js')]; - run('options/file-beta.fixture.js', args, function (err, res) { + run('options/file-beta.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -122,20 +121,21 @@ describe('options', function () { assert.equal(res.stats.passes, 2); assert.equal(res.stats.failures, 0); - assert.equal(res.passes[0].fullTitle, - 'alpha should be executed first'); + assert.equal(res.passes[0].fullTitle, 'alpha should be executed first'); assert.equal(res.code, 0); done(); }); }); - it('should run multiple tests passed via file first', function (done) { + it('should run multiple tests passed via file first', function(done) { args = [ - '--file', resolvePath('options/file-alpha.fixture.js'), - '--file', resolvePath('options/file-beta.fixture.js') + '--file', + resolvePath('options/file-alpha.fixture.js'), + '--file', + resolvePath('options/file-beta.fixture.js') ]; - run('options/file-theta.fixture.js', args, function (err, res) { + run('options/file-theta.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -144,25 +144,22 @@ describe('options', function () { assert.equal(res.stats.passes, 3); assert.equal(res.stats.failures, 0); - assert.equal(res.passes[0].fullTitle, - 'alpha should be executed first'); - assert.equal(res.passes[1].fullTitle, - 'beta should be executed second'); - assert.equal(res.passes[2].fullTitle, - 'theta should be executed third'); + assert.equal(res.passes[0].fullTitle, 'alpha should be executed first'); + assert.equal(res.passes[1].fullTitle, 'beta should be executed second'); + assert.equal(res.passes[2].fullTitle, 'theta should be executed third'); assert.equal(res.code, 0); done(); }); }); }); - describe('--delay', function () { - before(function () { + describe('--delay', function() { + before(function() { args = ['--delay']; }); - it('should run the generated test suite', function (done) { - run('options/delay.fixture.js', args, function (err, res) { + it('should run the generated test suite', function(done) { + run('options/delay.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -171,15 +168,17 @@ describe('options', function () { assert.equal(res.stats.passes, 1); assert.equal(res.stats.failures, 0); - assert.equal(res.passes[0].title, - 'should have no effect if attempted twice in the same suite'); + assert.equal( + res.passes[0].title, + 'should have no effect if attempted twice in the same suite' + ); assert.equal(res.code, 0); done(); }); }); - it('should execute exclusive tests only', function (done) { - run('options/delay-only.fixture.js', args, function (err, res) { + it('should execute exclusive tests only', function(done) { + run('options/delay-only.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -197,8 +196,8 @@ describe('options', function () { }); }); - it('should throw an error if the test suite failed to run', function (done) { - run('options/delay-fail.fixture.js', args, function (err, res) { + it('should throw an error if the test suite failed to run', function(done) { + run('options/delay-fail.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -207,18 +206,20 @@ describe('options', function () { assert.equal(res.stats.passes, 0); assert.equal(res.stats.failures, 1); - assert.equal(res.failures[0].title, - 'Uncaught error outside test suite'); + assert.equal( + res.failures[0].title, + 'Uncaught error outside test suite' + ); assert.equal(res.code, 1); done(); }); }); }); - describe('--grep', function () { - it('runs specs matching a string', function (done) { + describe('--grep', function() { + it('runs specs matching a string', function(done) { args = ['--grep', 'match']; - run('options/grep.fixture.js', args, function (err, res) { + run('options/grep.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -231,10 +232,10 @@ describe('options', function () { }); }); - describe('runs specs matching a RegExp', function () { - it('with RegExp like strings(pattern follow by flag)', function (done) { + describe('runs specs matching a RegExp', function() { + it('with RegExp like strings(pattern follow by flag)', function(done) { args = ['--grep', '/match/i']; - run('options/grep.fixture.js', args, function (err, res) { + run('options/grep.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -247,9 +248,9 @@ describe('options', function () { }); }); - it('string as pattern', function (done) { + it('string as pattern', function(done) { args = ['--grep', '.*']; - run('options/grep.fixture.js', args, function (err, res) { + run('options/grep.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -263,10 +264,10 @@ describe('options', function () { }); }); - describe('with --invert', function () { - it('runs specs that do not match the pattern', function (done) { + describe('with --invert', function() { + it('runs specs that do not match the pattern', function(done) { args = ['--grep', 'fail', '--invert']; - run('options/grep.fixture.js', args, function (err, res) { + run('options/grep.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -281,10 +282,10 @@ describe('options', function () { }); }); - describe('--retries', function () { - it('retries after a certain threshold', function (done) { + describe('--retries', function() { + it('retries after a certain threshold', function(done) { args = ['--retries', '3']; - run('options/retries.fixture.js', args, function (err, res) { + run('options/retries.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -300,15 +301,15 @@ describe('options', function () { }); }); - describe('--forbid-only', function () { + describe('--forbid-only', function() { var onlyErrorMessage = '`.only` forbidden'; - before(function () { + before(function() { args = ['--forbid-only']; }); - it('succeeds if there are only passed tests', function (done) { - run('options/forbid-only/passed.js', args, function (err, res) { + it('succeeds if there are only passed tests', function(done) { + run('options/forbid-only/passed.js', args, function(err, res) { if (err) { done(err); return; @@ -318,8 +319,8 @@ describe('options', function () { }); }); - it('fails if there are tests marked only', function (done) { - run('options/forbid-only/only.js', args, function (err, res) { + it('fails if there are tests marked only', function(done) { + run('options/forbid-only/only.js', args, function(err, res) { if (err) { done(err); return; @@ -330,8 +331,8 @@ describe('options', function () { }); }); - it('fails if there are tests in suites marked only', function (done) { - run('options/forbid-only/only-suite.js', args, function (err, res) { + it('fails if there are tests in suites marked only', function(done) { + run('options/forbid-only/only-suite.js', args, function(err, res) { assert(!err); assert.equal(res.code, 1); assert.equal(res.failures[0].err.message, onlyErrorMessage); @@ -340,15 +341,15 @@ describe('options', function () { }); }); - describe('--forbid-pending', function () { + describe('--forbid-pending', function() { var pendingErrorMessage = 'Pending test forbidden'; - before(function () { + before(function() { args = ['--forbid-pending']; }); - it('succeeds if there are only passed tests', function (done) { - run('options/forbid-pending/passed.js', args, function (err, res) { + it('succeeds if there are only passed tests', function(done) { + run('options/forbid-pending/passed.js', args, function(err, res) { if (err) { done(err); return; @@ -367,11 +368,16 @@ describe('options', function () { 'fails if there are tests in suites marked skip': 'skip-suite.js' }; - Object.keys(forbidPendingFailureTests).forEach(function (title) { - it(title, function (done) { - run(path.join('options', 'forbid-pending', forbidPendingFailureTests[title]), + Object.keys(forbidPendingFailureTests).forEach(function(title) { + it(title, function(done) { + run( + path.join( + 'options', + 'forbid-pending', + forbidPendingFailureTests[title] + ), args, - function (err, res) { + function(err, res) { if (err) { done(err); return; @@ -379,12 +385,13 @@ describe('options', function () { assert.equal(res.code, 1); assert.equal(res.failures[0].err.message, pendingErrorMessage); done(); - }); + } + ); }); }); }); - describe('--exit', function () { + describe('--exit', function() { var behaviors = { enabled: '--exit', disabled: '--no-exit' @@ -398,15 +405,15 @@ describe('options', function () { * @param {string} [behavior] - 'enabled' or 'disabled' * @returns {Function} */ - var runExit = function (shouldExit, behavior) { - return function (done) { + var runExit = function(shouldExit, behavior) { + return function(done) { this.timeout(0); this.slow(3000); var didExit = true; var t; var args = behaviors[behavior] ? [behaviors[behavior]] : []; - var mocha = run('exit.fixture.js', args, function (err) { + var mocha = run('exit.fixture.js', args, function(err) { clearTimeout(t); if (err) { done(err); @@ -417,7 +424,7 @@ describe('options', function () { }); // if this callback happens, then Mocha didn't automatically exit. - t = setTimeout(function () { + t = setTimeout(function() { didExit = false; // this is the only way to kill the child, afaik. // after the process ends, the callback to `run()` above is handled. @@ -426,38 +433,48 @@ describe('options', function () { }; }; - describe('default behavior', function () { + describe('default behavior', function() { it('should force exit after root suite completion', runExit(false)); }); - describe('with exit enabled', function () { - it('should force exit after root suite completion', runExit(true, 'enabled')); + describe('with exit enabled', function() { + it( + 'should force exit after root suite completion', + runExit(true, 'enabled') + ); }); - describe('with exit disabled', function () { - it('should not force exit after root suite completion', runExit(false, 'disabled')); + describe('with exit disabled', function() { + it( + 'should not force exit after root suite completion', + runExit(false, 'disabled') + ); }); }); - describe('--help', function () { - it('works despite the presence of mocha.opts', function (done) { - directInvoke(['-h'], function (error, result) { - if (error) { - return done(error); - } - expect(result.output).to.contain('Usage:'); - done(); - }, path.join(__dirname, 'fixtures', 'options', 'help')); + describe('--help', function() { + it('works despite the presence of mocha.opts', function(done) { + directInvoke( + ['-h'], + function(error, result) { + if (error) { + return done(error); + } + expect(result.output).to.contain('Usage:'); + done(); + }, + path.join(__dirname, 'fixtures', 'options', 'help') + ); }); }); - describe('--exclude', function () { + describe('--exclude', function() { /* * Runs mocha in {path} with the given args. * Calls handleResult with the result. */ - function runMochaTest (fixture, args, handleResult, done) { - run(fixture, args, function (err, res) { + function runMochaTest(fixture, args, handleResult, done) { + run(fixture, args, function(err, res) { if (err) { done(err); return; @@ -467,40 +484,55 @@ describe('options', function () { }); } - it('should exclude specific files', function (done) { - runMochaTest('options/exclude/*.fixture.js', [ - '--exclude', - 'test/integration/fixtures/options/exclude/fail.fixture.js' - ], function (res) { - assert.equal(res.stats.pending, 0); - assert.equal(res.stats.passes, 1); - assert.equal(res.stats.failures, 0); - assert.equal(res.passes[0].title, 'should find this test'); - assert.equal(res.code, 0); - }, done); - }); - - it('should exclude globbed files', function (done) { - runMochaTest('options/exclude/**/*.fixture.js', ['--exclude', '**/fail.fixture.js'], function (res) { - assert.equal(res.stats.pending, 0); - assert.equal(res.stats.passes, 2); - assert.equal(res.stats.failures, 0); - assert.equal(res.code, 0); - }, done); + it('should exclude specific files', function(done) { + runMochaTest( + 'options/exclude/*.fixture.js', + [ + '--exclude', + 'test/integration/fixtures/options/exclude/fail.fixture.js' + ], + function(res) { + assert.equal(res.stats.pending, 0); + assert.equal(res.stats.passes, 1); + assert.equal(res.stats.failures, 0); + assert.equal(res.passes[0].title, 'should find this test'); + assert.equal(res.code, 0); + }, + done + ); }); - it('should exclude multiple patterns', function (done) { - runMochaTest('options/exclude/**/*.fixture.js', [ - '--exclude', - 'test/integration/fixtures/options/exclude/fail.fixture.js', - '--exclude', - 'test/integration/fixtures/options/exclude/nested/fail.fixture.js' - ], function (res) { - assert.equal(res.stats.pending, 0); - assert.equal(res.stats.passes, 2); - assert.equal(res.stats.failures, 0); - assert.equal(res.code, 0); - }, done); + it('should exclude globbed files', function(done) { + runMochaTest( + 'options/exclude/**/*.fixture.js', + ['--exclude', '**/fail.fixture.js'], + function(res) { + assert.equal(res.stats.pending, 0); + assert.equal(res.stats.passes, 2); + assert.equal(res.stats.failures, 0); + assert.equal(res.code, 0); + }, + done + ); + }); + + it('should exclude multiple patterns', function(done) { + runMochaTest( + 'options/exclude/**/*.fixture.js', + [ + '--exclude', + 'test/integration/fixtures/options/exclude/fail.fixture.js', + '--exclude', + 'test/integration/fixtures/options/exclude/nested/fail.fixture.js' + ], + function(res) { + assert.equal(res.stats.pending, 0); + assert.equal(res.stats.passes, 2); + assert.equal(res.stats.failures, 0); + assert.equal(res.code, 0); + }, + done + ); }); }); }); diff --git a/test/integration/pending.spec.js b/test/integration/pending.spec.js index af665accf6..27601b7a0e 100644 --- a/test/integration/pending.spec.js +++ b/test/integration/pending.spec.js @@ -4,10 +4,10 @@ var assert = require('assert'); var run = require('./helpers').runMochaJSON; var args = []; -describe('pending', function () { - describe('pending specs', function () { - it('should be created by omitting a function', function (done) { - run('pending/spec.fixture.js', args, function (err, res) { +describe('pending', function() { + describe('pending specs', function() { + it('should be created by omitting a function', function(done) { + run('pending/spec.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -19,8 +19,8 @@ describe('pending', function () { done(); }); }); - it('should return the test object when used via shorthand methods', function (done) { - run('pending/skip-shorthand.fixture.js', args, function (err, res) { + it('should return the test object when used via shorthand methods', function(done) { + run('pending/skip-shorthand.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -32,8 +32,8 @@ describe('pending', function () { done(); }); }); - it('should keep hierarchies of suites', function (done) { - run('pending/skip-hierarchy.fixture.js', args, function (err, res) { + it('should keep hierarchies of suites', function(done) { + run('pending/skip-hierarchy.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -49,10 +49,10 @@ describe('pending', function () { }); }); - describe('synchronous skip()', function () { - describe('in spec', function () { - it('should immediately skip the spec and run all others', function (done) { - run('pending/skip-sync-spec.fixture.js', args, function (err, res) { + describe('synchronous skip()', function() { + describe('in spec', function() { + it('should immediately skip the spec and run all others', function(done) { + run('pending/skip-sync-spec.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -66,9 +66,9 @@ describe('pending', function () { }); }); - describe('in before', function () { - it('should skip all suite specs', function (done) { - run('pending/skip-sync-before.fixture.js', args, function (err, res) { + describe('in before', function() { + it('should skip all suite specs', function(done) { + run('pending/skip-sync-before.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -82,9 +82,12 @@ describe('pending', function () { }); }); - describe('in beforeEach', function () { - it('should skip all suite specs', function (done) { - run('pending/skip-sync-beforeEach.fixture.js', args, function (err, res) { + describe('in beforeEach', function() { + it('should skip all suite specs', function(done) { + run('pending/skip-sync-beforeEach.fixture.js', args, function( + err, + res + ) { if (err) { done(err); return; @@ -99,10 +102,10 @@ describe('pending', function () { }); }); - describe('asynchronous skip()', function () { - describe('in spec', function () { - it('should immediately skip the spec and run all others', function (done) { - run('pending/skip-async-spec.fixture.js', args, function (err, res) { + describe('asynchronous skip()', function() { + describe('in spec', function() { + it('should immediately skip the spec and run all others', function(done) { + run('pending/skip-async-spec.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -116,9 +119,9 @@ describe('pending', function () { }); }); - describe('in before', function () { - it('should skip all suite specs', function (done) { - run('pending/skip-async-before.fixture.js', args, function (err, res) { + describe('in before', function() { + it('should skip all suite specs', function(done) { + run('pending/skip-async-before.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -132,9 +135,12 @@ describe('pending', function () { }); }); - describe('in beforeEach', function () { - it('should skip all suite specs', function (done) { - run('pending/skip-sync-beforeEach.fixture.js', args, function (err, res) { + describe('in beforeEach', function() { + it('should skip all suite specs', function(done) { + run('pending/skip-sync-beforeEach.fixture.js', args, function( + err, + res + ) { if (err) { done(err); return; diff --git a/test/integration/regression.spec.js b/test/integration/regression.spec.js index 1c0466b180..e1f6b19dde 100644 --- a/test/integration/regression.spec.js +++ b/test/integration/regression.spec.js @@ -6,11 +6,11 @@ var path = require('path'); var run = require('./helpers').runMocha; var runJSON = require('./helpers').runMochaJSON; -describe('regressions', function () { - it('issue-1327: should run all 3 specs exactly once', function (done) { +describe('regressions', function() { + it('issue-1327: should run all 3 specs exactly once', function(done) { var args = []; - run('regression/issue-1327.fixture.js', args, function (err, res) { - var occurences = function (str) { + run('regression/issue-1327.fixture.js', args, function(err, res) { + var occurences = function(str) { var pattern = new RegExp(str, 'g'); return (res.output.match(pattern) || []).length; }; @@ -28,17 +28,34 @@ describe('regressions', function () { }); }); - it('should not duplicate mocha.opts args in process.argv', function () { + it('should not duplicate mocha.opts args in process.argv', function() { var processArgv = process.argv.join(''); - var mochaOpts = fs.readFileSync(path.join(__dirname, '..', 'mocha.opts'), 'utf-8').split(/[\s]+/).join(''); - assert.notEqual(processArgv.indexOf(mochaOpts), -1, 'process.argv missing mocha.opts'); - assert.equal(processArgv.indexOf(mochaOpts), processArgv.lastIndexOf(mochaOpts), 'process.argv contains duplicated mocha.opts'); + var mochaOpts = fs + .readFileSync(path.join(__dirname, '..', 'mocha.opts'), 'utf-8') + .split(/[\s]+/) + .join(''); + assert.notEqual( + processArgv.indexOf(mochaOpts), + -1, + 'process.argv missing mocha.opts' + ); + assert.equal( + processArgv.indexOf(mochaOpts), + processArgv.lastIndexOf(mochaOpts), + 'process.argv contains duplicated mocha.opts' + ); }); - it('issue-1794: Can\'t --require custom UI and use it', function (done) { - var simpleUiPath = path.join(__dirname, 'fixtures', 'regression', '1794', 'simple-ui.js'); + it("issue-1794: Can't --require custom UI and use it", function(done) { + var simpleUiPath = path.join( + __dirname, + 'fixtures', + 'regression', + '1794', + 'simple-ui.js' + ); var args = ['--require', simpleUiPath, '--ui', 'simple-ui']; - run('regression/1794/issue-1794.fixture.js', args, function (err, res) { + run('regression/1794/issue-1794.fixture.js', args, function(err, res) { if (err) { done(err); return; @@ -48,36 +65,48 @@ describe('regressions', function () { }); }); - it('issue-1991: Declarations do not get cleaned up unless you set them to `null` - Memory Leak', function (done) { + it('issue-1991: Declarations do not get cleaned up unless you set them to `null` - Memory Leak', function(done) { // on a modern MBP takes ±5 seconds on node 4.0, but on older laptops with node 0.12 ±40 seconds. // Could easily take longer on even weaker machines (Travis-CI containers for example). this.timeout(120000); this.slow(12000); - run('regression/issue-1991.fixture.js', [], function (err, res) { + run('regression/issue-1991.fixture.js', [], function(err, res) { if (err) { done(err); return; } - assert.equal(/process out of memory/.test(res.output), false, 'fixture\'s process out of memory!'); - assert.equal(res.code, 0, 'Runnable fn (it/before[Each]/after[Each]) references should be deleted to avoid memory leaks'); + assert.equal( + /process out of memory/.test(res.output), + false, + "fixture's process out of memory!" + ); + assert.equal( + res.code, + 0, + 'Runnable fn (it/before[Each]/after[Each]) references should be deleted to avoid memory leaks' + ); done(); }); }); - describe('issue-2286: after doesn\'t execute if test was skipped in beforeEach', function () { + describe("issue-2286: after doesn't execute if test was skipped in beforeEach", function() { var afterWasRun = false; - describe('suite with skipped test for meta test', function () { - beforeEach(function () { this.skip(); }); - after(function () { afterWasRun = true; }); - it('should be pending', function () {}); + describe('suite with skipped test for meta test', function() { + beforeEach(function() { + this.skip(); + }); + after(function() { + afterWasRun = true; + }); + it('should be pending', function() {}); }); - after('meta test', function () { + after('meta test', function() { expect(afterWasRun).to.be.ok(); }); }); - it('issue-2315: cannot read property currentRetry of undefined', function (done) { - runJSON('regression/issue-2315.fixture.js', [], function (err, res) { + it('issue-2315: cannot read property currentRetry of undefined', function(done) { + runJSON('regression/issue-2315.fixture.js', [], function(err, res) { if (err) { done(err); return; @@ -90,9 +119,9 @@ describe('regressions', function () { }); }); - it('issue-2406: should run nested describe.only suites', function (done) { + it('issue-2406: should run nested describe.only suites', function(done) { this.timeout(2000); - runJSON('regression/issue-2406.fixture.js', [], function (err, res) { + runJSON('regression/issue-2406.fixture.js', [], function(err, res) { if (err) { done(err); return; @@ -105,8 +134,8 @@ describe('regressions', function () { }); }); - it('issue-2417: should not recurse infinitely with .only suites nested within each other', function (done) { - runJSON('regression/issue-2417.fixture.js', [], function (err, res) { + it('issue-2417: should not recurse infinitely with .only suites nested within each other', function(done) { + runJSON('regression/issue-2417.fixture.js', [], function(err, res) { if (err) { done(err); return; @@ -119,8 +148,8 @@ describe('regressions', function () { }); }); - it('issue-1417 uncaught exceptions from async specs', function (done) { - runJSON('regression/issue-1417.fixture.js', [], function (err, res) { + it('issue-1417 uncaught exceptions from async specs', function(done) { + runJSON('regression/issue-1417.fixture.js', [], function(err, res) { if (err) { done(err); return; @@ -129,11 +158,15 @@ describe('regressions', function () { assert.equal(res.stats.passes, 0); assert.equal(res.stats.failures, 2); - assert.equal(res.failures[0].title, - 'fails exactly once when a global error is thrown synchronously and done errors'); + assert.equal( + res.failures[0].title, + 'fails exactly once when a global error is thrown synchronously and done errors' + ); assert.equal(res.failures[0].err.message, 'sync error'); - assert.equal(res.failures[1].title, - 'fails exactly once when a global error is thrown synchronously and done completes'); + assert.equal( + res.failures[1].title, + 'fails exactly once when a global error is thrown synchronously and done completes' + ); assert.equal(res.failures[1].err.message, 'sync error'); assert.equal(res.code, 2); done(); diff --git a/test/integration/reporters.spec.js b/test/integration/reporters.spec.js index 9bf8df289c..bd1e755ed8 100644 --- a/test/integration/reporters.spec.js +++ b/test/integration/reporters.spec.js @@ -7,52 +7,55 @@ var crypto = require('crypto'); var path = require('path'); var run = require('./helpers').runMocha; -describe('reporters', function () { - describe('markdown', function () { +describe('reporters', function() { + describe('markdown', function() { var res; - before(function (done) { - run('passing.fixture.js', ['--reporter', 'markdown'], function (err, result) { + before(function(done) { + run('passing.fixture.js', ['--reporter', 'markdown'], function( + err, + result + ) { res = result; done(err); }); }); - it('does not exceed maximum callstack (issue: 1875)', function () { + it('does not exceed maximum callstack (issue: 1875)', function() { assert(res.output.indexOf('RangeError') === -1, 'Threw RangeError'); }); - it('contains spec src', function () { - var src = [ - '```js', - 'assert(true);', - '```' - ].join('\n'); + it('contains spec src', function() { + var src = ['```js', 'assert(true);', '```'].join('\n'); assert(res.output.indexOf(src) !== -1, 'No assert found'); }); }); - describe('xunit', function () { - it('prints test cases with --reporter-options output (issue: 1864)', function (done) { + describe('xunit', function() { + it('prints test cases with --reporter-options output (issue: 1864)', function(done) { var randomStr = crypto.randomBytes(8).toString('hex'); var tmpDir = os.tmpdir().replace(new RegExp(path.sep + '$'), ''); var tmpFile = tmpDir + path.sep + 'test-issue-1864-' + randomStr + '.xml'; - var args = ['--reporter=xunit', '--reporter-options', 'output=' + tmpFile]; + var args = [ + '--reporter=xunit', + '--reporter-options', + 'output=' + tmpFile + ]; var expectedOutput = [ ' (/usr/local/dev/test.js:16:12)', @@ -28,9 +28,7 @@ describe('stackTraceFilter()', function () { 'Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)', 'at processImmediate [as _immediateCallback] (timers.js:321:17)' ]; - expect(filter(stack.join('\n'))) - .to.equal(stack.slice(0, 3) - .join('\n')); + expect(filter(stack.join('\n'))).to.equal(stack.slice(0, 3).join('\n')); stack = [ 'AssertionError: bar baz', @@ -46,12 +44,10 @@ describe('stackTraceFilter()', function () { 'at processImmediate [as _immediateCallback] (timers.js:321:17)' ]; - expect(filter(stack.join('\n'))) - .to.equal(stack.slice(0, 7) - .join('\n')); + expect(filter(stack.join('\n'))).to.equal(stack.slice(0, 7).join('\n')); }); - it('does not ignore other bower_components and components', function () { + it('does not ignore other bower_components and components', function() { var stack = [ 'Error: failed', 'at assert (index.html:11:26)', @@ -67,12 +63,10 @@ describe('stackTraceFilter()', function () { 'at file:///.../components/mochajs/mocha/2.1.0/mocha.js:4970:12', 'at next (file:///.../components/mochajs/mocha/2.1.0/mocha.js:4817:14)' ]; - expect(filter(stack.join('\n'))) - .to.equal(stack.slice(0, 7) - .join('\n')); + expect(filter(stack.join('\n'))).to.equal(stack.slice(0, 7).join('\n')); }); - it('should replace absolute with relative paths', function () { + it('should replace absolute with relative paths', function() { var stack = [ 'Error: ' + process.cwd() + '/bla.js has a problem', 'at foo (' + process.cwd() + '/foo/index.js:13:226)', @@ -85,11 +79,10 @@ describe('stackTraceFilter()', function () { 'at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)' ]; - expect(filter(stack.join('\n'))) - .to.equal(expected.join('\n')); + expect(filter(stack.join('\n'))).to.equal(expected.join('\n')); }); - it('should not replace absolute path which has cwd as infix', function () { + it('should not replace absolute path which has cwd as infix', function() { var stack = [ 'Error: /www' + process.cwd() + '/bla.js has a problem', 'at foo (/www' + process.cwd() + '/foo/index.js:13:226)', @@ -102,19 +95,18 @@ describe('stackTraceFilter()', function () { 'at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)' ]; - expect(filter(stack.join('\n'))) - .to.equal(expected.join('\n')); + expect(filter(stack.join('\n'))).to.equal(expected.join('\n')); }); }); - describe('on Windows', function () { - before(function () { + describe('on Windows', function() { + before(function() { if (path.sep === '/') { this.skip(); } }); - it('should work on Windows', function () { + it('should work on Windows', function() { var stack = [ 'Error: failed', 'at Context. (C:\\Users\\ishida\\src\\test\\test\\mytest.js:5:9)', @@ -127,21 +119,19 @@ describe('stackTraceFilter()', function () { 'at next (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:284:14)', 'at Immediate._onImmediate (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:320:5)' ]; - expect(filter(stack.join('\n'))) - .to.equal(stack.slice(0, 2) - .join('\n')); + expect(filter(stack.join('\n'))).to.equal(stack.slice(0, 2).join('\n')); }); }); }); - describe('on browser', function () { + describe('on browser', function() { var filter; - before(function () { + before(function() { global.document = true; global.location = {href: 'localhost:3000/foo/bar/index.html'}; filter = utils.stackTraceFilter(); }); - it('does not strip out other bower_components', function () { + it('does not strip out other bower_components', function() { var stack = [ 'Error: failed', 'at assert (index.html:11:26)', @@ -154,12 +144,10 @@ describe('stackTraceFilter()', function () { 'at localhost:3000/foo/bar/node_modules/mocha.js:4970:12', 'at next (node_modules/mocha.js:4817:14)' ]; - expect(filter(stack.join('\n'))) - .to.equal(stack.slice(0, 7) - .join('\n')); + expect(filter(stack.join('\n'))).to.equal(stack.slice(0, 7).join('\n')); }); - after(function () { + after(function() { delete global.document; delete global.location; }); diff --git a/test/only/bdd-require.spec.js b/test/only/bdd-require.spec.js index 9b85052c23..8f1b239642 100644 --- a/test/only/bdd-require.spec.js +++ b/test/only/bdd-require.spec.js @@ -6,12 +6,12 @@ var beforeEach = mocha.beforeEach; var it = mocha.it; var describe = mocha.describe; -describe('it.only via require("mocha")', function () { - beforeEach(function () { +describe('it.only via require("mocha")', function() { + beforeEach(function() { this.didRunBeforeEach = true; }); - describe('nested within a describe/context', function () { - it.only('should run all enclosing beforeEach hooks', function () { + describe('nested within a describe/context', function() { + it.only('should run all enclosing beforeEach hooks', function() { require('assert').equal(this.didRunBeforeEach, true); }); }); diff --git a/test/only/bdd.spec.js b/test/only/bdd.spec.js index ac9f92a0d4..b317e51bed 100644 --- a/test/only/bdd.spec.js +++ b/test/only/bdd.spec.js @@ -1,77 +1,77 @@ 'use strict'; -describe('should only run .only test in this bdd suite', function () { - it('should not run this test', function () { +describe('should only run .only test in this bdd suite', function() { + it('should not run this test', function() { expect(0).to.equal(1, 'this test should have been skipped'); }); - it.only('should run this test', function () { + it.only('should run this test', function() { expect(0).to.equal(0, 'this .only test should run'); }); - it('should run this test, not (includes the title of the .only test)', function () { + it('should run this test, not (includes the title of the .only test)', function() { expect(0).to.equal(1, 'this test should have been skipped'); }); }); -describe('should not run this suite', function () { - it('should not run this test', function () { +describe('should not run this suite', function() { + it('should not run this test', function() { expect(true).to.equal(false); }); - it('should not run this test', function () { + it('should not run this test', function() { expect(true).to.equal(false); }); - it('should not run this test', function () { + it('should not run this test', function() { expect(true).to.equal(false); }); }); -describe.only('should run all tests in this bdd suite', function () { - it('should run this test #1', function () { +describe.only('should run all tests in this bdd suite', function() { + it('should run this test #1', function() { expect(true).to.equal(true); }); - it('should run this test #2', function () { + it('should run this test #2', function() { expect(1).to.equal(1); }); - it('should run this test #3', function () { + it('should run this test #3', function() { expect('foo').to.equal('foo'); }); }); -describe('should run only suites that marked as `only`', function () { - describe.only('should run all this tdd suite', function () { - it('should run this test #1', function () { +describe('should run only suites that marked as `only`', function() { + describe.only('should run all this tdd suite', function() { + it('should run this test #1', function() { expect(true).to.equal(true); }); - it('should run this test #2', function () { + it('should run this test #2', function() { expect(true).to.equal(true); }); }); - describe('should not run this suite', function () { - it('should run this test', function () { + describe('should not run this suite', function() { + it('should run this test', function() { expect(true).to.equal(false); }); }); }); // Nested situation -describe('should not run parent tests', function () { - it('should not run this test', function () { +describe('should not run parent tests', function() { + it('should not run this test', function() { expect(true).to.equal(false); }); - describe('and not the child tests too', function () { - it('should not run this test', function () { + describe('and not the child tests too', function() { + it('should not run this test', function() { expect(true).to.equal(false); }); - describe.only('but run all the tests in this suite', function () { - it('should run this test #1', function () { + describe.only('but run all the tests in this suite', function() { + it('should run this test #1', function() { expect(true).to.equal(true); }); - it('should run this test #2', function () { + it('should run this test #2', function() { expect(true).to.equal(true); }); }); @@ -79,49 +79,49 @@ describe('should not run parent tests', function () { }); // mark test as `only` override the suite behavior -describe.only('should run only tests that marked as `only`', function () { - it('should not run this test #1', function () { +describe.only('should run only tests that marked as `only`', function() { + it('should not run this test #1', function() { expect(false).to.equal(true); }); - it.only('should run this test #2', function () { + it.only('should run this test #2', function() { expect(true).to.equal(true); }); - it('should not run this test #3', function () { + it('should not run this test #3', function() { expect(false).to.equal(true); }); - it.only('should run this test #4', function () { + it.only('should run this test #4', function() { expect(true).to.equal(true); }); }); -describe.only('Should run only test cases that mark as only', function () { - it.only('should runt his test', function () { +describe.only('Should run only test cases that mark as only', function() { + it.only('should runt his test', function() { expect(true).to.equal(true); }); - it('should not run this test', function () { + it('should not run this test', function() { expect(false).to.equal(true); }); - describe('should not run this suite', function () { - it('should not run this test', function () { + describe('should not run this suite', function() { + it('should not run this test', function() { expect(false).to.equal(true); }); }); }); // Root Suite -it.only('#Root-Suite, should run this test-case #1', function () { +it.only('#Root-Suite, should run this test-case #1', function() { expect(true).to.equal(true); }); -it.only('#Root-Suite, should run this test-case #2', function () { +it.only('#Root-Suite, should run this test-case #2', function() { expect(true).to.equal(true); }); -it('#Root-Suite, should not run this test', function () { +it('#Root-Suite, should not run this test', function() { expect(false).to.equal(true); }); diff --git a/test/only/global/bdd.spec.js b/test/only/global/bdd.spec.js index 5e5e271350..759d3e6f4e 100644 --- a/test/only/global/bdd.spec.js +++ b/test/only/global/bdd.spec.js @@ -1,14 +1,14 @@ 'use strict'; // Root-only test cases -it.only('#Root-Suite, should run this bdd test-case #1', function () { +it.only('#Root-Suite, should run this bdd test-case #1', function() { expect(true).to.equal(true); }); -it('#Root-Suite, should not run this bdd test-case #2', function () { +it('#Root-Suite, should not run this bdd test-case #2', function() { expect(false).to.equal(true); }); -it('#Root-Suite, should not run this bdd test-case #3', function () { +it('#Root-Suite, should not run this bdd test-case #3', function() { expect(false).to.equal(true); }); diff --git a/test/only/global/qunit.spec.js b/test/only/global/qunit.spec.js index 20a16ddced..2d09c3fb9c 100644 --- a/test/only/global/qunit.spec.js +++ b/test/only/global/qunit.spec.js @@ -1,14 +1,14 @@ 'use strict'; // Root-only test cases -test.only('#Root-Suite, should run this qunit test-case #1', function () { +test.only('#Root-Suite, should run this qunit test-case #1', function() { expect(true).to.equal(true); }); -test('#Root-Suite, should not run this qunit test-case #2', function () { +test('#Root-Suite, should not run this qunit test-case #2', function() { expect(false).to.equal(true); }); -test('#Root-Suite, should not run this qunit test-case #3', function () { +test('#Root-Suite, should not run this qunit test-case #3', function() { expect(false).to.equal(true); }); diff --git a/test/only/global/tdd.spec.js b/test/only/global/tdd.spec.js index f140de29b3..29f21c6b8d 100644 --- a/test/only/global/tdd.spec.js +++ b/test/only/global/tdd.spec.js @@ -1,14 +1,14 @@ 'use strict'; // Root-only test cases -test.only('#Root-Suite, should run this tdd test-case #1', function () { +test.only('#Root-Suite, should run this tdd test-case #1', function() { expect(true).to.equal(true); }); -test('#Root-Suite, should not run this tdd test-case #2', function () { +test('#Root-Suite, should not run this tdd test-case #2', function() { expect(false).to.equal(true); }); -test('#Root-Suite, should not run this tdd test-case #3', function () { +test('#Root-Suite, should not run this tdd test-case #3', function() { expect(false).to.equal(true); }); diff --git a/test/only/qunit.spec.js b/test/only/qunit.spec.js index 1e1c84c532..b027602118 100644 --- a/test/only/qunit.spec.js +++ b/test/only/qunit.spec.js @@ -1,75 +1,75 @@ 'use strict'; // Root Suite -test.only('#Root-Suite, should run this test-case #1', function () { +test.only('#Root-Suite, should run this test-case #1', function() { expect(true).to.equal(true); }); -test.only('#Root-Suite, should run this test-case #2', function () { +test.only('#Root-Suite, should run this test-case #2', function() { expect(true).to.equal(true); }); -test('#Root-Suite, should not run this test', function () { +test('#Root-Suite, should not run this test', function() { expect(false).to.equal(true); }); suite('should only run .only test in this qunit suite'); -test('should not run this test', function () { +test('should not run this test', function() { expect(0).to.equal(1, 'this test should have been skipped'); }); -test.only('should run this test', function () { +test.only('should run this test', function() { expect(0).to.equal(0, 'this .only test should run'); }); -test('should run this test, not (includes the title of the .only test)', function () { +test('should run this test, not (includes the title of the .only test)', function() { expect(0).to.equal(1, 'this test should have been skipped'); }); // Mark suite suite.only('should run all tests in this suite'); -test('should run this test #1', function () { +test('should run this test #1', function() { expect(true).to.equal(true); }); -test('should run this test #2', function () { +test('should run this test #2', function() { expect(true).to.equal(true); }); -test('should run this test #3', function () { +test('should run this test #3', function() { expect(true).to.equal(true); }); // Unmark this suite -suite('should not run any of this suite\'s tests'); +suite("should not run any of this suite's tests"); -test('should not run this test', function () { +test('should not run this test', function() { expect(false).to.equal(true); }); -test('should not run this test', function () { +test('should not run this test', function() { expect(false).to.equal(true); }); -test('should not run this test', function () { +test('should not run this test', function() { expect(false).to.equal(true); }); // Mark test as `only` override the suite behavior suite.only('should run only tests that marked as `only`'); -test('should not run this test #1', function () { +test('should not run this test #1', function() { expect(false).to.equal(true); }); -test.only('should not run this test #2', function () { +test.only('should not run this test #2', function() { expect(true).to.equal(true); }); -test('should not run this test #3', function () { +test('should not run this test #3', function() { expect(false).to.equal(true); }); -test.only('should not run this test #4', function () { +test.only('should not run this test #4', function() { expect(true).to.equal(true); }); diff --git a/test/only/tdd.spec.js b/test/only/tdd.spec.js index 425828f8b1..981bbfeb4b 100644 --- a/test/only/tdd.spec.js +++ b/test/only/tdd.spec.js @@ -1,77 +1,77 @@ 'use strict'; -suite('should only run .only test in this tdd suite', function () { - test('should not run this test', function () { +suite('should only run .only test in this tdd suite', function() { + test('should not run this test', function() { expect(0).to.equal(1, 'this test should have been skipped'); }); - test.only('should run this test', function () { + test.only('should run this test', function() { expect(0).to.equal(0, 'this .only test should run'); }); - test('should run this test, not (includes the title of the .only test)', function () { + test('should run this test, not (includes the title of the .only test)', function() { expect(0).to.equal(1, 'this test should have been skipped'); }); }); -suite('should not run this suite', function () { - test('should not run this test', function () { +suite('should not run this suite', function() { + test('should not run this test', function() { expect(true).to.equal(false); }); - test('should not run this test', function () { + test('should not run this test', function() { expect(true).to.equal(false); }); - test('should not run this test', function () { + test('should not run this test', function() { expect(true).to.equal(false); }); }); -suite.only('should run all tests in this tdd suite', function () { - test('should run this test #1', function () { +suite.only('should run all tests in this tdd suite', function() { + test('should run this test #1', function() { expect(true).to.equal(true); }); - test('should run this test #2', function () { + test('should run this test #2', function() { expect(1).to.equal(1); }); - test('should run this test #3', function () { + test('should run this test #3', function() { expect('foo').to.equal('foo'); }); }); -suite('should run only suites that marked as `only`', function () { - suite.only('should run all this tdd suite', function () { - test('should run this test #1', function () { +suite('should run only suites that marked as `only`', function() { + suite.only('should run all this tdd suite', function() { + test('should run this test #1', function() { expect(true).to.equal(true); }); - test('should run this test #2', function () { + test('should run this test #2', function() { expect(true).to.equal(true); }); }); - suite('should not run this suite', function () { - test('should not run this test', function () { + suite('should not run this suite', function() { + test('should not run this test', function() { expect(true).to.equal(false); }); }); }); // Nested situation -suite('should not run parent tests', function () { - test('should not run this test', function () { +suite('should not run parent tests', function() { + test('should not run this test', function() { expect(true).to.equal(false); }); - suite('and not the child tests too', function () { - test('should not run this test', function () { + suite('and not the child tests too', function() { + test('should not run this test', function() { expect(true).to.equal(false); }); - suite.only('but run all the tests in this suite', function () { - test('should run this test #1', function () { + suite.only('but run all the tests in this suite', function() { + test('should run this test #1', function() { expect(true).to.equal(true); }); - test('should run this test #2', function () { + test('should run this test #2', function() { expect(true).to.equal(true); }); }); @@ -79,49 +79,49 @@ suite('should not run parent tests', function () { }); // mark test as `only` override the suite behavior -suite.only('should run only tests that marked as `only`', function () { - test('should not run this test #1', function () { +suite.only('should run only tests that marked as `only`', function() { + test('should not run this test #1', function() { expect(false).to.equal(true); }); - test.only('should run this test #2', function () { + test.only('should run this test #2', function() { expect(true).to.equal(true); }); - test('should not run this test #3', function () { + test('should not run this test #3', function() { expect(false).to.equal(true); }); - test.only('should run this test #4', function () { + test.only('should run this test #4', function() { expect(true).to.equal(true); }); }); -suite.only('Should run only test cases that mark as only', function () { - test.only('should runt his test', function () { +suite.only('Should run only test cases that mark as only', function() { + test.only('should runt his test', function() { expect(true).to.equal(true); }); - test('should not run this test', function () { + test('should not run this test', function() { expect(false).to.equal(true); }); - suite('should not run this suite', function () { - test('should not run this test', function () { + suite('should not run this suite', function() { + test('should not run this test', function() { expect(false).to.equal(true); }); }); }); // Root Suite -test.only('#Root-Suite, should run this test-case #1', function () { +test.only('#Root-Suite, should run this test-case #1', function() { expect(true).to.equal(true); }); -test.only('#Root-Suite, should run this test-case #2', function () { +test.only('#Root-Suite, should run this test-case #2', function() { expect(true).to.equal(true); }); -test('#Root-Suite, should not run this test', function () { +test('#Root-Suite, should not run this test', function() { expect(false).to.equal(true); }); diff --git a/test/reporters/base.spec.js b/test/reporters/base.spec.js index ce815264ea..dc7065309b 100644 --- a/test/reporters/base.spec.js +++ b/test/reporters/base.spec.js @@ -8,7 +8,7 @@ var Assert = require('assert').AssertionError; var makeTest = require('./helpers').makeTest; var createElements = require('./helpers').createElements; -describe('Base reporter', function () { +describe('Base reporter', function() { var stdout; var stdoutWrite; var useColors; @@ -16,27 +16,27 @@ describe('Base reporter', function () { var errOut; var test; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; useColors = Base.useColors; Base.useColors = false; }); - afterEach(function () { + afterEach(function() { process.stdout.write = stdoutWrite; Base.useColors = useColors; }); - describe('showDiff', function () { - beforeEach(function () { - err = new Assert({ actual: 'foo', expected: 'bar' }); + describe('showDiff', function() { + beforeEach(function() { + err = new Assert({actual: 'foo', expected: 'bar'}); }); - it('should show diffs by default', function () { + it('should show diffs by default', function() { test = makeTest(err); Base.list([test]); @@ -46,7 +46,7 @@ describe('Base reporter', function () { expect(errOut).to.match(/\+ expected/); }); - it('should show diffs if property set to `true`', function () { + it('should show diffs if property set to `true`', function() { err.showDiff = true; test = makeTest(err); @@ -57,7 +57,7 @@ describe('Base reporter', function () { expect(errOut).to.match(/\+ expected/); }); - it('should not show diffs when showDiff property set to `false`', function () { + it('should not show diffs when showDiff property set to `false`', function() { err.showDiff = false; test = makeTest(err); @@ -68,7 +68,7 @@ describe('Base reporter', function () { expect(errOut).to.not.match(/\+ expected/); }); - it('should not show diffs when expected is not defined', function () { + it('should not show diffs when expected is not defined', function() { err = new Error('ouch'); test = makeTest(err); @@ -80,7 +80,7 @@ describe('Base reporter', function () { expect(errOut).to.not.match(/\+ expected/); }); - it('should not show diffs when hideDiff is set', function () { + it('should not show diffs when hideDiff is set', function() { test = makeTest(err); Base.hideDiff = true; @@ -93,9 +93,9 @@ describe('Base reporter', function () { }); }); - describe('Getting two strings', function () { + describe('Getting two strings', function() { // Fix regression V1.2.1(see: issue #1241) - it('should show strings diff as is', function () { + it('should show strings diff as is', function() { err = new Error('test'); err.actual = 'foo\nbar'; @@ -108,50 +108,56 @@ describe('Base reporter', function () { errOut = stdout.join('\n'); expect(errOut).to.not.match(/"foo\\nbar"/); - expect(errOut).to.match(/foo/).and.match(/bar/); + expect(errOut) + .to.match(/foo/) + .and.match(/bar/); expect(errOut).to.match(/test/); expect(errOut).to.match(/actual/); expect(errOut).to.match(/expected/); }); }); - describe('Diff generation', function () { + describe('Diff generation', function() { var oldInlineDiffs; var actual; var expected; var output; - beforeEach(function () { + beforeEach(function() { oldInlineDiffs = Base.inlineDiffs; }); - afterEach(function () { + afterEach(function() { Base.inlineDiffs = oldInlineDiffs; }); - it('should generate unified diffs if `inlineDiff === false`', function () { + it('should generate unified diffs if `inlineDiff === false`', function() { actual = 'a foo unified diff'; expected = 'a bar unified diff'; Base.inlineDiffs = false; output = Base.generateDiff(actual, expected); - expect(output).to.equal('\n + expected - actual\n\n -a foo unified diff\n +a bar unified diff\n '); + expect(output).to.equal( + '\n + expected - actual\n\n -a foo unified diff\n +a bar unified diff\n ' + ); }); - it('should generate inline diffs if `inlineDiffs === true`', function () { + it('should generate inline diffs if `inlineDiffs === true`', function() { actual = 'a foo inline diff'; expected = 'a bar inline diff'; Base.inlineDiffs = true; output = Base.generateDiff(actual, expected); - expect(output).to.equal(' \n actual expected\n \n a foobar inline diff\n '); + expect(output).to.equal( + ' \n actual expected\n \n a foobar inline diff\n ' + ); }); }); - describe('Inline strings diff', function () { - it('should show single line diff if property set to `true`', function () { + describe('Inline strings diff', function() { + it('should show single line diff if property set to `true`', function() { err = new Error('test'); err.actual = 'a foo inline diff'; @@ -170,7 +176,7 @@ describe('Base reporter', function () { expect(errOut).to.match(/expected/); }); - it('should split lines when string has more than 4 line breaks', function () { + it('should split lines when string has more than 4 line breaks', function() { err = new Error('test'); err.actual = 'a\nfoo\ninline\ndiff\nwith\nmultiple lines'; @@ -195,14 +201,14 @@ describe('Base reporter', function () { }); }); - describe('unified diff reporter', function () { - beforeEach(function () { + describe('unified diff reporter', function() { + beforeEach(function() { err = new Error('test'); }); - it('should separate diff hunks by two dashes', function () { - err.actual = createElements({ from: 2, to: 11 }); - err.expected = createElements({ from: 1, to: 10 }); + it('should separate diff hunks by two dashes', function() { + err.actual = createElements({from: 2, to: 11}); + err.expected = createElements({from: 1, to: 10}); err.showDiff = true; test = makeTest(err); @@ -230,13 +236,13 @@ describe('Base reporter', function () { /actual/ ]; - regexesToMatch.forEach(function (aRegex) { + regexesToMatch.forEach(function(aRegex) { expect(errOut).to.match(aRegex); }); }); }); - it('should stringify objects', function () { + it('should stringify objects', function() { err = new Error('test'); err.actual = {key: 'a1'}; @@ -253,7 +259,7 @@ describe('Base reporter', function () { expect(errOut).to.match(/\+ expected/); }); - it('should stringify Object.create(null)', function () { + it('should stringify Object.create(null)', function() { err = new Error('test'); err.actual = Object.create(null); @@ -272,7 +278,7 @@ describe('Base reporter', function () { expect(errOut).to.match(/\+ expected/); }); - it('should handle error messages that are not strings', function () { + it('should handle error messages that are not strings', function() { try { assert(false, true); } catch (err) { @@ -291,7 +297,7 @@ describe('Base reporter', function () { } }); - it('should interpret chaijs custom error messages', function () { + it('should interpret chaijs custom error messages', function() { try { // expect(43, 'custom error message').to.equal(42); // AssertionError: custom error message: expected 43 to equal 42. @@ -313,7 +319,7 @@ describe('Base reporter', function () { } }); - it('should remove message from stack', function () { + it('should remove message from stack', function() { err = { message: 'Error', stack: 'Error\nfoo\nbar', @@ -327,10 +333,12 @@ describe('Base reporter', function () { expect(errOut).to.equal('1) test title:\n Error\n foo\n bar'); }); - it('should use the inspect() property if `message` is not set', function () { + it('should use the inspect() property if `message` is not set', function() { err = { showDiff: false, - inspect: function () { return 'an error happened'; } + inspect: function() { + return 'an error happened'; + } }; test = makeTest(err); Base.list([test]); @@ -338,7 +346,7 @@ describe('Base reporter', function () { expect(errOut).to.equal('1) test title:\n an error happened'); }); - it('should set an empty message if `message` and `inspect()` are not set', function () { + it('should set an empty message if `message` and `inspect()` are not set', function() { err = { showDiff: false }; @@ -348,7 +356,7 @@ describe('Base reporter', function () { expect(errOut).to.equal('1) test title:'); }); - it('should not modify stack if it does not contain message', function () { + it('should not modify stack if it does not contain message', function() { err = { message: 'Error', stack: 'foo\nbar', diff --git a/test/reporters/doc.spec.js b/test/reporters/doc.spec.js index 4f3b48868a..b6584e004b 100644 --- a/test/reporters/doc.spec.js +++ b/test/reporters/doc.spec.js @@ -5,27 +5,27 @@ var Doc = reporters.Doc; var createMockRunner = require('./helpers.js').createMockRunner; -describe('Doc reporter', function () { +describe('Doc reporter', function() { var stdout; var stdoutWrite; var runner; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; }); - describe('on suite', function () { - describe('if suite root does not exist', function () { + describe('on suite', function() { + describe('if suite root does not exist', function() { var expectedTitle = 'expectedTitle'; var unescapedTitle = '
      ' + expectedTitle + '
      '; var suite = { root: false, title: expectedTitle }; - it('should log html with indents and expected title', function () { + it('should log html with indents and expected title', function() { runner = createMockRunner('suite', 'suite', null, null, suite); Doc.call(this, runner); process.stdout.write = stdoutWrite; @@ -36,7 +36,7 @@ describe('Doc reporter', function () { ]; expect(stdout).to.eql(expectedArray); }); - it('should escape title where necessary', function () { + it('should escape title where necessary', function() { var suite = { root: false, title: unescapedTitle @@ -53,11 +53,11 @@ describe('Doc reporter', function () { expect(stdout).to.eql(expectedArray); }); }); - describe('if suite root does exist', function () { + describe('if suite root does exist', function() { var suite = { root: true }; - it('should not log any html', function () { + it('should not log any html', function() { runner = createMockRunner('suite', 'suite', null, null, suite); Doc.call(this, runner); process.stdout.write = stdoutWrite; @@ -66,26 +66,24 @@ describe('Doc reporter', function () { }); }); - describe('on suite end', function () { - describe('if suite root does not exist', function () { + describe('on suite end', function() { + describe('if suite root does not exist', function() { var suite = { root: false }; - it('should log expected html with indents', function () { + it('should log expected html with indents', function() { runner = createMockRunner('suite end', 'suite end', null, null, suite); Doc.call(this, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - '
\n', '\n' - ]; + var expectedArray = [' \n', '\n']; expect(stdout).to.eql(expectedArray); }); }); - describe('if suite root does exist', function () { + describe('if suite root does exist', function() { var suite = { root: true }; - it('should not log any html', function () { + it('should not log any html', function() { runner = createMockRunner('suite end', 'suite end', null, null, suite); Doc.call(this, runner); process.stdout.write = stdoutWrite; @@ -94,17 +92,17 @@ describe('Doc reporter', function () { }); }); - describe('on pass', function () { + describe('on pass', function() { var expectedTitle = 'some tite'; var expectedBody = 'some body'; var test = { title: expectedTitle, body: expectedBody, - slow: function () { + slow: function() { return ''; } }; - it('should log html with indents and expected title and body', function () { + it('should log html with indents and expected title and body', function() { runner = createMockRunner('pass', 'pass', null, null, test); Doc.call(this, runner); process.stdout.write = stdoutWrite; @@ -114,14 +112,16 @@ describe('Doc reporter', function () { ]; expect(stdout).to.eql(expectedArray); }); - it('should escape title and body where necessary', function () { + it('should escape title and body where necessary', function() { var unescapedTitle = '
' + expectedTitle + '
'; var unescapedBody = '
' + expectedBody + '
'; test.title = unescapedTitle; test.body = unescapedBody; - var expectedEscapedTitle = '<div>' + expectedTitle + '</div>'; - var expectedEscapedBody = '<div>' + expectedBody + '</div>'; + var expectedEscapedTitle = + '<div>' + expectedTitle + '</div>'; + var expectedEscapedBody = + '<div>' + expectedBody + '</div>'; runner = createMockRunner('pass', 'pass', null, null, test); Doc.call(this, runner); process.stdout.write = stdoutWrite; @@ -133,44 +133,65 @@ describe('Doc reporter', function () { }); }); - describe('on fail', function () { + describe('on fail', function() { var expectedTitle = 'some tite'; var expectedBody = 'some body'; var expectedError = 'some error'; var test = { title: expectedTitle, body: expectedBody, - slow: function () { + slow: function() { return ''; } }; - it('should log html with indents and expected title, body and error', function () { - runner = createMockRunner('fail two args', 'fail', null, null, test, expectedError); + it('should log html with indents and expected title, body and error', function() { + runner = createMockRunner( + 'fail two args', + 'fail', + null, + null, + test, + expectedError + ); Doc.call(this, runner); process.stdout.write = stdoutWrite; var expectedArray = [ '
' + expectedTitle + '
\n', - '
' + expectedBody + '
\n', + '
' +
+          expectedBody +
+          '
\n', '
' + expectedError + '
\n' ]; expect(stdout).to.eql(expectedArray); }); - it('should escape title, body and error where necessary', function () { + it('should escape title, body and error where necessary', function() { var unescapedTitle = '
' + expectedTitle + '
'; var unescapedBody = '
' + expectedBody + '
'; var unescapedError = '
' + expectedError + '
'; test.title = unescapedTitle; test.body = unescapedBody; - var expectedEscapedTitle = '<div>' + expectedTitle + '</div>'; - var expectedEscapedBody = '<div>' + expectedBody + '</div>'; - var expectedEscapedError = '<div>' + expectedError + '</div>'; - runner = createMockRunner('fail two args', 'fail', null, null, test, unescapedError); + var expectedEscapedTitle = + '<div>' + expectedTitle + '</div>'; + var expectedEscapedBody = + '<div>' + expectedBody + '</div>'; + var expectedEscapedError = + '<div>' + expectedError + '</div>'; + runner = createMockRunner( + 'fail two args', + 'fail', + null, + null, + test, + unescapedError + ); Doc.call(this, runner); process.stdout.write = stdoutWrite; var expectedArray = [ '
' + expectedEscapedTitle + '
\n', - '
' + expectedEscapedBody + '
\n', + '
' +
+          expectedEscapedBody +
+          '
\n', '
' + expectedEscapedError + '
\n' ]; expect(stdout).to.eql(expectedArray); diff --git a/test/reporters/dot.spec.js b/test/reporters/dot.spec.js index 228487ff0d..701d179f37 100644 --- a/test/reporters/dot.spec.js +++ b/test/reporters/dot.spec.js @@ -6,17 +6,17 @@ var Base = reporters.Base; var createMockRunner = require('./helpers.js').createMockRunner; -describe('Dot reporter', function () { +describe('Dot reporter', function() { var stdout; var stdoutWrite; var runner; var useColors; var windowWidth; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; useColors = Base.useColors; @@ -25,136 +25,119 @@ describe('Dot reporter', function () { Base.window.width = 0; }); - afterEach(function () { + afterEach(function() { Base.useColors = useColors; Base.window.width = windowWidth; }); - describe('on start', function () { - it('should return a new line', function () { + describe('on start', function() { + it('should return a new line', function() { runner = createMockRunner('start', 'start'); - Dot.call({epilogue: function () {}}, runner); + Dot.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - '\n' - ]; + var expectedArray = ['\n']; expect(stdout).to.eql(expectedArray); }); }); - describe('on pending', function () { - describe('if window width is greater than 1', function () { - beforeEach(function () { + describe('on pending', function() { + describe('if window width is greater than 1', function() { + beforeEach(function() { Base.window.width = 2; }); - it('should return a new line and then a coma', function () { + it('should return a new line and then a coma', function() { runner = createMockRunner('pending', 'pending'); - Dot.call({epilogue: function () {}}, runner); + Dot.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - '\n ', - Base.symbols.comma - ]; + var expectedArray = ['\n ', Base.symbols.comma]; expect(stdout).to.eql(expectedArray); }); }); - describe('if window width is equal to or less than 1', function () { - it('should return a coma', function () { + describe('if window width is equal to or less than 1', function() { + it('should return a coma', function() { runner = createMockRunner('pending', 'pending'); - Dot.call({epilogue: function () {}}, runner); + Dot.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - Base.symbols.comma - ]; + var expectedArray = [Base.symbols.comma]; expect(stdout).to.eql(expectedArray); }); }); }); - describe('on pass', function () { + describe('on pass', function() { var test = { duration: 1, - slow: function () { return 2; } + slow: function() { + return 2; + } }; - describe('if window width is greater than 1', function () { - beforeEach(function () { + describe('if window width is greater than 1', function() { + beforeEach(function() { Base.window.width = 2; }); - describe('if test speed is fast', function () { - it('should return a new line and then a dot', function () { + describe('if test speed is fast', function() { + it('should return a new line and then a dot', function() { runner = createMockRunner('pass', 'pass', null, null, test); - Dot.call({epilogue: function () {}}, runner); + Dot.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - '\n ', - Base.symbols.dot - ]; + var expectedArray = ['\n ', Base.symbols.dot]; expect(stdout).to.eql(expectedArray); }); }); }); - describe('if window width is equal to or less than 1', function () { - describe('if test speed is fast', function () { - it('should return a dot', function () { + describe('if window width is equal to or less than 1', function() { + describe('if test speed is fast', function() { + it('should return a dot', function() { runner = createMockRunner('pass', 'pass', null, null, test); - Dot.call({epilogue: function () {}}, runner); + Dot.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - Base.symbols.dot - ]; + var expectedArray = [Base.symbols.dot]; expect(stdout).to.eql(expectedArray); }); }); - describe('if test speed is slow', function () { - it('should return a dot', function () { + describe('if test speed is slow', function() { + it('should return a dot', function() { test.duration = 2; runner = createMockRunner('pass', 'pass', null, null, test); - Dot.call({epilogue: function () {}}, runner); + Dot.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - Base.symbols.dot - ]; + var expectedArray = [Base.symbols.dot]; expect(stdout).to.eql(expectedArray); }); }); }); }); - describe('on fail', function () { + describe('on fail', function() { var test = { test: { err: 'some error' } }; - describe('if window width is greater than 1', function () { - beforeEach(function () { + describe('if window width is greater than 1', function() { + beforeEach(function() { Base.window.width = 2; }); - it('should return a new line and then an exclamation mark', function () { + it('should return a new line and then an exclamation mark', function() { runner = createMockRunner('fail', 'fail', null, null, test); - Dot.call({epilogue: function () {}}, runner); + Dot.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - '\n ', - Base.symbols.bang - ]; + var expectedArray = ['\n ', Base.symbols.bang]; expect(stdout).to.eql(expectedArray); }); }); - describe('if window width is equal to or less than 1', function () { - it('should return an exclamation mark', function () { + describe('if window width is equal to or less than 1', function() { + it('should return an exclamation mark', function() { runner = createMockRunner('fail', 'fail', null, null, test); - Dot.call({epilogue: function () {}}, runner); + Dot.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - Base.symbols.bang - ]; + var expectedArray = [Base.symbols.bang]; expect(stdout).to.eql(expectedArray); }); }); }); - describe('on end', function () { - it('should call the epilogue', function () { + describe('on end', function() { + it('should call the epilogue', function() { runner = createMockRunner('end', 'end'); var epilogueCalled = false; - var epilogue = function () { + var epilogue = function() { epilogueCalled = true; }; Dot.call({epilogue: epilogue}, runner); diff --git a/test/reporters/helpers.js b/test/reporters/helpers.js index aa1af15742..e0c6604216 100644 --- a/test/reporters/helpers.js +++ b/test/reporters/helpers.js @@ -8,21 +8,28 @@ scope of this function for the tests to run properly. */ -function createMockRunner (runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { - var runnerFunction = createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2); +function createMockRunner(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { + var runnerFunction = createRunnerFunction( + runStr, + ifStr1, + ifStr2, + ifStr3, + arg1, + arg2 + ); return { on: runnerFunction, once: runnerFunction }; } -function createRunnerFunction (runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { +function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { var test = null; switch (runStr) { case 'start': case 'pending': case 'end': - return function (event, callback) { + return function(event, callback) { if (event === ifStr1) { callback(); } @@ -34,7 +41,7 @@ function createRunnerFunction (runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { case 'suite end': case 'test end': test = arg1; - return function (event, callback) { + return function(event, callback) { if (event === ifStr1) { callback(test); } @@ -42,14 +49,14 @@ function createRunnerFunction (runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { case 'fail two args': test = arg1; var expectedError = arg2; - return function (event, callback) { + return function(event, callback) { if (event === ifStr1) { callback(test, expectedError); } }; case 'start test': test = arg1; - return function (event, callback) { + return function(event, callback) { if (event === ifStr1) { callback(); } @@ -59,7 +66,7 @@ function createRunnerFunction (runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { }; case 'suite suite end': var expectedSuite = arg1; - return function (event, callback) { + return function(event, callback) { if (event === ifStr1) { callback(expectedSuite); } @@ -72,7 +79,7 @@ function createRunnerFunction (runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { }; case 'pass end': test = arg1; - return function (event, callback) { + return function(event, callback) { if (event === ifStr1) { callback(test); } @@ -83,7 +90,7 @@ function createRunnerFunction (runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { case 'test end fail': test = arg1; var error = arg2; - return function (event, callback) { + return function(event, callback) { if (event === ifStr1) { callback(); } @@ -92,7 +99,7 @@ function createRunnerFunction (runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { } }; case 'fail end pass': - return function (event, callback) { + return function(event, callback) { test = arg1; if (event === ifStr1) { callback(test, {}); @@ -111,16 +118,16 @@ function createRunnerFunction (runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) { } } -function makeTest (err) { +function makeTest(err) { return { err: err, - titlePath: function () { + titlePath: function() { return ['test title']; } }; } -function createElements (argObj) { +function createElements(argObj) { var res = []; for (var i = argObj.from; i <= argObj.to; i++) { res.push('element ' + i); @@ -128,7 +135,7 @@ function createElements (argObj) { return res; } -function makeExpectedTest ( +function makeExpectedTest( expectedTitle, expectedFullTitle, expectedDuration, @@ -137,14 +144,14 @@ function makeExpectedTest ( ) { return { title: expectedTitle, - fullTitle: function () { + fullTitle: function() { return expectedFullTitle; }, duration: expectedDuration, - currentRetry: function () { + currentRetry: function() { return currentRetry; }, - slow: function () {} + slow: function() {} }; } diff --git a/test/reporters/json-stream.spec.js b/test/reporters/json-stream.spec.js index 0d11597038..bfd0c16b81 100644 --- a/test/reporters/json-stream.spec.js +++ b/test/reporters/json-stream.spec.js @@ -6,7 +6,7 @@ var JSONStream = reporters.JSONStream; var createMockRunner = require('./helpers').createMockRunner; var makeExpectedTest = require('./helpers').makeExpectedTest; -describe('Json Stream reporter', function () { +describe('Json Stream reporter', function() { var runner; var stdout; var stdoutWrite; @@ -15,23 +15,28 @@ describe('Json Stream reporter', function () { var expectedFullTitle = 'full title'; var expectedDuration = 1000; var currentRetry = 1; - var expectedTest = makeExpectedTest(expectedTitle, expectedFullTitle, expectedDuration, currentRetry); + var expectedTest = makeExpectedTest( + expectedTitle, + expectedFullTitle, + expectedDuration, + currentRetry + ); var expectedErrorMessage = 'error message'; var expectedErrorStack = 'error stack'; var expectedError = { message: expectedErrorMessage }; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; }); - describe('on start', function () { - it('should write stringified start with expected total', function () { + describe('on start', function() { + it('should write stringified start with expected total', function() { runner = createMockRunner('start', 'start'); var expectedTotal = 12; runner.total = expectedTotal; @@ -43,46 +48,96 @@ describe('Json Stream reporter', function () { }); }); - describe('on pass', function () { - it('should write stringified test data', function () { + describe('on pass', function() { + it('should write stringified test data', function() { runner = createMockRunner('pass', 'pass', null, null, expectedTest); JSONStream.call({}, runner); process.stdout.write = stdoutWrite; - expect(stdout[0]).to.eql('["pass",{"title":"' + expectedTitle + '","fullTitle":"' + expectedFullTitle + '","duration":' + expectedDuration + ',"currentRetry":' + currentRetry + '}]\n'); + expect(stdout[0]).to.eql( + '["pass",{"title":"' + + expectedTitle + + '","fullTitle":"' + + expectedFullTitle + + '","duration":' + + expectedDuration + + ',"currentRetry":' + + currentRetry + + '}]\n' + ); }); }); - describe('on fail', function () { - describe('if error stack exists', function () { - it('should write stringified test data with error data', function () { + describe('on fail', function() { + describe('if error stack exists', function() { + it('should write stringified test data with error data', function() { expectedError.stack = expectedErrorStack; - runner = createMockRunner('fail two args', 'fail', null, null, expectedTest, expectedError); + runner = createMockRunner( + 'fail two args', + 'fail', + null, + null, + expectedTest, + expectedError + ); JSONStream.call({}, runner); process.stdout.write = stdoutWrite; - expect(stdout[0]).to.eql('["fail",{"title":"' + expectedTitle + '","fullTitle":"' + expectedFullTitle + '","duration":' + expectedDuration + ',"currentRetry":' + currentRetry + ',"err":"' + expectedErrorMessage + '","stack":"' + expectedErrorStack + '"}]\n'); + expect(stdout[0]).to.eql( + '["fail",{"title":"' + + expectedTitle + + '","fullTitle":"' + + expectedFullTitle + + '","duration":' + + expectedDuration + + ',"currentRetry":' + + currentRetry + + ',"err":"' + + expectedErrorMessage + + '","stack":"' + + expectedErrorStack + + '"}]\n' + ); }); }); - describe('if error stack does not exist', function () { - it('should write stringified test data with error data', function () { + describe('if error stack does not exist', function() { + it('should write stringified test data with error data', function() { expectedError.stack = null; - runner = createMockRunner('fail two args', 'fail', null, null, expectedTest, expectedError); + runner = createMockRunner( + 'fail two args', + 'fail', + null, + null, + expectedTest, + expectedError + ); JSONStream.call({}, runner); process.stdout.write = stdoutWrite; - expect(stdout[0]).to.eql('["fail",{"title":"' + expectedTitle + '","fullTitle":"' + expectedFullTitle + '","duration":' + expectedDuration + ',"currentRetry":' + currentRetry + ',"err":"' + expectedErrorMessage + '","stack":null}]\n'); + expect(stdout[0]).to.eql( + '["fail",{"title":"' + + expectedTitle + + '","fullTitle":"' + + expectedFullTitle + + '","duration":' + + expectedDuration + + ',"currentRetry":' + + currentRetry + + ',"err":"' + + expectedErrorMessage + + '","stack":null}]\n' + ); }); }); }); - describe('on end', function () { - it('should write end details', function () { + describe('on end', function() { + it('should write end details', function() { runner = createMockRunner('end', 'end'); JSONStream.call({}, runner); process.stdout.write = stdoutWrite; diff --git a/test/reporters/json.spec.js b/test/reporters/json.spec.js index a40eead75f..fcab2882d2 100644 --- a/test/reporters/json.spec.js +++ b/test/reporters/json.spec.js @@ -5,11 +5,11 @@ var Suite = Mocha.Suite; var Runner = Mocha.Runner; var Test = Mocha.Test; -describe('json reporter', function () { +describe('json reporter', function() { var suite, runner; var testTitle = 'json test 1'; - beforeEach(function () { + beforeEach(function() { var mocha = new Mocha({ reporter: 'json' }); @@ -19,14 +19,16 @@ describe('json reporter', function () { var mochaReporter = new mocha._reporter(runner); }); - it('should have 1 test failure', function (done) { - var error = { message: 'oh shit' }; + it('should have 1 test failure', function(done) { + var error = {message: 'oh shit'}; - suite.addTest(new Test(testTitle, function (done) { - done(new Error(error.message)); - })); + suite.addTest( + new Test(testTitle, function(done) { + done(new Error(error.message)); + }) + ); - runner.run(function (failureCount) { + runner.run(function(failureCount) { expect(failureCount).to.be(1); expect(runner).to.have.property('testResults'); expect(runner.testResults).to.have.property('failures'); @@ -42,10 +44,10 @@ describe('json reporter', function () { }); }); - it('should have 1 test pending', function (done) { + it('should have 1 test pending', function(done) { suite.addTest(new Test(testTitle)); - runner.run(function (failureCount) { + runner.run(function(failureCount) { expect(failureCount).to.be(0); expect(runner).to.have.property('testResults'); expect(runner.testResults).to.have.property('pending'); @@ -59,19 +61,21 @@ describe('json reporter', function () { }); }); - it('should handle circular objects in errors', function (done) { + it('should handle circular objects in errors', function(done) { var testTitle = 'json test 1'; - function CircleError () { + function CircleError() { this.message = 'oh shit'; this.circular = this; } var error = new CircleError(); - suite.addTest(new Test(testTitle, function (done) { - throw error; - })); + suite.addTest( + new Test(testTitle, function(done) { + throw error; + }) + ); - runner.run(function (failureCount) { + runner.run(function(failureCount) { expect(failureCount).to.equal(1); expect(runner).to.have.property('testResults'); expect(runner.testResults).to.have.property('failures'); diff --git a/test/reporters/landing.spec.js b/test/reporters/landing.spec.js index 633c29e823..ac110e6d23 100644 --- a/test/reporters/landing.spec.js +++ b/test/reporters/landing.spec.js @@ -6,7 +6,7 @@ var Base = reporters.Base; var createMockRunner = require('./helpers').createMockRunner; -describe('Landing reporter', function () { +describe('Landing reporter', function() { var stdout; var stdoutWrite; var runner; @@ -24,10 +24,10 @@ describe('Landing reporter', function () { resetCode ]; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; useColors = Base.useColors; @@ -36,15 +36,15 @@ describe('Landing reporter', function () { Base.window.width = 1; }); - afterEach(function () { + afterEach(function() { Base.useColors = useColors; Base.window.width = windowWidth; }); - describe('on start', function () { - it('should write new lines', function () { + describe('on start', function() { + it('should write new lines', function() { var cachedCursor = Base.cursor; - Base.cursor.hide = function () {}; + Base.cursor.hide = function() {}; runner = createMockRunner('start', 'start'); Landing.call({}, runner); @@ -54,10 +54,10 @@ describe('Landing reporter', function () { Base.cursor = cachedCursor; }); - it('should call cursor hide', function () { + it('should call cursor hide', function() { var cachedCursor = Base.cursor; var calledCursorHide = false; - Base.cursor.hide = function () { + Base.cursor.hide = function() { calledCursorHide = true; }; runner = createMockRunner('start', 'start'); @@ -70,9 +70,9 @@ describe('Landing reporter', function () { }); }); - describe('on test end', function () { - describe('if test has failed', function () { - it('should write expected landing strip', function () { + describe('on test end', function() { + describe('if test has failed', function() { + it('should write expected landing strip', function() { var test = { state: 'failed' }; @@ -85,8 +85,8 @@ describe('Landing reporter', function () { expect(stdout).to.eql(expectedArray); }); }); - describe('if test has not failed', function () { - it('should write expected landing strip', function () { + describe('if test has not failed', function() { + it('should write expected landing strip', function() { var test = { state: 'success' }; @@ -100,21 +100,24 @@ describe('Landing reporter', function () { }); }); }); - describe('on end', function () { - it('should call cursor show and epilogue', function () { + describe('on end', function() { + it('should call cursor show and epilogue', function() { var cachedCursor = Base.cursor; var calledCursorShow = false; - Base.cursor.show = function () { + Base.cursor.show = function() { calledCursorShow = true; }; runner = createMockRunner('end', 'end'); var calledEpilogue = false; - Landing.call({ - epilogue: function () { - calledEpilogue = true; - } - }, runner); + Landing.call( + { + epilogue: function() { + calledEpilogue = true; + } + }, + runner + ); process.stdout.write = stdoutWrite; expect(calledEpilogue).to.be(true); diff --git a/test/reporters/list.spec.js b/test/reporters/list.spec.js index 7871caf82e..179e320ef5 100644 --- a/test/reporters/list.spec.js +++ b/test/reporters/list.spec.js @@ -6,7 +6,7 @@ var Base = reporters.Base; var createMockRunner = require('./helpers').createMockRunner; -describe('List reporter', function () { +describe('List reporter', function() { var stdout; var stdoutWrite; var runner; @@ -14,60 +14,57 @@ describe('List reporter', function () { var expectedTitle = 'some title'; var expectedDuration = 100; var test = { - fullTitle: function () { + fullTitle: function() { return expectedTitle; }, duration: expectedDuration, - slow: function () {} + slow: function() {} }; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; useColors = Base.useColors; Base.useColors = false; }); - afterEach(function () { + afterEach(function() { Base.useColors = useColors; }); - describe('on start and test', function () { - it('should write expected new line and title to the console', function () { + describe('on start and test', function() { + it('should write expected new line and title to the console', function() { runner = createMockRunner('start test', 'start', 'test', null, test); - List.call({epilogue: function () {}}, runner); + List.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; var startString = '\n'; var testString = ' ' + expectedTitle + ': '; - var expectedArray = [ - startString, - testString - ]; + var expectedArray = [startString, testString]; expect(stdout).to.eql(expectedArray); }); }); - describe('on pending', function () { - it('should write expected title to the console', function () { + describe('on pending', function() { + it('should write expected title to the console', function() { runner = createMockRunner('pending test', 'pending', null, null, test); - List.call({epilogue: function () {}}, runner); + List.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; expect(stdout[0]).to.eql(' - ' + expectedTitle + '\n'); }); }); - describe('on pass', function () { - it('should call cursor CR', function () { + describe('on pass', function() { + it('should call cursor CR', function() { var calledCursorCR = false; var cachedCursor = Base.cursor; - Base.cursor.CR = function () { + Base.cursor.CR = function() { calledCursorCR = true; }; runner = createMockRunner('pass', 'pass', null, null, test); - List.call({epilogue: function () {}}, runner); + List.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; @@ -75,32 +72,40 @@ describe('List reporter', function () { Base.cursor = cachedCursor; }); - it('should write expected symbol, title and duration to the console', function () { + it('should write expected symbol, title and duration to the console', function() { var cachedSymbols = Base.symbols; var expectedOkSymbol = 'OK'; Base.symbols.ok = expectedOkSymbol; var cachedCursor = Base.cursor; - Base.cursor.CR = function () {}; + Base.cursor.CR = function() {}; runner = createMockRunner('pass', 'pass', null, null, test); - List.call({epilogue: function () {}}, runner); + List.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - expect(stdout[0]).to.equal(' ' + expectedOkSymbol + ' ' + expectedTitle + ': ' + expectedDuration + 'ms\n'); + expect(stdout[0]).to.equal( + ' ' + + expectedOkSymbol + + ' ' + + expectedTitle + + ': ' + + expectedDuration + + 'ms\n' + ); Base.cursor = cachedCursor; Base.symbols = cachedSymbols; }); }); - describe('on fail', function () { - it('should call cursor CR', function () { + describe('on fail', function() { + it('should call cursor CR', function() { var calledCursorCR = false; var cachedCursor = Base.cursor; - Base.cursor.CR = function () { + Base.cursor.CR = function() { calledCursorCR = true; }; runner = createMockRunner('fail', 'fail', null, null, test); - List.call({epilogue: function () {}}, runner); + List.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; @@ -108,26 +113,28 @@ describe('List reporter', function () { Base.cursor = cachedCursor; }); - it('should write expected error number and title', function () { + it('should write expected error number and title', function() { var cachedCursor = Base.cursor; var expectedErrorCount = 1; - Base.cursor.CR = function () {}; + Base.cursor.CR = function() {}; runner = createMockRunner('fail', 'fail', null, null, test); - List.call({epilogue: function () {}}, runner); + List.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - expect(stdout[0]).to.equal(' ' + expectedErrorCount + ') ' + expectedTitle + '\n'); + expect(stdout[0]).to.equal( + ' ' + expectedErrorCount + ') ' + expectedTitle + '\n' + ); Base.cursor = cachedCursor; }); - it('should immediately construct fail strings', function () { - var actual = { a: 'actual' }; - var expected = { a: 'expected' }; + it('should immediately construct fail strings', function() { + var actual = {a: 'actual'}; + var expected = {a: 'expected'}; var checked = false; var err; test = {}; - runner.on = runner.once = function (event, callback) { + runner.on = runner.once = function(event, callback) { if (!checked && event === 'fail') { err = new Error('fake failure object with actual/expected'); err.actual = actual; @@ -137,7 +144,7 @@ describe('List reporter', function () { checked = true; } }; - List.call({epilogue: function () {}}, runner); + List.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; expect(typeof err.actual).to.equal('string'); @@ -145,15 +152,18 @@ describe('List reporter', function () { }); }); - describe('on end', function () { - it('should call epilogue', function () { + describe('on end', function() { + it('should call epilogue', function() { var calledEpilogue = false; runner = createMockRunner('end', 'end'); - List.call({ - epilogue: function () { - calledEpilogue = true; - } - }, runner); + List.call( + { + epilogue: function() { + calledEpilogue = true; + } + }, + runner + ); process.stdout.write = stdoutWrite; expect(calledEpilogue).to.be(true); diff --git a/test/reporters/markdown.spec.js b/test/reporters/markdown.spec.js index f6fcf095e0..4303ef2aaf 100644 --- a/test/reporters/markdown.spec.js +++ b/test/reporters/markdown.spec.js @@ -5,7 +5,7 @@ var Markdown = reporters.Markdown; var createMockRunner = require('./helpers').createMockRunner; -describe('Markdown reporter', function () { +describe('Markdown reporter', function() { var stdout; var stdoutWrite; var runner; @@ -13,44 +13,66 @@ describe('Markdown reporter', function () { var expectedFullTitle = 'full title'; var sluggedFullTitle = 'full-title'; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; }); - describe('on \'suite\'', function () { - it('should write expected slugged titles on \'end\' event', function () { + describe("on 'suite'", function() { + it("should write expected slugged titles on 'end' event", function() { var expectedSuite = { title: expectedTitle, - fullTitle: function () { return expectedFullTitle; }, - suites: [{ - title: expectedTitle, - fullTitle: function () { return expectedFullTitle; }, - suites: [] - }] + fullTitle: function() { + return expectedFullTitle; + }, + suites: [ + { + title: expectedTitle, + fullTitle: function() { + return expectedFullTitle; + }, + suites: [] + } + ] }; - runner = createMockRunner('suite suite end', 'suite', 'suite end', 'end', expectedSuite); + runner = createMockRunner( + 'suite suite end', + 'suite', + 'suite end', + 'end', + expectedSuite + ); runner.suite = expectedSuite; Markdown.call({}, runner); process.stdout.write = stdoutWrite; var expectedArray = [ '# TOC\n', - ' - [' + expectedTitle + '](#' + sluggedFullTitle + ')\n - [' + expectedTitle + '](#' + sluggedFullTitle + ')\n', + ' - [' + + expectedTitle + + '](#' + + sluggedFullTitle + + ')\n - [' + + expectedTitle + + '](#' + + sluggedFullTitle + + ')\n', '\n ' + expectedTitle + '\n' ]; expect(stdout).to.eql(expectedArray); }); }); - describe('on \'pass\'', function () { - it('should write test code inside js code block, on \'end\' event', function () { + describe("on 'pass'", function() { + it("should write test code inside js code block, on 'end' event", function() { var expectedSuite = { title: expectedTitle, - fullTitle: function () { return expectedFullTitle; }, + fullTitle: function() { + return expectedFullTitle; + }, suites: [] }; var expectedDuration = 1000; @@ -58,10 +80,14 @@ describe('Markdown reporter', function () { var expectedBody = 'some body'; var expectedTest = { title: expectedTitle, - fullTitle: function () { return expectedFullTitle; }, + fullTitle: function() { + return expectedFullTitle; + }, duration: expectedDuration, - currentRetry: function () { return currentRetry; }, - slow: function () {}, + currentRetry: function() { + return currentRetry; + }, + slow: function() {}, body: expectedBody }; runner = createMockRunner('pass end', 'pass', 'end', null, expectedTest); diff --git a/test/reporters/min.spec.js b/test/reporters/min.spec.js index 1312e21ea8..129a3b35d6 100644 --- a/test/reporters/min.spec.js +++ b/test/reporters/min.spec.js @@ -5,42 +5,42 @@ var Min = reporters.Min; var createMockRunner = require('./helpers').createMockRunner; -describe('Min reporter', function () { +describe('Min reporter', function() { var stdout; var stdoutWrite; var runner; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; }); - describe('on start', function () { - it('should clear screen then set cursor position', function () { + describe('on start', function() { + it('should clear screen then set cursor position', function() { runner = createMockRunner('start', 'start'); - Min.call({epilogue: function () {}}, runner); + Min.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - '\u001b[2J', - '\u001b[1;3H' - ]; + var expectedArray = ['\u001b[2J', '\u001b[1;3H']; expect(stdout).to.eql(expectedArray); }); }); - describe('on end', function () { - it('should call epilogue', function () { + describe('on end', function() { + it('should call epilogue', function() { var calledEpilogue = false; runner = createMockRunner('end', 'end'); - Min.call({ - epilogue: function () { - calledEpilogue = true; - } - }, runner); + Min.call( + { + epilogue: function() { + calledEpilogue = true; + } + }, + runner + ); process.stdout.write = stdoutWrite; expect(calledEpilogue).to.be(true); diff --git a/test/reporters/nyan.spec.js b/test/reporters/nyan.spec.js index 43e8c778e1..633a2ce4f8 100644 --- a/test/reporters/nyan.spec.js +++ b/test/reporters/nyan.spec.js @@ -6,129 +6,152 @@ var Base = reporters.Base; var createMockRunner = require('./helpers').createMockRunner; -describe('Nyan reporter', function () { - describe('events', function () { +describe('Nyan reporter', function() { + describe('events', function() { var runner; var stdout; var stdoutWrite; var calledDraw; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; }); - describe('on start', function () { - it('should call draw', function () { + describe('on start', function() { + it('should call draw', function() { calledDraw = false; runner = createMockRunner('start', 'start'); - NyanCat.call({ - draw: function () { - calledDraw = true; + NyanCat.call( + { + draw: function() { + calledDraw = true; + }, + generateColors: function() {} }, - generateColors: function () {} - }, runner); + runner + ); process.stdout.write = stdoutWrite; expect(calledDraw).to.be(true); }); }); - describe('on pending', function () { - it('should call draw', function () { + describe('on pending', function() { + it('should call draw', function() { calledDraw = false; runner = createMockRunner('pending', 'pending'); - NyanCat.call({ - draw: function () { - calledDraw = true; + NyanCat.call( + { + draw: function() { + calledDraw = true; + }, + generateColors: function() {} }, - generateColors: function () {} - }, runner); + runner + ); process.stdout.write = stdoutWrite; expect(calledDraw).to.be(true); }); }); - describe('on pass', function () { - it('should call draw', function () { + describe('on pass', function() { + it('should call draw', function() { calledDraw = false; var test = { duration: '', - slow: function () {} + slow: function() {} }; runner = createMockRunner('pass', 'pass', null, null, test); - NyanCat.call({ - draw: function () { - calledDraw = true; + NyanCat.call( + { + draw: function() { + calledDraw = true; + }, + generateColors: function() {} }, - generateColors: function () {} - }, runner); + runner + ); process.stdout.write = stdoutWrite; expect(calledDraw).to.be(true); }); }); - describe('on fail', function () { - it('should call draw', function () { + describe('on fail', function() { + it('should call draw', function() { calledDraw = false; var test = { err: '' }; runner = createMockRunner('fail', 'fail', null, null, test); - NyanCat.call({ - draw: function () { - calledDraw = true; + NyanCat.call( + { + draw: function() { + calledDraw = true; + }, + generateColors: function() {} }, - generateColors: function () {} - }, runner); + runner + ); process.stdout.write = stdoutWrite; expect(calledDraw).to.be(true); }); }); - describe('on end', function () { - it('should call epilogue', function () { + describe('on end', function() { + it('should call epilogue', function() { var calledEpilogue = false; runner = createMockRunner('end', 'end'); - NyanCat.call({ - draw: function () {}, - generateColors: function () {}, - epilogue: function () { - calledEpilogue = true; - } - }, runner); + NyanCat.call( + { + draw: function() {}, + generateColors: function() {}, + epilogue: function() { + calledEpilogue = true; + } + }, + runner + ); process.stdout.write = stdoutWrite; expect(calledEpilogue).to.be(true); }); - it('should write numberOfLines amount of new lines', function () { + it('should write numberOfLines amount of new lines', function() { var expectedNumberOfLines = 4; runner = createMockRunner('end', 'end'); - NyanCat.call({ - draw: function () {}, - generateColors: function () {}, - epilogue: function () {} - }, runner); + NyanCat.call( + { + draw: function() {}, + generateColors: function() {}, + epilogue: function() {} + }, + runner + ); - var arrayOfNewlines = stdout.filter(function (value) { return value === '\n'; }); + var arrayOfNewlines = stdout.filter(function(value) { + return value === '\n'; + }); process.stdout.write = stdoutWrite; expect(arrayOfNewlines).to.have.length(expectedNumberOfLines); }); - it('should call Base show', function () { + it('should call Base show', function() { var showCalled = false; var cachedShow = Base.cursor.show; - Base.cursor.show = function () { + Base.cursor.show = function() { showCalled = true; }; runner = createMockRunner('end', 'end'); - NyanCat.call({ - draw: function () {}, - generateColors: function () {}, - epilogue: function () {} - }, runner); + NyanCat.call( + { + draw: function() {}, + generateColors: function() {}, + epilogue: function() {} + }, + runner + ); process.stdout.write = stdoutWrite; expect(showCalled).to.be(true); @@ -137,34 +160,34 @@ describe('Nyan reporter', function () { }); }); - describe('draw', function () { + describe('draw', function() { var stdout; var stdoutWrite; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; }); - describe('if tick is false', function () { - it('should draw face with expected spaces, _ and ^', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); - nyanCat.stats = { passes: 2, pending: 1, failures: 0 }; + describe('if tick is false', function() { + it('should draw face with expected spaces, _ and ^', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); + nyanCat.stats = {passes: 2, pending: 1, failures: 0}; nyanCat.draw.call({ tick: false, - appendRainbow: function () {}, - rainbowify: function () {}, - drawScoreboard: function () {}, - drawRainbow: function () {}, + appendRainbow: function() {}, + rainbowify: function() {}, + drawScoreboard: function() {}, + drawRainbow: function() {}, drawNyanCat: NyanCat.prototype.drawNyanCat, scoreboardWidth: 0, trajectories: [[]], - face: function () {}, - cursorUp: function () {} + face: function() {}, + cursorUp: function() {} }); process.stdout.write = stdoutWrite; @@ -185,22 +208,22 @@ describe('Nyan reporter', function () { expect(stdout).to.eql(expectedArray); }); }); - describe('if tick is true', function () { - it('should draw face with expected spaces, _ and ~', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); - nyanCat.stats = { passes: 2, pending: 1, failures: 0 }; + describe('if tick is true', function() { + it('should draw face with expected spaces, _ and ~', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); + nyanCat.stats = {passes: 2, pending: 1, failures: 0}; nyanCat.draw.call({ tick: true, - appendRainbow: function () {}, - rainbowify: function () {}, - drawScoreboard: function () {}, - drawRainbow: function () {}, + appendRainbow: function() {}, + rainbowify: function() {}, + drawScoreboard: function() {}, + drawRainbow: function() {}, drawNyanCat: NyanCat.prototype.drawNyanCat, scoreboardWidth: 0, trajectories: [[]], - face: function () {}, - cursorUp: function () {} + face: function() {}, + cursorUp: function() {} }); process.stdout.write = stdoutWrite; @@ -223,117 +246,115 @@ describe('Nyan reporter', function () { }); }); - describe('cursorDown', function () { + describe('cursorDown', function() { var stdout; var stdoutWrite; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; }); - it('should write cursor down interaction with expected number', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + it('should write cursor down interaction with expected number', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); var expectedNumber = 25; nyanCat.cursorDown(expectedNumber); process.stdout.write = stdoutWrite; - var expectedArray = [ - '\u001b[' + expectedNumber + 'B' - ]; + var expectedArray = ['\u001b[' + expectedNumber + 'B']; expect(stdout).to.eql(expectedArray); }); }); - describe('cursorUp', function () { + describe('cursorUp', function() { var stdout; var stdoutWrite; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; }); - it('should write cursor up interaction with expected number', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + it('should write cursor up interaction with expected number', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); var expectedNumber = 25; nyanCat.cursorUp(expectedNumber); process.stdout.write = stdoutWrite; - var expectedArray = [ - '\u001b[' + expectedNumber + 'A' - ]; + var expectedArray = ['\u001b[' + expectedNumber + 'A']; expect(stdout).to.eql(expectedArray); }); }); - describe('rainbowify', function () { - describe('useColors is false', function () { + describe('rainbowify', function() { + describe('useColors is false', function() { var useColors; - beforeEach(function () { + beforeEach(function() { useColors = Base.useColors; Base.useColors = false; }); - afterEach(function () { + afterEach(function() { Base.useColors = useColors; }); - it('should return argument string', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + it('should return argument string', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); var expectedString = 'hello'; var outputString = nyanCat.rainbowify(expectedString); expect(outputString).to.equal(expectedString); }); }); - describe('useColors is true', function () { + describe('useColors is true', function() { var useColors; - beforeEach(function () { + beforeEach(function() { useColors = Base.useColors; Base.useColors = true; }); - afterEach(function () { + afterEach(function() { Base.useColors = useColors; }); - it('should return rainbowified string from the given string and predefined codes', function () { + it('should return rainbowified string from the given string and predefined codes', function() { var startCode = '\u001b[38;5;'; var endCode = '\u001b[0m'; - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); var expectedString = 'hello'; var colorCode = 'somecode'; - var expectedRainbowifyString = startCode + colorCode + 'm' + expectedString + endCode; + var expectedRainbowifyString = + startCode + colorCode + 'm' + expectedString + endCode; var outputString = nyanCat.rainbowify.call( { rainbowColors: [colorCode], colorIndex: 0 }, - expectedString); + expectedString + ); expect(outputString).to.equal(expectedRainbowifyString); }); }); }); - describe('appendRainbow', function () { - describe('if tick is true', function () { - it('should set an _ segment', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + describe('appendRainbow', function() { + describe('if tick is true', function() { + it('should set an _ segment', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); var expectedSegment; var inputArray = []; var trajectories = [inputArray, inputArray, inputArray, inputArray]; nyanCat.appendRainbow.call({ tick: true, - rainbowify: function (segment) { + rainbowify: function(segment) { expectedSegment = segment; }, numberOfLines: 4, @@ -343,17 +364,24 @@ describe('Nyan reporter', function () { expect(expectedSegment).to.equal('_'); }); - it('should shift each trajectory item, if its length is greater of equal to its max width', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + it('should shift each trajectory item, if its length is greater of equal to its max width', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); var rainbowifyResult = 'rainbowify'; var inputArray = ['itemToShify']; var trajectories = [inputArray, inputArray, inputArray, inputArray]; var expectedArray = [rainbowifyResult]; - var expectedTrajectories = [expectedArray, expectedArray, expectedArray, expectedArray]; + var expectedTrajectories = [ + expectedArray, + expectedArray, + expectedArray, + expectedArray + ]; nyanCat.appendRainbow.call({ tick: true, - rainbowify: function () { return rainbowifyResult; }, + rainbowify: function() { + return rainbowifyResult; + }, numberOfLines: 4, trajectoryWidthMax: 0, trajectories: trajectories @@ -362,15 +390,15 @@ describe('Nyan reporter', function () { expect(trajectories).to.eql(expectedTrajectories); }); }); - describe('if tick is false', function () { - it('should set an - segment', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + describe('if tick is false', function() { + it('should set an - segment', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); var expectedSegment; var inputArray = []; var trajectories = [inputArray, inputArray, inputArray, inputArray]; nyanCat.appendRainbow.call({ tick: false, - rainbowify: function (segment) { + rainbowify: function(segment) { expectedSegment = segment; }, numberOfLines: 4, @@ -383,25 +411,25 @@ describe('Nyan reporter', function () { }); }); - describe('drawScoreboard', function () { - it('should write scoreboard with color set with each stat', function () { + describe('drawScoreboard', function() { + it('should write scoreboard with color set with each stat', function() { var cachedColor = Base.color; - Base.color = function (type, n) { + Base.color = function(type, n) { return type + n; }; var stdout = []; var stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; var passes = 2; var pending = 1; var failures = 1; - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); nyanCat.drawScoreboard.call({ - cursorUp: function () {}, - stats: { passes: passes, pending: pending, failures: failures }, + cursorUp: function() {}, + stats: {passes: passes, pending: pending, failures: failures}, numberOfLines: 4 }); var expectedArray = [ @@ -420,21 +448,21 @@ describe('Nyan reporter', function () { process.stdout.write = stdoutWrite; Base.color = cachedColor; }); - it('should call cursorUp with given numberOfLines', function () { + it('should call cursorUp with given numberOfLines', function() { var stdout = []; var stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; var expectedCursorArgument = null; var expectedNumberOfLines = 1000; - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); nyanCat.drawScoreboard.call({ - cursorUp: function (lines) { + cursorUp: function(lines) { expectedCursorArgument = lines; }, - stats: { passes: 0, pending: 0, failures: 0 }, + stats: {passes: 0, pending: 0, failures: 0}, numberOfLines: expectedNumberOfLines }); @@ -443,11 +471,11 @@ describe('Nyan reporter', function () { }); }); - describe('drawRainbow', function () { - it('should write width, contents and newline for each trajectory', function () { + describe('drawRainbow', function() { + it('should write width, contents and newline for each trajectory', function() { var stdout = []; var stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; var expectedWidth = 444; @@ -455,9 +483,9 @@ describe('Nyan reporter', function () { var expectedContents = 'input'; var inputArray = [expectedContents]; var trajectories = [inputArray]; - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); nyanCat.drawRainbow.call({ - cursorUp: function () {}, + cursorUp: function() {}, trajectories: trajectories, scoreboardWidth: expectedWidth, numberOfLines: 1 @@ -472,18 +500,18 @@ describe('Nyan reporter', function () { expect(stdout).to.eql(expectedArray); }); - it('should call cursorUp with given numberOfLines', function () { + it('should call cursorUp with given numberOfLines', function() { var stdout = []; var stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; var expectedCursorArgument = null; var expectedNumberOfLines = 1000; - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); nyanCat.drawRainbow.call({ - cursorUp: function (lines) { + cursorUp: function(lines) { expectedCursorArgument = lines; }, trajectories: [['input']], @@ -495,28 +523,28 @@ describe('Nyan reporter', function () { process.stdout.write = stdoutWrite; }); }); - describe('face', function () { - it('expected face:(x .x) when "failures" at least one', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); - nyanCat.stats = { passes: 2, pending: 1, failures: 1 }; + describe('face', function() { + it('expected face:(x .x) when "failures" at least one', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); + nyanCat.stats = {passes: 2, pending: 1, failures: 1}; expect(nyanCat.face()).to.equal('( x .x)'); }); - it('expected face:(x .x) when "pending" at least one and no failing', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); - nyanCat.stats = { passes: 2, pending: 1, failures: 0 }; + it('expected face:(x .x) when "pending" at least one and no failing', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); + nyanCat.stats = {passes: 2, pending: 1, failures: 0}; expect(nyanCat.face()).to.equal('( o .o)'); }); - it('expected face:(^ .^) when "passing" only', function () { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); - nyanCat.stats = { passes: 1, pending: 0, failures: 0 }; + it('expected face:(^ .^) when "passing" only', function() { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); + nyanCat.stats = {passes: 1, pending: 0, failures: 0}; expect(nyanCat.face()).to.equal('( ^ .^)'); }); - it('expected face:(- .-) when otherwise', function (done) { - var nyanCat = new NyanCat({on: function () {}, once: function () {}}); - nyanCat.stats = { passes: 0, pending: 0, failures: 0 }; + it('expected face:(- .-) when otherwise', function(done) { + var nyanCat = new NyanCat({on: function() {}, once: function() {}}); + nyanCat.stats = {passes: 0, pending: 0, failures: 0}; expect(nyanCat.face()).to.equal('( - .-)'); done(); }); diff --git a/test/reporters/progress.spec.js b/test/reporters/progress.spec.js index 47818f841d..1cca6e58d2 100644 --- a/test/reporters/progress.spec.js +++ b/test/reporters/progress.spec.js @@ -6,24 +6,24 @@ var Base = reporters.Base; var createMockRunner = require('./helpers').createMockRunner; -describe('Progress reporter', function () { +describe('Progress reporter', function() { var stdout; var stdoutWrite; var runner; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; }); - describe('on start', function () { - it('should call cursor hide', function () { + describe('on start', function() { + it('should call cursor hide', function() { var cachedCursor = Base.cursor; var calledCursorHide = false; - Base.cursor.hide = function () { + Base.cursor.hide = function() { calledCursorHide = true; }; runner = createMockRunner('start', 'start'); @@ -36,13 +36,13 @@ describe('Progress reporter', function () { }); }); - describe('on test end', function () { - describe('if line has not changed', function () { - it('should return and not write anything', function () { + describe('on test end', function() { + describe('if line has not changed', function() { + it('should return and not write anything', function() { var cachedCursor = Base.cursor; var useColors = Base.useColors; Base.useColors = false; - Base.cursor.CR = function () {}; + Base.cursor.CR = function() {}; var windowWidth = Base.window.width; Base.window.width = -3; @@ -61,13 +61,13 @@ describe('Progress reporter', function () { Base.window.width = windowWidth; }); }); - describe('if line has changed', function () { - it('should write expected progress of open and close options', function () { + describe('if line has changed', function() { + it('should write expected progress of open and close options', function() { var calledCursorCR = false; var cachedCursor = Base.cursor; var useColors = Base.useColors; Base.useColors = false; - Base.cursor.CR = function () { + Base.cursor.CR = function() { calledCursorCR = true; }; var windowWidth = Base.window.width; @@ -108,20 +108,23 @@ describe('Progress reporter', function () { }); }); - describe('on end', function () { - it('should call cursor show and epilogue', function () { + describe('on end', function() { + it('should call cursor show and epilogue', function() { var cachedCursor = Base.cursor; var calledCursorShow = false; - Base.cursor.show = function () { + Base.cursor.show = function() { calledCursorShow = true; }; runner = createMockRunner('end', 'end'); var calledEpilogue = false; - Progress.call({ - epilogue: function () { - calledEpilogue = true; - } - }, runner); + Progress.call( + { + epilogue: function() { + calledEpilogue = true; + } + }, + runner + ); process.stdout.write = stdoutWrite; expect(calledEpilogue).to.be(true); diff --git a/test/reporters/spec.spec.js b/test/reporters/spec.spec.js index cb662e4530..da929fb16a 100644 --- a/test/reporters/spec.spec.js +++ b/test/reporters/spec.spec.js @@ -6,99 +6,106 @@ var Base = reporters.Base; var createMockRunner = require('./helpers').createMockRunner; -describe('Spec reporter', function () { +describe('Spec reporter', function() { var stdout; var stdoutWrite; var runner; var useColors; var expectedTitle = 'expectedTitle'; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; useColors = Base.useColors; Base.useColors = false; }); - afterEach(function () { + afterEach(function() { Base.useColors = useColors; }); - describe('on suite', function () { - it('should return title', function () { + describe('on suite', function() { + it('should return title', function() { var suite = { title: expectedTitle }; runner = createMockRunner('suite', 'suite', null, null, suite); - Spec.call({epilogue: function () {}}, runner); + Spec.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - expectedTitle + '\n' - ]; + var expectedArray = [expectedTitle + '\n']; expect(stdout).to.eql(expectedArray); }); }); - describe('on pending', function () { - it('should return title', function () { + describe('on pending', function() { + it('should return title', function() { var suite = { title: expectedTitle }; runner = createMockRunner('pending test', 'pending', null, null, suite); - Spec.call({epilogue: function () {}}, runner); + Spec.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - ' - ' + expectedTitle + '\n' - ]; + var expectedArray = [' - ' + expectedTitle + '\n']; expect(stdout).to.eql(expectedArray); }); }); - describe('on pass', function () { - describe('if test speed is slow', function () { - it('should return expected tick, title and duration', function () { + describe('on pass', function() { + describe('if test speed is slow', function() { + it('should return expected tick, title and duration', function() { var expectedDuration = 2; var test = { title: expectedTitle, duration: expectedDuration, - slow: function () { return 1; } + slow: function() { + return 1; + } }; runner = createMockRunner('pass', 'pass', null, null, test); - Spec.call({epilogue: function () {}}, runner); + Spec.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedString = ' ' + Base.symbols.ok + ' ' + expectedTitle + ' (' + expectedDuration + 'ms)' + '\n'; + var expectedString = + ' ' + + Base.symbols.ok + + ' ' + + expectedTitle + + ' (' + + expectedDuration + + 'ms)' + + '\n'; expect(stdout[0]).to.equal(expectedString); }); }); - describe('if test speed is fast', function () { - it('should return expected tick, title and without a duration', function () { + describe('if test speed is fast', function() { + it('should return expected tick, title and without a duration', function() { var expectedDuration = 1; var test = { title: expectedTitle, duration: expectedDuration, - slow: function () { return 2; } + slow: function() { + return 2; + } }; runner = createMockRunner('pass', 'pass', null, null, test); - Spec.call({epilogue: function () {}}, runner); + Spec.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedString = ' ' + Base.symbols.ok + ' ' + expectedTitle + '\n'; + var expectedString = + ' ' + Base.symbols.ok + ' ' + expectedTitle + '\n'; expect(stdout[0]).to.equal(expectedString); }); }); }); - describe('on fail', function () { - it('should return title and function count', function () { + describe('on fail', function() { + it('should return title and function count', function() { var functionCount = 1; var test = { title: expectedTitle }; runner = createMockRunner('fail', 'fail', null, null, test); - Spec.call({epilogue: function () {}}, runner); + Spec.call({epilogue: function() {}}, runner); process.stdout.write = stdoutWrite; - var expectedArray = [ - ' ' + functionCount + ') ' + expectedTitle + '\n' - ]; + var expectedArray = [' ' + functionCount + ') ' + expectedTitle + '\n']; expect(stdout).to.eql(expectedArray); }); }); diff --git a/test/reporters/tap.spec.js b/test/reporters/tap.spec.js index 9b7eac9491..27381ea20a 100644 --- a/test/reporters/tap.spec.js +++ b/test/reporters/tap.spec.js @@ -5,7 +5,7 @@ var TAP = reporters.TAP; var createMockRunner = require('./helpers').createMockRunner; -describe('TAP reporter', function () { +describe('TAP reporter', function() { var stdout; var stdoutWrite; var runner; @@ -13,36 +13,34 @@ describe('TAP reporter', function () { var countAfterTestEnd = 2; var test; - beforeEach(function () { + beforeEach(function() { stdout = []; stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; test = { - fullTitle: function () { + fullTitle: function() { return expectedTitle; }, - slow: function () {} + slow: function() {} }; }); - describe('on start', function () { - it('should hand runners suite into grepTotal and log the total', function () { + describe('on start', function() { + it('should hand runners suite into grepTotal and log the total', function() { var expectedSuite = 'some suite'; var expectedTotal = 10; var expectedString; runner = createMockRunner('start', 'start'); runner.suite = expectedSuite; - runner.grepTotal = function (string) { + runner.grepTotal = function(string) { expectedString = string; return expectedTotal; }; TAP.call({}, runner); - var expectedArray = [ - '1..' + expectedTotal + '\n' - ]; + var expectedArray = ['1..' + expectedTotal + '\n']; process.stdout.write = stdoutWrite; expect(stdout).to.eql(expectedArray); @@ -50,51 +48,59 @@ describe('TAP reporter', function () { }); }); - describe('on pending', function () { - it('should write expected message including count and title', function () { - runner = createMockRunner('start test', 'test end', 'pending', null, test); + describe('on pending', function() { + it('should write expected message including count and title', function() { + runner = createMockRunner( + 'start test', + 'test end', + 'pending', + null, + test + ); runner.suite = ''; - runner.grepTotal = function () { }; + runner.grepTotal = function() {}; TAP.call({}, runner); process.stdout.write = stdoutWrite; - var expectedMessage = 'ok ' + countAfterTestEnd + ' ' + expectedTitle + ' # SKIP -\n'; + var expectedMessage = + 'ok ' + countAfterTestEnd + ' ' + expectedTitle + ' # SKIP -\n'; expect(stdout[0]).to.eql(expectedMessage); }); }); - describe('on pass', function () { - it('should write expected message including count and title', function () { + describe('on pass', function() { + it('should write expected message including count and title', function() { runner = createMockRunner('start test', 'test end', 'pass', null, test); runner.suite = ''; - runner.grepTotal = function () { }; + runner.grepTotal = function() {}; TAP.call({}, runner); process.stdout.write = stdoutWrite; - var expectedMessage = 'ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n'; + var expectedMessage = + 'ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n'; expect(stdout[0]).to.eql(expectedMessage); }); }); - describe('on fail', function () { - describe('if there is an error message', function () { - it('should write expected message and error message', function () { + describe('on fail', function() { + describe('if there is an error message', function() { + it('should write expected message and error message', function() { var expectedTitle = 'some title'; var countAfterTestEnd = 2; var expectedErrorMessage = 'some error'; var test = { - fullTitle: function () { + fullTitle: function() { return expectedTitle; }, - slow: function () {} + slow: function() {} }; var error = { message: expectedErrorMessage }; - runner.on = function (event, callback) { + runner.on = function(event, callback) { if (event === 'test end') { callback(); } @@ -103,7 +109,7 @@ describe('TAP reporter', function () { } }; runner.suite = ''; - runner.grepTotal = function () { }; + runner.grepTotal = function() {}; TAP.call({}, runner); process.stdout.write = stdoutWrite; @@ -115,15 +121,22 @@ describe('TAP reporter', function () { expect(stdout).to.eql(expectedArray); }); }); - describe('if there is an error stack', function () { - it('should write expected message and stack', function () { + describe('if there is an error stack', function() { + it('should write expected message and stack', function() { var expectedStack = 'some stack'; var error = { stack: expectedStack }; - runner = createMockRunner('test end fail', 'test end', 'fail', null, test, error); + runner = createMockRunner( + 'test end fail', + 'test end', + 'fail', + null, + test, + error + ); runner.suite = ''; - runner.grepTotal = function () { }; + runner.grepTotal = function() {}; TAP.call({}, runner); process.stdout.write = stdoutWrite; @@ -135,23 +148,23 @@ describe('TAP reporter', function () { expect(stdout).to.eql(expectedArray); }); }); - describe('if there is an error stack and error message', function () { - it('should write expected message and stack', function () { + describe('if there is an error stack and error message', function() { + it('should write expected message and stack', function() { var expectedTitle = 'some title'; var countAfterTestEnd = 2; var expectedStack = 'some stack'; var expectedErrorMessage = 'some error'; var test = { - fullTitle: function () { + fullTitle: function() { return expectedTitle; }, - slow: function () {} + slow: function() {} }; var error = { stack: expectedStack, message: expectedErrorMessage }; - runner.on = function (event, callback) { + runner.on = function(event, callback) { if (event === 'test end') { callback(); } @@ -160,7 +173,7 @@ describe('TAP reporter', function () { } }; runner.suite = ''; - runner.grepTotal = function () { }; + runner.grepTotal = function() {}; TAP.call({}, runner); process.stdout.write = stdoutWrite; @@ -173,10 +186,10 @@ describe('TAP reporter', function () { expect(stdout).to.eql(expectedArray); }); }); - describe('if there is no error stack or error message', function () { - it('should write expected message only', function () { + describe('if there is no error stack or error message', function() { + it('should write expected message only', function() { var error = {}; - runner.on = runner.once = function (event, callback) { + runner.on = runner.once = function(event, callback) { if (event === 'test end') { callback(); } @@ -185,7 +198,7 @@ describe('TAP reporter', function () { } }; runner.suite = ''; - runner.grepTotal = function () { }; + runner.grepTotal = function() {}; TAP.call({}, runner); process.stdout.write = stdoutWrite; @@ -198,13 +211,13 @@ describe('TAP reporter', function () { }); }); - describe('on end', function () { - it('should write total tests, passes and failures', function () { + describe('on end', function() { + it('should write total tests, passes and failures', function() { var numberOfPasses = 1; var numberOfFails = 1; runner = createMockRunner('fail end pass', 'fail', 'end', 'pass', test); runner.suite = ''; - runner.grepTotal = function () { }; + runner.grepTotal = function() {}; TAP.call({}, runner); process.stdout.write = stdoutWrite; diff --git a/test/reporters/xunit.spec.js b/test/reporters/xunit.spec.js index c0c066d60b..18a43cb882 100644 --- a/test/reporters/xunit.spec.js +++ b/test/reporters/xunit.spec.js @@ -7,7 +7,7 @@ var assert = require('assert'); var reporters = require('../../').reporters; var XUnit = reporters.XUnit; -describe('XUnit reporter', function () { +describe('XUnit reporter', function() { var stdout; var stdoutWrite; var runner; @@ -21,37 +21,45 @@ describe('XUnit reporter', function () { var expectedStack = 'some-stack'; var expectedWrite = null; - beforeEach(function () { + beforeEach(function() { stdout = []; - runner = {on: function () {}, once: function () {}}; + runner = {on: function() {}, once: function() {}}; }); - describe('if reporter options output is given', function () { + describe('if reporter options output is given', function() { var expectedOutput = 'some-output'; var options = { reporterOptions: { output: expectedOutput } }; - describe('but it cant create a write stream', function () { - it('should throw expected error', function () { + describe('but it cant create a write stream', function() { + it('should throw expected error', function() { var fsCreateWriteStream = fs.createWriteStream; fs.createWriteStream = false; var boundXUnit = XUnit.bind({}, runner, options); - expect(boundXUnit).to.throwException('file output not supported in browser'); + expect(boundXUnit).to.throwException( + 'file output not supported in browser' + ); fs.createWriteStream = fsCreateWriteStream; }); }); - describe('and it can create a write stream', function () { - it('should locate the output dir, create it, then assign as fileStream', function () { + describe('and it can create a write stream', function() { + it('should locate the output dir, create it, then assign as fileStream', function() { var expectedDirectory; var mkdirpSync = mkdirp.sync; var pathDirname = path.dirname; var fsCreateWriteStream = fs.createWriteStream; - mkdirp.sync = function (directory) { expectedDirectory = directory; }; - path.dirname = function (location) { return location; }; - fs.createWriteStream = function (streamDetails) { return streamDetails; }; + mkdirp.sync = function(directory) { + expectedDirectory = directory; + }; + path.dirname = function(location) { + return location; + }; + fs.createWriteStream = function(streamDetails) { + return streamDetails; + }; var contextVariables = { fileStream: null @@ -68,21 +76,21 @@ describe('XUnit reporter', function () { }); }); - describe('on \'pending\', \'pass\' and \'fail\' events', function () { - it('should add test to tests called on \'end\' event', function () { + describe("on 'pending', 'pass' and 'fail' events", function() { + it("should add test to tests called on 'end' event", function() { var pendingTest = { name: 'pending', - slow: function () {} + slow: function() {} }; var failTest = { name: 'fail', - slow: function () {} + slow: function() {} }; var passTest = { name: 'pass', - slow: function () {} + slow: function() {} }; - runner.on = runner.once = function (event, callback) { + runner.on = runner.once = function(event, callback) { if (event === 'pending') { callback(pendingTest); } @@ -98,112 +106,94 @@ describe('XUnit reporter', function () { }; var calledTests = []; - XUnit.call({ - write: function () {}, - test: function (test) { - calledTests.push(test); - } - }, runner); + XUnit.call( + { + write: function() {}, + test: function(test) { + calledTests.push(test); + } + }, + runner + ); - var expectedCalledTests = [ - pendingTest, - passTest, - failTest - ]; + var expectedCalledTests = [pendingTest, passTest, failTest]; expect(calledTests).to.eql(expectedCalledTests); }); }); - describe('done', function () { - describe('if fileStream is truthly', function () { - it('should run callback with failure inside streams end', function () { - var xunit = new XUnit({on: function () {}, once: function () {}}); - var callback = function (failures) { + describe('done', function() { + describe('if fileStream is truthly', function() { + it('should run callback with failure inside streams end', function() { + var xunit = new XUnit({on: function() {}, once: function() {}}); + var callback = function(failures) { callbackArgument = failures; }; var calledEnd = false; var fileStream = { - end: function (callback) { + end: function(callback) { calledEnd = true; callback(); } }; - xunit.done.call( - { fileStream: fileStream }, - expectedFailure, - callback - ); + xunit.done.call({fileStream: fileStream}, expectedFailure, callback); expect(calledEnd).to.be(true); expect(callbackArgument).to.equal(expectedFailure); }); }); - describe('if fileStream is falsy', function () { - it('should run callback with failure', function () { - var xunit = new XUnit({on: function () {}, once: function () {}}); - var callback = function (failures) { + describe('if fileStream is falsy', function() { + it('should run callback with failure', function() { + var xunit = new XUnit({on: function() {}, once: function() {}}); + var callback = function(failures) { callbackArgument = failures; }; - xunit.done.call( - { fileStream: false }, - expectedFailure, - callback - ); + xunit.done.call({fileStream: false}, expectedFailure, callback); expect(callbackArgument).to.equal(expectedFailure); }); }); }); - describe('write', function () { - describe('if fileStream is truthly', function () { - it('should call fileStream write with line and new line', function () { - var xunit = new XUnit({on: function () {}, once: function () {}}); + describe('write', function() { + describe('if fileStream is truthly', function() { + it('should call fileStream write with line and new line', function() { + var xunit = new XUnit({on: function() {}, once: function() {}}); var fileStream = { - write: function (write) { + write: function(write) { expectedWrite = write; } }; - xunit.write.call( - { fileStream: fileStream }, - expectedLine - ); + xunit.write.call({fileStream: fileStream}, expectedLine); expect(expectedWrite).to.equal(expectedLine + '\n'); }); }); - describe('if fileStream is falsy and stdout exists', function () { - it('should call write with line and new line', function () { + describe('if fileStream is falsy and stdout exists', function() { + it('should call write with line and new line', function() { stdoutWrite = process.stdout.write; - process.stdout.write = function (string) { + process.stdout.write = function(string) { stdout.push(string); }; - var xunit = new XUnit({on: function () {}, once: function () {}}); - xunit.write.call( - { fileStream: false }, - expectedLine - ); + var xunit = new XUnit({on: function() {}, once: function() {}}); + xunit.write.call({fileStream: false}, expectedLine); process.stdout.write = stdoutWrite; expect(stdout[0]).to.equal(expectedLine + '\n'); }); }); - describe('if fileStream is falsy and stdout does not exist', function () { - it('should call write with line', function () { + describe('if fileStream is falsy and stdout does not exist', function() { + it('should call write with line', function() { stdoutWrite = process; process = false; // eslint-disable-line no-native-reassign, no-global-assign var cachedConsoleLog = console.log; - console.log = function (string) { + console.log = function(string) { stdout.push(string); }; - var xunit = new XUnit({on: function () {}, once: function () {}}); - xunit.write.call( - { fileStream: false }, - expectedLine - ); + var xunit = new XUnit({on: function() {}, once: function() {}}); + xunit.write.call({fileStream: false}, expectedLine); console.log = cachedConsoleLog; process = stdoutWrite; // eslint-disable-line no-native-reassign, no-global-assign @@ -212,15 +202,15 @@ describe('XUnit reporter', function () { }); }); - describe('test', function () { - describe('on test failure', function () { - it('should write expected tag with error details', function () { - var xunit = new XUnit({on: function () {}, once: function () {}}); + describe('test', function() { + describe('on test failure', function() { + it('should write expected tag with error details', function() { + var xunit = new XUnit({on: function() {}, once: function() {}}); var expectedTest = { state: 'failed', title: expectedTitle, parent: { - fullTitle: function () { + fullTitle: function() { return expectedClassName; } }, @@ -232,27 +222,38 @@ describe('XUnit reporter', function () { }; xunit.test.call( { - write: function (string) { + write: function(string) { expectedWrite = string; } }, expectedTest ); - var expectedTag = '' + expectedMessage + '\n' + expectedStack + ''; + var expectedTag = + '' + + expectedMessage + + '\n' + + expectedStack + + ''; expect(expectedWrite).to.equal(expectedTag); }); }); - describe('on test pending', function () { - it('should write expected tag', function () { - var xunit = new XUnit({on: function () {}, once: function () {}}); + describe('on test pending', function() { + it('should write expected tag', function() { + var xunit = new XUnit({on: function() {}, once: function() {}}); var expectedTest = { - isPending: function () { return true; }, + isPending: function() { + return true; + }, title: expectedTitle, parent: { - fullTitle: function () { + fullTitle: function() { return expectedClassName; } }, @@ -260,27 +261,34 @@ describe('XUnit reporter', function () { }; xunit.test.call( { - write: function (string) { + write: function(string) { expectedWrite = string; } }, expectedTest ); - var expectedTag = ''; + var expectedTag = + ''; expect(expectedWrite).to.equal(expectedTag); }); }); - describe('on test in any other state', function () { - it('should write expected tag', function () { - var xunit = new XUnit({on: function () {}, once: function () {}}); + describe('on test in any other state', function() { + it('should write expected tag', function() { + var xunit = new XUnit({on: function() {}, once: function() {}}); var expectedTest = { - isPending: function () { return false; }, + isPending: function() { + return false; + }, title: expectedTitle, parent: { - fullTitle: function () { + fullTitle: function() { return expectedClassName; } }, @@ -288,21 +296,26 @@ describe('XUnit reporter', function () { }; xunit.test.call( { - write: function (string) { + write: function(string) { expectedWrite = string; } }, expectedTest ); - var expectedTag = ''; + var expectedTag = + ''; expect(expectedWrite).to.equal(expectedTag); }); }); }); - describe('custom suite name', function () { + describe('custom suite name', function() { // capture the events that the reporter subscribes to var events; // the runner parameter of the reporter @@ -312,11 +325,11 @@ describe('XUnit reporter', function () { // the file stream into which the xunit reporter will write into var fileStream; - beforeEach(function () { + beforeEach(function() { events = {}; runner = { - on: function (eventName, eventHandler) { + on: function(eventName, eventHandler) { // capture the event handler events[eventName] = eventHandler; } @@ -325,14 +338,14 @@ describe('XUnit reporter', function () { lines = []; fileStream = { - write: function (line) { + write: function(line) { // capture the output lines lines.push(line); } }; }); - it('should use "Mocha Tests" as the suite name if no custom name is provided', function () { + it('should use "Mocha Tests" as the suite name if no custom name is provided', function() { // arrange var xunit = new XUnit(runner); xunit.fileStream = fileStream; @@ -341,10 +354,13 @@ describe('XUnit reporter', function () { events['end'](); // assert - assert(lines[0].indexOf('Mocha Tests') >= 0, 'it should contain the text "Mocha Tests"'); + assert( + lines[0].indexOf('Mocha Tests') >= 0, + 'it should contain the text "Mocha Tests"' + ); }); - it('should use the custom suite name as the suite name when provided in the reporter options', function () { + it('should use the custom suite name as the suite name when provided in the reporter options', function() { // arrange var options = { reporterOptions: { @@ -360,7 +376,10 @@ describe('XUnit reporter', function () { events['end'](); // assert - assert(lines[0].indexOf('2^31', function () { - it('should set disabled', function () { + describe('#timeout(ms) when ms>2^31', function() { + it('should set disabled', function() { var run = new Runnable(); run.timeout(1e10); expect(run.enableTimeouts()).to.equal(false); }); }); - describe('#enableTimeouts(enabled)', function () { - it('should set enabled', function () { + describe('#enableTimeouts(enabled)', function() { + it('should set enabled', function() { var run = new Runnable(); run.enableTimeouts(false); expect(run.enableTimeouts()).to.equal(false); }); }); - describe('#slow(ms)', function () { + describe('#slow(ms)', function() { var run; - beforeEach(function () { + beforeEach(function() { run = new Runnable(); }); - it('should set the slow threshold', function () { + it('should set the slow threshold', function() { run.slow(100); expect(run.slow()).to.equal(100); }); - it('should not set the slow threshold if the parameter is not passed', function () { + it('should not set the slow threshold if the parameter is not passed', function() { run.slow(); expect(run.slow()).to.equal(75); }); - it('should not set the slow threshold if the parameter is undefined', function () { + it('should not set the slow threshold if the parameter is undefined', function() { run.slow(undefined); expect(run.slow()).to.equal(75); }); }); - describe('.title', function () { - it('should be present', function () { + describe('.title', function() { + it('should be present', function() { expect(new Runnable('foo').title).to.equal('foo'); }); }); - describe('.titlePath()', function () { - it('returns the concatenation of the parent\'s title path and runnable\'s title', function () { + describe('.titlePath()', function() { + it("returns the concatenation of the parent's title path and runnable's title", function() { var runnable = new Runnable('bar'); runnable.parent = new Suite('foo'); expect(runnable.titlePath()).to.eql(['foo', 'bar']); }); }); - describe('when arity >= 1', function () { - it('should be .async', function () { - var run = new Runnable('foo', function (done) {}); + describe('when arity >= 1', function() { + it('should be .async', function() { + var run = new Runnable('foo', function(done) {}); expect(run.async).to.equal(1); expect(run.sync).to.be(false); }); }); - describe('when arity == 0', function () { - it('should be .sync', function () { - var run = new Runnable('foo', function () {}); + describe('when arity == 0', function() { + it('should be .sync', function() { + var run = new Runnable('foo', function() {}); expect(run.async).to.be.equal(0); expect(run.sync).to.be(true); }); }); - describe('#globals', function () { - it('should allow for whitelisting globals', function (done) { - var test = new Runnable('foo', function () {}); + describe('#globals', function() { + it('should allow for whitelisting globals', function(done) { + var test = new Runnable('foo', function() {}); expect(test.async).to.be.equal(0); expect(test.sync).to.be(true); test.globals(['foobar']); @@ -122,18 +119,18 @@ describe('Runnable(title, fn)', function () { }); }); - describe('#retries(n)', function () { - it('should set the number of retries', function () { + describe('#retries(n)', function() { + it('should set the number of retries', function() { var run = new Runnable(); run.retries(1); expect(run.retries()).to.equal(1); }); }); - describe('.run(fn)', function () { - describe('when .pending', function () { - it('should not invoke the callback', function (done) { - var test = new Runnable('foo', function () { + describe('.run(fn)', function() { + describe('when .pending', function() { + it('should not invoke the callback', function(done) { + var test = new Runnable('foo', function() { throw new Error('should not be called'); }); @@ -142,28 +139,23 @@ describe('Runnable(title, fn)', function () { }); }); - describe('when sync', function () { - describe('without error', function () { - it('should invoke the callback', function (done) { + describe('when sync', function() { + describe('without error', function() { + it('should invoke the callback', function(done) { var calls = 0; - var test = new Runnable('foo', function () { + var test = new Runnable('foo', function() { ++calls; }); - test.run(function (err) { + test.run(function(err) { if (err) { done(err); return; } try { - expect(calls) - .to - .equal(1); - expect(test.duration) - .to - .be - .a('number'); + expect(calls).to.equal(1); + expect(test.duration).to.be.a('number'); } catch (err) { done(err); return; @@ -173,15 +165,15 @@ describe('Runnable(title, fn)', function () { }); }); - describe('when an exception is thrown', function () { - it('should invoke the callback', function (done) { + describe('when an exception is thrown', function() { + it('should invoke the callback', function(done) { var calls = 0; - var test = new Runnable('foo', function () { + var test = new Runnable('foo', function() { ++calls; throw new Error('fail'); }); - test.run(function (err) { + test.run(function(err) { expect(calls).to.equal(1); expect(err.message).to.equal('fail'); done(); @@ -189,14 +181,14 @@ describe('Runnable(title, fn)', function () { }); }); - describe('when an exception is thrown and is allowed to remain uncaught', function () { - it('throws an error when it is allowed', function (done) { - var test = new Runnable('foo', function () { + describe('when an exception is thrown and is allowed to remain uncaught', function() { + it('throws an error when it is allowed', function(done) { + var test = new Runnable('foo', function() { throw new Error('fail'); }); test.allowUncaught = true; - function fail () { - test.run(function () {}); + function fail() { + test.run(function() {}); } expect(fail).to.throwError('fail'); done(); @@ -204,10 +196,10 @@ describe('Runnable(title, fn)', function () { }); }); - describe('when timeouts are disabled', function () { - it('should not error with timeout', function (done) { - var test = new Runnable('foo', function (done) { - setTimeout(function () { + describe('when timeouts are disabled', function() { + it('should not error with timeout', function(done) { + var test = new Runnable('foo', function(done) { + setTimeout(function() { setTimeout(done); }, 2); }); @@ -217,10 +209,10 @@ describe('Runnable(title, fn)', function () { }); }); - describe('when async', function () { - describe('without error', function () { - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function (done) { + describe('when async', function() { + describe('without error', function() { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function(done) { setTimeout(done); }); @@ -228,20 +220,20 @@ describe('Runnable(title, fn)', function () { }); }); - describe('when the callback is invoked several times', function () { - describe('without an error', function () { - it('should emit a single "error" event', function (done) { + describe('when the callback is invoked several times', function() { + describe('without an error', function() { + it('should emit a single "error" event', function(done) { var calls = 0; var errCalls = 0; - var test = new Runnable('foo', function (done) { + var test = new Runnable('foo', function(done) { process.nextTick(done); setTimeout(done); setTimeout(done); setTimeout(done); }); - test.on('error', function (err) { + test.on('error', function(err) { ++errCalls; expect(err.message).to.equal('done() called multiple times'); expect(calls).to.equal(1); @@ -249,18 +241,18 @@ describe('Runnable(title, fn)', function () { done(); }); - test.run(function () { + test.run(function() { ++calls; }); }); }); - describe('with an error', function () { - it('should emit a single "error" event', function (done) { + describe('with an error', function() { + it('should emit a single "error" event', function(done) { var calls = 0; var errCalls = 0; - var test = new Runnable('foo', function (done) { + var test = new Runnable('foo', function(done) { done(new Error('fail')); setTimeout(done); done(new Error('fail')); @@ -268,111 +260,116 @@ describe('Runnable(title, fn)', function () { setTimeout(done); }); - test.on('error', function (err) { + test.on('error', function(err) { ++errCalls; expect(err.message).to.equal( - "fail (and Mocha's done() called multiple times)"); + "fail (and Mocha's done() called multiple times)" + ); expect(calls).to.equal(1); expect(errCalls).to.equal(1); done(); }); - test.run(function () { + test.run(function() { ++calls; }); }); }); }); - describe('when an exception is thrown', function () { - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function (done) { + describe('when an exception is thrown', function() { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function(done) { throw new Error('fail'); }); - test.run(function (err) { + test.run(function(err) { expect(err.message).to.equal('fail'); done(); }); }); - it('should not throw its own exception if passed a non-object', function (done) { - var test = new Runnable('foo', function (done) { + it('should not throw its own exception if passed a non-object', function(done) { + var test = new Runnable('foo', function(done) { /* eslint no-throw-literal: off */ throw null; }); - test.run(function (err) { + test.run(function(err) { expect(err.message).to.equal(utils.undefinedError().message); done(); }); }); }); - describe('when an exception is thrown and is allowed to remain uncaught', function () { - it('throws an error when it is allowed', function (done) { - var test = new Runnable('foo', function (done) { + describe('when an exception is thrown and is allowed to remain uncaught', function() { + it('throws an error when it is allowed', function(done) { + var test = new Runnable('foo', function(done) { throw new Error('fail'); }); test.allowUncaught = true; - function fail () { - test.run(function () {}); + function fail() { + test.run(function() {}); } expect(fail).to.throwError('fail'); done(); }); }); - describe('when an error is passed', function () { - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function (done) { + describe('when an error is passed', function() { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function(done) { done(new Error('fail')); }); - test.run(function (err) { + test.run(function(err) { expect(err.message).to.equal('fail'); done(); }); }); }); - describe('when done() is invoked with a non-Error object', function () { - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function (done) { - done({ error: 'Test error' }); + describe('when done() is invoked with a non-Error object', function() { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function(done) { + done({error: 'Test error'}); }); - test.run(function (err) { - expect(err.message).to.equal('done() invoked with non-Error: {"error":"Test error"}'); + test.run(function(err) { + expect(err.message).to.equal( + 'done() invoked with non-Error: {"error":"Test error"}' + ); done(); }); }); }); - describe('when done() is invoked with a string', function () { - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function (done) { + describe('when done() is invoked with a string', function() { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function(done) { done('Test error'); }); - test.run(function (err) { - expect(err.message).to.equal('done() invoked with non-Error: Test error'); + test.run(function(err) { + expect(err.message).to.equal( + 'done() invoked with non-Error: Test error' + ); done(); }); }); }); - it('should allow updating the timeout', function (done) { + it('should allow updating the timeout', function(done) { var callCount = 0; - var increment = function () { + var increment = function() { callCount++; }; - var test = new Runnable('foo', function (done) { + var test = new Runnable('foo', function(done) { setTimeout(increment, 1); setTimeout(increment, 100); }); test.timeout(50); - test.run(function (err) { + test.run(function(err) { expect(err).to.be.ok(); expect(callCount).to.equal(1); done(); @@ -382,16 +379,16 @@ describe('Runnable(title, fn)', function () { it('should allow a timeout of 0'); }); - describe('when fn returns a promise', function () { - describe('when the promise is fulfilled with no value', function () { + describe('when fn returns a promise', function() { + describe('when the promise is fulfilled with no value', function() { var fulfilledPromise = { - then: function (fulfilled, rejected) { + then: function(fulfilled, rejected) { setTimeout(fulfilled); } }; - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function () { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function() { return fulfilledPromise; }); @@ -399,17 +396,17 @@ describe('Runnable(title, fn)', function () { }); }); - describe('when the promise is fulfilled with a value', function () { + describe('when the promise is fulfilled with a value', function() { var fulfilledPromise = { - then: function (fulfilled, rejected) { - setTimeout(function () { + then: function(fulfilled, rejected) { + setTimeout(function() { fulfilled({}); }); } }; - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function () { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function() { return fulfilledPromise; }); @@ -417,74 +414,76 @@ describe('Runnable(title, fn)', function () { }); }); - describe('when the promise is rejected', function () { + describe('when the promise is rejected', function() { var expectedErr = new Error('fail'); var rejectedPromise = { - then: function (fulfilled, rejected) { - setTimeout(function () { + then: function(fulfilled, rejected) { + setTimeout(function() { rejected(expectedErr); }); } }; - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function () { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function() { return rejectedPromise; }); - test.run(function (err) { + test.run(function(err) { expect(err).to.equal(expectedErr); done(); }); }); }); - describe('when the promise is rejected without a reason', function () { + describe('when the promise is rejected without a reason', function() { var expectedErr = new Error('Promise rejected with no or falsy reason'); var rejectedPromise = { - then: function (fulfilled, rejected) { - setTimeout(function () { + then: function(fulfilled, rejected) { + setTimeout(function() { rejected(); }); } }; - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function () { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function() { return rejectedPromise; }); - test.run(function (err) { + test.run(function(err) { expect(err.message).to.equal(expectedErr.message); done(); }); }); }); - describe('when the promise takes too long to settle', function () { + describe('when the promise takes too long to settle', function() { var foreverPendingPromise = { - then: function () { } + then: function() {} }; - it('should throw the timeout error', function (done) { - var test = new Runnable('foo', function () { + it('should throw the timeout error', function(done) { + var test = new Runnable('foo', function() { return foreverPendingPromise; }); test.file = '/some/path'; test.timeout(10); - test.run(function (err) { - expect(err.message).to.match(/Timeout of 10ms exceeded.*\(\/some\/path\)$/); + test.run(function(err) { + expect(err.message).to.match( + /Timeout of 10ms exceeded.*\(\/some\/path\)$/ + ); done(); }); }); }); }); - describe('when fn returns a non-promise', function () { - it('should invoke the callback', function (done) { - var test = new Runnable('foo', function () { - return { then: 'i ran my tests' }; + describe('when fn returns a non-promise', function() { + it('should invoke the callback', function(done) { + var test = new Runnable('foo', function() { + return {then: 'i ran my tests'}; }); test.run(done); @@ -492,34 +491,31 @@ describe('Runnable(title, fn)', function () { }); }); - describe('#isFailed()', function () { - it('should return `true` if test has not failed', function () { - var test = new Runnable('foo', function () { - }); + describe('#isFailed()', function() { + it('should return `true` if test has not failed', function() { + var test = new Runnable('foo', function() {}); // runner sets the state - test.run(function () { + test.run(function() { expect(test.isFailed()).not.to.be.ok(); }); }); - it('should return `true` if test has failed', function () { - var test = new Runnable('foo', function () { - }); + it('should return `true` if test has failed', function() { + var test = new Runnable('foo', function() {}); // runner sets the state test.state = 'failed'; - test.run(function () { + test.run(function() { expect(test.isFailed()).to.be.ok(); }); }); - it('should return `false` if test is pending', function () { - var test = new Runnable('foo', function () { - }); + it('should return `false` if test is pending', function() { + var test = new Runnable('foo', function() {}); // runner sets the state - test.isPending = function () { + test.isPending = function() { return true; }; - test.run(function () { + test.run(function() { expect(test.isFailed()).not.to.be.ok(); }); }); diff --git a/test/unit/runner.spec.js b/test/unit/runner.spec.js index 718a9b7cf6..b319351044 100644 --- a/test/unit/runner.spec.js +++ b/test/unit/runner.spec.js @@ -8,17 +8,17 @@ var Hook = mocha.Hook; var path = require('path'); var noop = mocha.utils.noop; -describe('Runner', function () { +describe('Runner', function() { var suite; var runner; - beforeEach(function () { + beforeEach(function() { suite = new Suite('Suite', 'root'); runner = new Runner(suite); }); - describe('.grep()', function () { - it('should update the runner.total with number of matched tests', function () { + describe('.grep()', function() { + it('should update the runner.total with number of matched tests', function() { suite.addTest(new Test('im a test about lions', noop)); suite.addTest(new Test('im another test about lions', noop)); suite.addTest(new Test('im a test about bears', noop)); @@ -27,7 +27,7 @@ describe('Runner', function () { expect(newRunner.total).to.equal(2); }); - it('should update the runner.total with number of matched tests when inverted', function () { + it('should update the runner.total with number of matched tests when inverted', function() { suite.addTest(new Test('im a test about lions', noop)); suite.addTest(new Test('im another test about lions', noop)); suite.addTest(new Test('im a test about bears', noop)); @@ -37,8 +37,8 @@ describe('Runner', function () { }); }); - describe('.grepTotal()', function () { - it('should return the total number of matched tests', function () { + describe('.grepTotal()', function() { + it('should return the total number of matched tests', function() { suite.addTest(new Test('im a test about lions', noop)); suite.addTest(new Test('im another test about lions', noop)); suite.addTest(new Test('im a test about bears', noop)); @@ -46,7 +46,7 @@ describe('Runner', function () { expect(runner.grepTotal(suite)).to.equal(2); }); - it('should return the total number of matched tests when inverted', function () { + it('should return the total number of matched tests when inverted', function() { suite.addTest(new Test('im a test about lions', noop)); suite.addTest(new Test('im another test about lions', noop)); suite.addTest(new Test('im a test about bears', noop)); @@ -55,8 +55,8 @@ describe('Runner', function () { }); }); - describe('.globalProps()', function () { - it('should include common non enumerable globals', function () { + describe('.globalProps()', function() { + it('should include common non enumerable globals', function() { var props = runner.globalProps(); expect(props).to.contain('setTimeout'); expect(props).to.contain('clearTimeout'); @@ -67,26 +67,26 @@ describe('Runner', function () { }); }); - describe('.globals()', function () { - it('should default to the known globals', function () { + describe('.globals()', function() { + it('should default to the known globals', function() { expect(runner.globals().length).to.be.above(16); }); - it('should white-list globals', function () { + it('should white-list globals', function() { runner.globals(['foo', 'bar']); expect(runner.globals()).to.contain('foo'); expect(runner.globals()).to.contain('bar'); }); }); - describe('.checkGlobals(test)', function () { - before(function () { + describe('.checkGlobals(test)', function() { + before(function() { if (!Object.create) { this.skip(); } }); - it('should allow variables that match a wildcard', function (done) { + it('should allow variables that match a wildcard', function(done) { runner.globals(['foo*', 'giz*']); global.foo = 'baz'; global.gizmo = 'quux'; @@ -96,11 +96,11 @@ describe('Runner', function () { done(); }); - it('should emit "fail" when a new global is introduced', function (done) { + it('should emit "fail" when a new global is introduced', function(done) { var test = new Test('im a test', noop); runner.checkGlobals(); global.foo = 'bar'; - runner.on('fail', function (_test, err) { + runner.on('fail', function(_test, err) { expect(_test).to.equal(test); expect(err.message).to.equal('global leak detected: foo'); delete global.foo; @@ -109,11 +109,11 @@ describe('Runner', function () { runner.checkGlobals(test); }); - it('should emit "fail" when a single new disallowed global is introduced after a single extra global is allowed', function (done) { + it('should emit "fail" when a single new disallowed global is introduced after a single extra global is allowed', function(done) { var doneCalled = false; runner.globals('good'); global.bad = 1; - runner.on('fail', function () { + runner.on('fail', function() { delete global.bad; done(); doneCalled = true; @@ -124,7 +124,7 @@ describe('Runner', function () { } }); - it('should not fail when a new common global is introduced', function () { + it('should not fail when a new common global is introduced', function() { if (process.browser) { this.skip(); return; @@ -138,7 +138,7 @@ describe('Runner', function () { var newRunner = new Runner(suite); // make the prop enumerable again. - global.XMLHttpRequest = function () {}; + global.XMLHttpRequest = function() {}; expect(global.propertyIsEnumerable('XMLHttpRequest')).to.be.ok(); // verify the test hasn't failed. @@ -149,12 +149,12 @@ describe('Runner', function () { delete global.XMLHttpRequest; }); - it('should pluralize the error message when several are introduced', function (done) { + it('should pluralize the error message when several are introduced', function(done) { var test = new Test('im a test', noop); runner.checkGlobals(); global.foo = 'bar'; global.bar = 'baz'; - runner.on('fail', function (_test, err) { + runner.on('fail', function(_test, err) { expect(_test).to.equal(test); expect(err.message).to.equal('global leaks detected: foo, bar'); delete global.foo; @@ -164,7 +164,7 @@ describe('Runner', function () { runner.checkGlobals(test); }); - it('should respect per test whitelisted globals', function () { + it('should respect per test whitelisted globals', function() { var test = new Test('im a test about lions', noop); test.globals(['foo']); @@ -180,7 +180,7 @@ describe('Runner', function () { delete global.foo; }); - it('should respect per test whitelisted globals but still detect other leaks', function (done) { + it('should respect per test whitelisted globals but still detect other leaks', function(done) { var test = new Test('im a test about lions', noop); test.globals(['foo']); @@ -188,7 +188,7 @@ describe('Runner', function () { global.foo = 'bar'; global.bar = 'baz'; - runner.on('fail', function (test, err) { + runner.on('fail', function(test, err) { expect(test.title).to.equal('im a test about lions'); expect(err.message).to.equal('global leak detected: bar'); delete global.foo; @@ -197,32 +197,32 @@ describe('Runner', function () { runner.checkGlobals(test); }); - it('should emit "fail" when a global beginning with d is introduced', function (done) { + it('should emit "fail" when a global beginning with d is introduced', function(done) { global.derp = 'bar'; - runner.on('fail', function () { + runner.on('fail', function() { delete global.derp; done(); }); - runner.checkGlobals(new Test('herp', function () {})); + runner.checkGlobals(new Test('herp', function() {})); }); }); - describe('.hook(name, fn)', function () { - it('should execute hooks after failed test if suite bail is true', function (done) { + describe('.hook(name, fn)', function() { + it('should execute hooks after failed test if suite bail is true', function(done) { runner.fail(new Test('failed test', noop)); suite.bail(true); - suite.afterEach(function () { - suite.afterAll(function () { + suite.afterEach(function() { + suite.afterAll(function() { done(); }); }); - runner.hook('afterEach', function () {}); - runner.hook('afterAll', function () {}); + runner.hook('afterEach', function() {}); + runner.hook('afterAll', function() {}); }); }); - describe('.fail(test, err)', function () { - it('should increment .failures', function () { + describe('.fail(test, err)', function() { + it('should increment .failures', function() { expect(runner.failures).to.equal(0); runner.fail(new Test('one', noop), {}); expect(runner.failures).to.equal(1); @@ -230,16 +230,16 @@ describe('Runner', function () { expect(runner.failures).to.equal(2); }); - it('should set test.state to "failed"', function () { + it('should set test.state to "failed"', function() { var test = new Test('some test', noop); runner.fail(test, 'some error'); expect(test.state).to.equal('failed'); }); - it('should emit "fail"', function (done) { + it('should emit "fail"', function(done) { var test = new Test('some other test', noop); var err = {}; - runner.on('fail', function (test, err) { + runner.on('fail', function(test, err) { expect(test).to.equal(test); expect(err).to.equal(err); done(); @@ -247,60 +247,63 @@ describe('Runner', function () { runner.fail(test, err); }); - it('should emit a helpful message when failed with a string', function (done) { + it('should emit a helpful message when failed with a string', function(done) { var test = new Test('helpful test', noop); var err = 'string'; - runner.on('fail', function (test, err) { - expect(err.message).to.equal('the string "string" was thrown, throw an Error :)'); + runner.on('fail', function(test, err) { + expect(err.message).to.equal( + 'the string "string" was thrown, throw an Error :)' + ); done(); }); runner.fail(test, err); }); - it('should emit a the error when failed with an Error instance', function (done) { + it('should emit a the error when failed with an Error instance', function(done) { var test = new Test('a test', noop); var err = new Error('an error message'); - runner.on('fail', function (test, err) { + runner.on('fail', function(test, err) { expect(err.message).to.equal('an error message'); done(); }); runner.fail(test, err); }); - it('should emit the error when failed with an Error-like object', function (done) { + it('should emit the error when failed with an Error-like object', function(done) { var test = new Test('a test', noop); - var err = { message: 'an error message' }; - runner.on('fail', function (test, err) { + var err = {message: 'an error message'}; + runner.on('fail', function(test, err) { expect(err.message).to.equal('an error message'); done(); }); runner.fail(test, err); }); - it('should emit a helpful message when failed with an Object', function (done) { + it('should emit a helpful message when failed with an Object', function(done) { var test = new Test('a test', noop); - var err = { x: 1 }; - runner.on('fail', function (test, err) { - expect(err.message).to.equal('the object {\n "x": 1\n} was thrown, throw an Error :)'); + var err = {x: 1}; + runner.on('fail', function(test, err) { + expect(err.message).to.equal( + 'the object {\n "x": 1\n} was thrown, throw an Error :)' + ); done(); }); runner.fail(test, err); }); - it('should emit a helpful message when failed with an Array', function (done) { + it('should emit a helpful message when failed with an Array', function(done) { var test = new Test('a test', noop); - var err = [ - 1, - 2 - ]; - runner.on('fail', function (test, err) { - expect(err.message).to.equal('the array [\n 1\n 2\n] was thrown, throw an Error :)'); + var err = [1, 2]; + runner.on('fail', function(test, err) { + expect(err.message).to.equal( + 'the array [\n 1\n 2\n] was thrown, throw an Error :)' + ); done(); }); runner.fail(test, err); }); - it('should recover if the error stack is not writable', function (done) { + it('should recover if the error stack is not writable', function(done) { if (!Object.create) { this.skip(); return; @@ -312,7 +315,7 @@ describe('Runner', function () { }); var test = new Test('a test', noop); - runner.on('fail', function (test, err) { + runner.on('fail', function(test, err) { expect(err.message).to.equal('not evil'); done(); }); @@ -321,8 +324,8 @@ describe('Runner', function () { }); }); - describe('.failHook(hook, err)', function () { - it('should increment .failures', function () { + describe('.failHook(hook, err)', function() { + it('should increment .failures', function() { expect(runner.failures).to.equal(0); runner.failHook(new Test('fail hook 1', noop), {}); expect(runner.failures).to.equal(1); @@ -330,9 +333,9 @@ describe('Runner', function () { expect(runner.failures).to.equal(2); }); - it('should augment hook title with current test title', function () { + it('should augment hook title with current test title', function() { var hook = new Hook('"before each" hook'); - hook.ctx = { currentTest: new Test('should behave', noop) }; + hook.ctx = {currentTest: new Test('should behave', noop)}; runner.failHook(hook, {}); expect(hook.title).to.equal('"before each" hook for "should behave"'); @@ -342,10 +345,10 @@ describe('Runner', function () { expect(hook.title).to.equal('"before each" hook for "should obey"'); }); - it('should emit "fail"', function (done) { + it('should emit "fail"', function(done) { var hook = new Hook(); var err = {}; - runner.on('fail', function (hook, err) { + runner.on('fail', function(hook, err) { expect(hook).to.equal(hook); expect(err).to.equal(err); done(); @@ -353,7 +356,7 @@ describe('Runner', function () { runner.failHook(hook, err); }); - it('should emit "end" if suite bail is true', function (done) { + it('should emit "end" if suite bail is true', function(done) { var hook = new Hook(); var err = {}; suite.bail(true); @@ -361,11 +364,11 @@ describe('Runner', function () { runner.failHook(hook, err); }); - it('should not emit "end" if suite bail is not true', function (done) { + it('should not emit "end" if suite bail is not true', function(done) { var hook = new Hook(); var err = {}; suite.bail(false); - runner.on('end', function () { + runner.on('end', function() { throw new Error('"end" was emit, but the bail is false'); }); runner.failHook(hook, err); @@ -373,14 +376,14 @@ describe('Runner', function () { }); }); - describe('allowUncaught', function () { - it('should allow unhandled errors to propagate through', function (done) { + describe('allowUncaught', function() { + it('should allow unhandled errors to propagate through', function(done) { var newRunner = new Runner(suite); newRunner.allowUncaught = true; - newRunner.test = new Test('failing test', function () { + newRunner.test = new Test('failing test', function() { throw new Error('allow unhandled errors'); }); - function fail () { + function fail() { newRunner.runTest(); } expect(fail).to.throwError('allow unhandled errors'); @@ -388,7 +391,7 @@ describe('Runner', function () { }); }); - describe('stackTrace', function () { + describe('stackTrace', function() { var stack = [ 'AssertionError: foo bar', 'at EventEmitter. (/usr/local/dev/test.js:16:12)', @@ -403,20 +406,20 @@ describe('Runner', function () { 'at processImmediate [as _immediateCallback] (timers.js:321:17)' ]; - describe('shortStackTrace', function () { - beforeEach(function () { + describe('shortStackTrace', function() { + beforeEach(function() { if (path.sep !== '/') { this.skip(); } }); - it('should prettify the stack-trace', function (done) { + it('should prettify the stack-trace', function(done) { var hook = new Hook(); var err = new Error(); // Fake stack-trace err.stack = stack.join('\n'); - runner.on('fail', function (hook, err) { + runner.on('fail', function(hook, err) { expect(err.stack).to.equal(stack.slice(0, 3).join('\n')); done(); }); @@ -424,14 +427,14 @@ describe('Runner', function () { }); }); - describe('longStackTrace', function () { - beforeEach(function () { + describe('longStackTrace', function() { + beforeEach(function() { if (path.sep !== '/') { this.skip(); } }); - it('should display the full stack-trace', function (done) { + it('should display the full stack-trace', function(done) { var hook = new Hook(); var err = new Error(); // Fake stack-trace @@ -439,7 +442,7 @@ describe('Runner', function () { // Add --stack-trace option runner.fullStackTrace = true; - runner.on('fail', function (hook, err) { + runner.on('fail', function(hook, err) { expect(err.stack).to.equal(stack.join('\n')); done(); }); diff --git a/test/unit/suite.spec.js b/test/unit/suite.spec.js index 3c3786efd1..251fb208ab 100644 --- a/test/unit/suite.spec.js +++ b/test/unit/suite.spec.js @@ -4,14 +4,14 @@ var mocha = require('../../lib/mocha'); var Suite = mocha.Suite; var Test = mocha.Test; -function supportsFunctionNames () { +function supportsFunctionNames() { // eslint-disable-next-line no-extra-parens - return (function foo () {}).name === 'foo'; + return function foo() {}.name === 'foo'; } -describe('Suite', function () { - describe('.clone()', function () { - beforeEach(function () { +describe('Suite', function() { + describe('.clone()', function() { + beforeEach(function() { this.suite = new Suite('To be cloned'); this.suite._timeout = 3043; this.suite._slow = 101; @@ -24,120 +24,120 @@ describe('Suite', function () { this.suite._afterAll.push(5); }); - it('should copy the title', function () { + it('should copy the title', function() { expect(this.suite.clone().title).to.equal('To be cloned'); }); - it('should copy the timeout value', function () { + it('should copy the timeout value', function() { expect(this.suite.clone().timeout()).to.equal(3043); }); - it('should copy the slow value', function () { + it('should copy the slow value', function() { expect(this.suite.clone().slow()).to.equal(101); }); - it('should copy the bail value', function () { + it('should copy the bail value', function() { expect(this.suite.clone().bail()).to.be(true); }); - it('should not copy the values from the suites array', function () { + it('should not copy the values from the suites array', function() { expect(this.suite.clone().suites).to.be.empty(); }); - it('should not copy the values from the tests array', function () { + it('should not copy the values from the tests array', function() { expect(this.suite.clone().tests).to.be.empty(); }); - it('should not copy the values from the _beforeEach array', function () { + it('should not copy the values from the _beforeEach array', function() { expect(this.suite.clone()._beforeEach).to.be.empty(); }); - it('should not copy the values from the _beforeAll array', function () { + it('should not copy the values from the _beforeAll array', function() { expect(this.suite.clone()._beforeAll).to.be.empty(); }); - it('should not copy the values from the _afterEach array', function () { + it('should not copy the values from the _afterEach array', function() { expect(this.suite.clone()._afterEach).to.be.empty(); }); - it('should not copy the values from the _afterAll array', function () { + it('should not copy the values from the _afterAll array', function() { expect(this.suite.clone()._afterAll).to.be.empty(); }); }); - describe('.timeout()', function () { - beforeEach(function () { + describe('.timeout()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('when no argument is passed', function () { - it('should return the timeout value', function () { + describe('when no argument is passed', function() { + it('should return the timeout value', function() { expect(this.suite.timeout()).to.equal(2000); }); }); - describe('when argument is passed', function () { - it('should return the Suite object', function () { + describe('when argument is passed', function() { + it('should return the Suite object', function() { var newSuite = this.suite.timeout(5000); expect(newSuite.timeout()).to.equal(5000); }); }); }); - describe('.slow()', function () { - beforeEach(function () { + describe('.slow()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('when given a string', function () { - it('should parse it', function () { + describe('when given a string', function() { + it('should parse it', function() { this.suite.slow('5 seconds'); expect(this.suite.slow()).to.equal(5000); }); }); - describe('when no argument is passed', function () { - it('should return the slow value', function () { + describe('when no argument is passed', function() { + it('should return the slow value', function() { expect(this.suite.slow()).to.equal(75); }); }); - describe('when argument is passed', function () { - it('should return the Suite object', function () { + describe('when argument is passed', function() { + it('should return the Suite object', function() { var newSuite = this.suite.slow(5000); expect(newSuite.slow()).to.equal(5000); }); }); }); - describe('.bail()', function () { - beforeEach(function () { + describe('.bail()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); this.suite._bail = true; }); - describe('when no argument is passed', function () { - it('should return the bail value', function () { + describe('when no argument is passed', function() { + it('should return the bail value', function() { expect(this.suite.bail()).to.be(true); }); }); - describe('when argument is passed', function () { - it('should return the Suite object', function () { + describe('when argument is passed', function() { + it('should return the Suite object', function() { var newSuite = this.suite.bail(false); expect(newSuite.bail()).to.be(false); }); }); }); - describe('.beforeAll()', function () { - beforeEach(function () { + describe('.beforeAll()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('wraps the passed in function in a Hook', function () { - it('adds it to _beforeAll', function () { - var fn = function () {}; + describe('wraps the passed in function in a Hook', function() { + it('adds it to _beforeAll', function() { + var fn = function() {}; this.suite.beforeAll(fn); expect(this.suite._beforeAll).to.have.length(1); @@ -146,30 +146,22 @@ describe('Suite', function () { expect(beforeAllItem.fn).to.equal(fn); }); - it('appends title to hook', function () { - var fn = function () { - }; + it('appends title to hook', function() { + var fn = function() {}; this.suite.beforeAll('test', fn); - expect(this.suite._beforeAll) - .to - .have - .length(1); + expect(this.suite._beforeAll).to.have.length(1); var beforeAllItem = this.suite._beforeAll[0]; - expect(beforeAllItem.title) - .to - .equal('"before all" hook: test'); - expect(beforeAllItem.fn) - .to - .equal(fn); + expect(beforeAllItem.title).to.equal('"before all" hook: test'); + expect(beforeAllItem.fn).to.equal(fn); }); - it('uses function name if available', function () { + it('uses function name if available', function() { if (!supportsFunctionNames()) { this.skip(); return; } - function namedFn () {} + function namedFn() {} this.suite.beforeAll(namedFn); var beforeAllItem = this.suite._beforeAll[0]; expect(beforeAllItem.title).to.equal('"before all" hook: namedFn'); @@ -178,14 +170,14 @@ describe('Suite', function () { }); }); - describe('.afterAll()', function () { - beforeEach(function () { + describe('.afterAll()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('wraps the passed in function in a Hook', function () { - it('adds it to _afterAll', function () { - var fn = function () {}; + describe('wraps the passed in function in a Hook', function() { + it('adds it to _afterAll', function() { + var fn = function() {}; this.suite.afterAll(fn); expect(this.suite._afterAll).to.have.length(1); @@ -193,30 +185,22 @@ describe('Suite', function () { expect(afterAllItem.title).to.match(/^"after all" hook/); expect(afterAllItem.fn).to.equal(fn); }); - it('appends title to hook', function () { - var fn = function () { - }; + it('appends title to hook', function() { + var fn = function() {}; this.suite.afterAll('test', fn); - expect(this.suite._afterAll) - .to - .have - .length(1); + expect(this.suite._afterAll).to.have.length(1); var beforeAllItem = this.suite._afterAll[0]; - expect(beforeAllItem.title) - .to - .equal('"after all" hook: test'); - expect(beforeAllItem.fn) - .to - .equal(fn); + expect(beforeAllItem.title).to.equal('"after all" hook: test'); + expect(beforeAllItem.fn).to.equal(fn); }); - it('uses function name if available', function () { + it('uses function name if available', function() { if (!supportsFunctionNames()) { this.skip(); return; } - function namedFn () {} + function namedFn() {} this.suite.afterAll(namedFn); var afterAllItem = this.suite._afterAll[0]; expect(afterAllItem.title).to.equal('"after all" hook: namedFn'); @@ -225,14 +209,14 @@ describe('Suite', function () { }); }); - describe('.beforeEach()', function () { - beforeEach(function () { + describe('.beforeEach()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('wraps the passed in function in a Hook', function () { - it('adds it to _beforeEach', function () { - var fn = function () {}; + describe('wraps the passed in function in a Hook', function() { + it('adds it to _beforeEach', function() { + var fn = function() {}; this.suite.beforeEach(fn); expect(this.suite._beforeEach).to.have.length(1); @@ -241,30 +225,22 @@ describe('Suite', function () { expect(beforeEachItem.fn).to.equal(fn); }); - it('appends title to hook', function () { - var fn = function () { - }; + it('appends title to hook', function() { + var fn = function() {}; this.suite.beforeEach('test', fn); - expect(this.suite._beforeEach) - .to - .have - .length(1); + expect(this.suite._beforeEach).to.have.length(1); var beforeAllItem = this.suite._beforeEach[0]; - expect(beforeAllItem.title) - .to - .equal('"before each" hook: test'); - expect(beforeAllItem.fn) - .to - .equal(fn); + expect(beforeAllItem.title).to.equal('"before each" hook: test'); + expect(beforeAllItem.fn).to.equal(fn); }); - it('uses function name if available', function () { + it('uses function name if available', function() { if (!supportsFunctionNames()) { this.skip(); return; } - function namedFn () {} + function namedFn() {} this.suite.beforeEach(namedFn); var beforeEachItem = this.suite._beforeEach[0]; expect(beforeEachItem.title).to.equal('"before each" hook: namedFn'); @@ -273,14 +249,14 @@ describe('Suite', function () { }); }); - describe('.afterEach()', function () { - beforeEach(function () { + describe('.afterEach()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('wraps the passed in function in a Hook', function () { - it('adds it to _afterEach', function () { - var fn = function () {}; + describe('wraps the passed in function in a Hook', function() { + it('adds it to _afterEach', function() { + var fn = function() {}; this.suite.afterEach(fn); expect(this.suite._afterEach).to.have.length(1); @@ -289,30 +265,22 @@ describe('Suite', function () { expect(afterEachItem.fn).to.equal(fn); }); - it('appends title to hook', function () { - var fn = function () { - }; + it('appends title to hook', function() { + var fn = function() {}; this.suite.afterEach('test', fn); - expect(this.suite._afterEach) - .to - .have - .length(1); + expect(this.suite._afterEach).to.have.length(1); var beforeAllItem = this.suite._afterEach[0]; - expect(beforeAllItem.title) - .to - .equal('"after each" hook: test'); - expect(beforeAllItem.fn) - .to - .equal(fn); + expect(beforeAllItem.title).to.equal('"after each" hook: test'); + expect(beforeAllItem.fn).to.equal(fn); }); - it('uses function name if available', function () { + it('uses function name if available', function() { if (!supportsFunctionNames()) { this.skip(); return; } - function namedFn () {} + function namedFn() {} this.suite.afterEach(namedFn); var afterEachItem = this.suite._afterEach[0]; expect(afterEachItem.title).to.equal('"after each" hook: namedFn'); @@ -321,8 +289,8 @@ describe('Suite', function () { }); }); - describe('.addSuite()', function () { - beforeEach(function () { + describe('.addSuite()', function() { + beforeEach(function() { this.first = new Suite('First suite'); this.first.timeout(4002); this.first.slow(200); @@ -330,24 +298,24 @@ describe('Suite', function () { this.first.addSuite(this.second); }); - it('sets the parent on the added Suite', function () { + it('sets the parent on the added Suite', function() { expect(this.second.parent).to.equal(this.first); }); - it('copies the timeout value', function () { + it('copies the timeout value', function() { expect(this.second.timeout()).to.equal(4002); }); - it('copies the slow value', function () { + it('copies the slow value', function() { expect(this.second.slow()).to.equal(200); }); - it('adds the suite to the suites collection', function () { + it('adds the suite to the suites collection', function() { expect(this.first.suites).to.have.length(1); expect(this.first.suites[0]).to.equal(this.second); }); - it('treats suite as pending if its parent is pending', function () { + it('treats suite as pending if its parent is pending', function() { this.first.pending = true; expect(this.second.isPending()).to.be(true); }); @@ -375,19 +343,19 @@ describe('Suite', function () { // }); // }); - describe('.fullTitle()', function () { - beforeEach(function () { + describe('.fullTitle()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('when there is no parent', function () { - it('returns the suite title', function () { + describe('when there is no parent', function() { + it('returns the suite title', function() { expect(this.suite.fullTitle()).to.equal('A Suite'); }); }); - describe('when there is a parent', function () { - it('returns the combination of parent\'s and suite\'s title', function () { + describe('when there is a parent', function() { + it("returns the combination of parent's and suite's title", function() { var parentSuite = new Suite('I am a parent'); parentSuite.addSuite(this.suite); expect(this.suite.fullTitle()).to.equal('I am a parent A Suite'); @@ -395,28 +363,28 @@ describe('Suite', function () { }); }); - describe('.titlePath()', function () { - beforeEach(function () { + describe('.titlePath()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('when there is no parent', function () { - it('returns the suite title', function () { + describe('when there is no parent', function() { + it('returns the suite title', function() { expect(this.suite.titlePath()).to.eql(['A Suite']); }); }); - describe('when there is a parent', function () { - describe('the parent is the root suite', function () { - it('returns the suite title', function () { + describe('when there is a parent', function() { + describe('the parent is the root suite', function() { + it('returns the suite title', function() { var parentSuite = new Suite(''); parentSuite.addSuite(this.suite); expect(this.suite.titlePath()).to.eql(['A Suite']); }); }); - describe('the parent is not the root suite', function () { - it('returns the concatenation of parent\'s and suite\'s title', function () { + describe('the parent is not the root suite', function() { + it("returns the concatenation of parent's and suite's title", function() { var parentSuite = new Suite('I am a parent'); parentSuite.addSuite(this.suite); expect(this.suite.titlePath()).to.eql(['I am a parent', 'A Suite']); @@ -425,19 +393,19 @@ describe('Suite', function () { }); }); - describe('.total()', function () { - beforeEach(function () { + describe('.total()', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('when there are no nested suites or tests', function () { - it('should return 0', function () { + describe('when there are no nested suites or tests', function() { + it('should return 0', function() { expect(this.suite.total()).to.equal(0); }); }); - describe('when there are several tests in the suite', function () { - it('should return the number', function () { + describe('when there are several tests in the suite', function() { + it('should return the number', function() { this.suite.addTest(new Test('a child test')); this.suite.addTest(new Test('another child test')); expect(this.suite.total()).to.equal(2); @@ -445,82 +413,88 @@ describe('Suite', function () { }); }); - describe('.eachTest(fn)', function () { - beforeEach(function () { + describe('.eachTest(fn)', function() { + beforeEach(function() { this.suite = new Suite('A Suite'); }); - describe('when there are no nested suites or tests', function () { - it('should return 0', function () { + describe('when there are no nested suites or tests', function() { + it('should return 0', function() { var n = 0; - function fn () { n++; } + function fn() { + n++; + } this.suite.eachTest(fn); expect(n).to.equal(0); }); }); - describe('when there are several tests in the suite', function () { - it('should return the number', function () { + describe('when there are several tests in the suite', function() { + it('should return the number', function() { this.suite.addTest(new Test('a child test')); this.suite.addTest(new Test('another child test')); var n = 0; - function fn () { n++; } + function fn() { + n++; + } this.suite.eachTest(fn); expect(n).to.equal(2); }); }); - describe('when there are several levels of nested suites', function () { - it('should return the number', function () { + describe('when there are several levels of nested suites', function() { + it('should return the number', function() { this.suite.addTest(new Test('a child test')); var suite = new Suite('a child suite'); suite.addTest(new Test('a test in a child suite')); this.suite.addSuite(suite); var n = 0; - function fn () { n++; } + function fn() { + n++; + } this.suite.eachTest(fn); expect(n).to.equal(2); }); }); }); - describe('initialization', function () { + describe('initialization', function() { /* eslint no-new: off */ - it('should throw an error if the title isn\'t a string', function () { - expect(function () { + it("should throw an error if the title isn't a string", function() { + expect(function() { new Suite(undefined, 'root'); }).to.throwError(); - expect(function () { - new Suite(function () {}, 'root'); + expect(function() { + new Suite(function() {}, 'root'); }).to.throwError(); }); - it('should not throw if the title is a string', function () { - expect(function () { + it('should not throw if the title is a string', function() { + expect(function() { new Suite('Bdd suite', 'root'); }).to.not.throwError(); }); }); }); -describe('Test', function () { - describe('initialization', function () { - it('should throw an error if the title isn\'t a string', function () { - expect(function () { - new Test(function () {}); +describe('Test', function() { + describe('initialization', function() { + it("should throw an error if the title isn't a string", function() { + expect(function() { + new Test(function() {}); }).to.throwError(); - expect(function () { - new Test(undefined, function () {}); + expect(function() { + new Test(undefined, function() {}); }).to.throwError(); }); - it('should not throw if the title is a string', function () { - expect(function () { - new Test('test-case', function () {}); + it('should not throw if the title is a string', function() { + expect(function() { + new Test('test-case', function() {}); }).to.not.throwError(); }); }); diff --git a/test/unit/test.spec.js b/test/unit/test.spec.js index 86aa5effa3..91bfc329e2 100644 --- a/test/unit/test.spec.js +++ b/test/unit/test.spec.js @@ -3,10 +3,10 @@ var mocha = require('../../lib/mocha'); var Test = mocha.Test; -describe('Test', function () { - describe('.clone()', function () { - beforeEach(function () { - this._test = new Test('To be cloned', function () {}); +describe('Test', function() { + describe('.clone()', function() { + beforeEach(function() { + this._test = new Test('To be cloned', function() {}); this._test._timeout = 3043; this._test._slow = 101; this._test._enableTimeouts = true; @@ -17,59 +17,63 @@ describe('Test', function () { this._test.file = 'bar'; }); - it('should copy the title', function () { + it('should copy the title', function() { expect(this._test.clone().title).to.equal('To be cloned'); }); - it('should copy the timeout value', function () { + it('should copy the timeout value', function() { expect(this._test.clone().timeout()).to.equal(3043); }); - it('should copy the slow value', function () { + it('should copy the slow value', function() { expect(this._test.clone().slow()).to.equal(101); }); - it('should copy the enableTimeouts value', function () { + it('should copy the enableTimeouts value', function() { expect(this._test.clone().enableTimeouts()).to.be(true); }); - it('should copy the retries value', function () { + it('should copy the retries value', function() { expect(this._test.clone().retries()).to.equal(3); }); - it('should copy the currentRetry value', function () { + it('should copy the currentRetry value', function() { expect(this._test.clone().currentRetry()).to.equal(1); }); - it('should copy the globals value', function () { + it('should copy the globals value', function() { expect(this._test.clone().globals()).to.not.be.empty(); }); - it('should copy the parent value', function () { + it('should copy the parent value', function() { expect(this._test.clone().parent).to.equal('foo'); }); - it('should copy the file value', function () { + it('should copy the file value', function() { expect(this._test.clone().file).to.equal('bar'); }); }); - describe('.isPending()', function () { - beforeEach(function () { - this._test = new Test('Is it skipped', function () {}); + describe('.isPending()', function() { + beforeEach(function() { + this._test = new Test('Is it skipped', function() {}); }); - it('should not be pending by default', function () { + it('should not be pending by default', function() { expect(this._test.isPending()).to.not.be(true); }); - it('should be pending when marked as such', function () { + it('should be pending when marked as such', function() { this._test.pending = true; expect(this._test.isPending()).to.be(true); }); - it('should be pending when its parent is pending', function () { - this._test.parent = { isPending: function () { return true; } }; + it('should be pending when its parent is pending', function() { + this._test.parent = { + isPending: function() { + return true; + } + }; expect(this._test.isPending()).to.be(true); }); }); diff --git a/test/unit/throw.spec.js b/test/unit/throw.spec.js index 104c0d3d2a..46168cf44e 100644 --- a/test/unit/throw.spec.js +++ b/test/unit/throw.spec.js @@ -6,12 +6,12 @@ var Suite = require('../../lib/suite'); var Test = require('../../lib/test'); var Runner = require('../../lib/runner'); -describe('a test that throws', function () { +describe('a test that throws', function() { var suite; var runner; var uncaughtHandlers; - beforeEach(function () { + beforeEach(function() { suite = new Suite('Suite', 'root'); runner = new Runner(suite); @@ -20,20 +20,20 @@ describe('a test that throws', function () { process.removeAllListeners('uncaughtException'); }); - afterEach(function () { - uncaughtHandlers.forEach(function (listener) { + afterEach(function() { + uncaughtHandlers.forEach(function(listener) { process.on('uncaughtException', listener); }); }); - describe('undefined', function () { - it('should not pass if throwing sync and test is sync', function (done) { - var test = new Test('im sync and throw undefined sync', function () { + describe('undefined', function() { + it('should not pass if throwing sync and test is sync', function(done) { + var test = new Test('im sync and throw undefined sync', function() { throw undefined; }); suite.addTest(test); runner = new Runner(suite); - runner.on('end', function () { + runner.on('end', function() { expect(runner.failures).to.equal(1); expect(test.state).to.equal('failed'); done(); @@ -41,13 +41,13 @@ describe('a test that throws', function () { runner.run(); }); - it('should not pass if throwing sync and test is async', function (done) { - var test = new Test('im async and throw undefined sync', function (done2) { + it('should not pass if throwing sync and test is async', function(done) { + var test = new Test('im async and throw undefined sync', function(done2) { throw undefined; }); suite.addTest(test); runner = new Runner(suite); - runner.on('end', function () { + runner.on('end', function() { expect(runner.failures).to.equal(1); expect(test.state).to.equal('failed'); done(); @@ -55,15 +55,17 @@ describe('a test that throws', function () { runner.run(); }); - it('should not pass if throwing async and test is async', function (done) { - var test = new Test('im async and throw undefined async', function (done2) { - process.nextTick(function () { + it('should not pass if throwing async and test is async', function(done) { + var test = new Test('im async and throw undefined async', function( + done2 + ) { + process.nextTick(function() { throw undefined; }); }); suite.addTest(test); runner = new Runner(suite); - runner.on('end', function () { + runner.on('end', function() { expect(runner.failures).to.equal(1); expect(test.state).to.equal('failed'); done(); @@ -72,14 +74,14 @@ describe('a test that throws', function () { }); }); - describe('null', function () { - it('should not pass if throwing sync and test is sync', function (done) { - var test = new Test('im sync and throw null sync', function () { + describe('null', function() { + it('should not pass if throwing sync and test is sync', function(done) { + var test = new Test('im sync and throw null sync', function() { throw null; }); suite.addTest(test); runner = new Runner(suite); - runner.on('end', function () { + runner.on('end', function() { expect(runner.failures).to.equal(1); expect(test.state).to.equal('failed'); done(); @@ -87,13 +89,13 @@ describe('a test that throws', function () { runner.run(); }); - it('should not pass if throwing sync and test is async', function (done) { - var test = new Test('im async and throw null sync', function (done2) { + it('should not pass if throwing sync and test is async', function(done) { + var test = new Test('im async and throw null sync', function(done2) { throw null; }); suite.addTest(test); runner = new Runner(suite); - runner.on('end', function () { + runner.on('end', function() { expect(runner.failures).to.equal(1); expect(test.state).to.equal('failed'); done(); @@ -101,15 +103,15 @@ describe('a test that throws', function () { runner.run(); }); - it('should not pass if throwing async and test is async', function (done) { - var test = new Test('im async and throw null async', function (done2) { - process.nextTick(function () { + it('should not pass if throwing async and test is async', function(done) { + var test = new Test('im async and throw null async', function(done2) { + process.nextTick(function() { throw null; }); }); suite.addTest(test); runner = new Runner(suite); - runner.on('end', function () { + runner.on('end', function() { expect(runner.failures).to.equal(1); expect(test.state).to.equal('failed'); done(); diff --git a/test/unit/timeout.spec.js b/test/unit/timeout.spec.js index 066e70d111..ce95edcb81 100644 --- a/test/unit/timeout.spec.js +++ b/test/unit/timeout.spec.js @@ -1,61 +1,61 @@ 'use strict'; -describe('timeouts', function () { - beforeEach(function (done) { +describe('timeouts', function() { + beforeEach(function(done) { // uncomment // setTimeout(done, 3000); done(); }); - it('should error on timeout', function (done) { + it('should error on timeout', function(done) { // uncomment // setTimeout(done, 3000); done(); }); - it('should allow overriding per-test', function (done) { + it('should allow overriding per-test', function(done) { this.timeout(200); - setTimeout(function () { + setTimeout(function() { done(); }, 50); }); - describe('disabling', function () { - it('should allow overriding per-test', function (done) { + describe('disabling', function() { + it('should allow overriding per-test', function(done) { this.enableTimeouts(false); this.timeout(1); setTimeout(done, 2); }); - it('should work with timeout(0)', function (done) { + it('should work with timeout(0)', function(done) { this.timeout(0); setTimeout(done, 1); }); - describe('using beforeEach', function () { - beforeEach(function () { + describe('using beforeEach', function() { + beforeEach(function() { this.timeout(0); }); - it('should work with timeout(0)', function (done) { + it('should work with timeout(0)', function(done) { setTimeout(done, 1); }); }); - describe('using before', function () { - before(function () { + describe('using before', function() { + before(function() { this.timeout(0); }); - it('should work with timeout(0)', function (done) { + it('should work with timeout(0)', function(done) { setTimeout(done, 1); }); }); - describe('using enableTimeouts(false)', function () { + describe('using enableTimeouts(false)', function() { this.timeout(4); - it('should suppress timeout(4)', function (done) { + it('should suppress timeout(4)', function(done) { this.slow(100); // The test is in the before() call. this.enableTimeouts(false); @@ -63,15 +63,15 @@ describe('timeouts', function () { }); }); - describe('suite-level', function () { + describe('suite-level', function() { this.timeout(0); - it('should work with timeout(0)', function (done) { + it('should work with timeout(0)', function(done) { setTimeout(done, 1); }); - describe('nested suite', function () { - it('should work with timeout(0)', function (done) { + describe('nested suite', function() { + it('should work with timeout(0)', function(done) { setTimeout(done, 1); }); }); diff --git a/test/unit/utils.spec.js b/test/unit/utils.spec.js index 7c4313ffee..b65098b113 100644 --- a/test/unit/utils.spec.js +++ b/test/unit/utils.spec.js @@ -2,85 +2,68 @@ var utils = require('../../lib/utils'); -describe('lib/utils', function () { - describe('clean', function () { - it('should remove the wrapping function declaration', function () { - expect(utils.clean('function (one, two, three) {\n//code\n}')) - .to - .equal('//code'); +describe('lib/utils', function() { + describe('clean', function() { + it('should remove the wrapping function declaration', function() { + expect(utils.clean('function (one, two, three) {\n//code\n}')).to.equal( + '//code' + ); }); - it('should handle newlines in the function declaration', function () { - expect(utils.clean('function (one, two, three)\n {\n//code\n}')) - .to - .equal('//code'); + it('should handle newlines in the function declaration', function() { + expect( + utils.clean('function (one, two, three)\n {\n//code\n}') + ).to.equal('//code'); }); - it('should remove space character indentation from the function body', - function () { - expect(utils.clean(' //line1\n //line2')) - .to - .equal('//line1\n //line2'); - }); + it('should remove space character indentation from the function body', function() { + expect(utils.clean(' //line1\n //line2')).to.equal( + '//line1\n //line2' + ); + }); - it('should remove tab character indentation from the function body', - function () { - expect(utils.clean('\t//line1\n\t\t//line2')) - .to - .equal('//line1\n\t//line2'); - }); + it('should remove tab character indentation from the function body', function() { + expect(utils.clean('\t//line1\n\t\t//line2')).to.equal( + '//line1\n\t//line2' + ); + }); - it('should handle functions with tabs in their declarations', function () { - expect(utils.clean('function\t(\t)\t{\n//code\n}')) - .to - .equal('//code'); + it('should handle functions with tabs in their declarations', function() { + expect(utils.clean('function\t(\t)\t{\n//code\n}')).to.equal('//code'); }); - it('should handle named functions without space after name', function () { - expect(utils.clean('function withName() {\n//code\n}')) - .to - .equal('//code'); + it('should handle named functions without space after name', function() { + expect(utils.clean('function withName() {\n//code\n}')).to.equal( + '//code' + ); }); - it('should handle named functions with space after name', function () { - expect(utils.clean('function withName () {\n//code\n}')) - .to - .equal('//code'); + it('should handle named functions with space after name', function() { + expect(utils.clean('function withName () {\n//code\n}')).to.equal( + '//code' + ); }); - it( - 'should handle functions with no space between the end and the closing brace', - function () { - expect(utils.clean('function() {/*code*/}')) - .to - .equal('/*code*/'); - }); + it('should handle functions with no space between the end and the closing brace', function() { + expect(utils.clean('function() {/*code*/}')).to.equal('/*code*/'); + }); - it('should handle functions with parentheses in the same line', - function () { - expect(utils.clean('function() { if (true) { /* code */ } }')) - .to - .equal('if (true) { /* code */ }'); - }); + it('should handle functions with parentheses in the same line', function() { + expect(utils.clean('function() { if (true) { /* code */ } }')).to.equal( + 'if (true) { /* code */ }' + ); + }); - it('should handle empty functions', function () { - expect(utils.clean('function() {}')) - .to - .equal(''); + it('should handle empty functions', function() { + expect(utils.clean('function() {}')).to.equal(''); }); - it('should format a single line test function', function () { - var fn = [ - 'function () {', - ' var a = 1;', - '}' - ].join('\n'); - expect(utils.clean(fn)) - .to - .equal('var a = 1;'); + it('should format a single line test function', function() { + var fn = ['function () {', ' var a = 1;', '}'].join('\n'); + expect(utils.clean(fn)).to.equal('var a = 1;'); }); - it('should format a multi line test indented with spaces', function () { + it('should format a multi line test indented with spaces', function() { // and no new lines after curly braces, shouldn't matter var fn = [ 'function(){ var a = 1;', @@ -88,12 +71,10 @@ describe('lib/utils', function () { ' var b = 2;', ' var c = 3; }' ].join('\n'); - expect(utils.clean(fn)) - .to - .equal('var a = 1;\n var b = 2;\nvar c = 3;'); + expect(utils.clean(fn)).to.equal('var a = 1;\n var b = 2;\nvar c = 3;'); }); - it('should format a multi line test indented with tabs', function () { + it('should format a multi line test indented with tabs', function() { var fn = [ 'function (arg1, arg2) {', '\tif (true) {', @@ -101,12 +82,10 @@ describe('lib/utils', function () { '\t}', '}' ].join('\n'); - expect(utils.clean(fn)) - .to - .equal('if (true) {\n\tvar a = 1;\n}'); + expect(utils.clean(fn)).to.equal('if (true) {\n\tvar a = 1;\n}'); }); - it('should format functions saved in windows style - spaces', function () { + it('should format functions saved in windows style - spaces', function() { var fn = [ 'function (one) {', ' do {', @@ -114,12 +93,10 @@ describe('lib/utils', function () { ' } while (false);', ' }' ].join('\r\n'); - expect(utils.clean(fn)) - .to - .equal('do {\n "nothing";\n} while (false);'); + expect(utils.clean(fn)).to.equal('do {\n "nothing";\n} while (false);'); }); - it('should format functions saved in windows style - tabs', function () { + it('should format functions saved in windows style - tabs', function() { var fn = [ 'function ( ) {', '\tif (false) {', @@ -129,78 +106,78 @@ describe('lib/utils', function () { '\t}', '}' ].join('\r\n'); - expect(utils.clean(fn)) - .to - .equal('if (false) {\n\tvar json = {\n\t\tone : 1\n\t};\n}'); + expect(utils.clean(fn)).to.equal( + 'if (false) {\n\tvar json = {\n\t\tone : 1\n\t};\n}' + ); }); - it('should format es6 arrow functions', function () { - var fn = [ - '() => {', - ' var a = 1;', - '}' - ].join('\n'); - expect(utils.clean(fn)) - .to - .equal('var a = 1;'); + it('should format es6 arrow functions', function() { + var fn = ['() => {', ' var a = 1;', '}'].join('\n'); + expect(utils.clean(fn)).to.equal('var a = 1;'); }); - it('should format es6 arrow functions with implicit return', function () { + it('should format es6 arrow functions with implicit return', function() { var fn = '() => foo()'; - expect(utils.clean(fn)) - .to - .equal('foo()'); + expect(utils.clean(fn)).to.equal('foo()'); }); }); - describe('stringify', function () { + describe('stringify', function() { var stringify = utils.stringify; - it('should return an object representation of a string created with a String constructor', function () { + it('should return an object representation of a string created with a String constructor', function() { /* eslint no-new-wrappers: off */ - expect(stringify(new String('foo'))).to.equal('{\n "0": "f"\n "1": "o"\n "2": "o"\n}'); + expect(stringify(new String('foo'))).to.equal( + '{\n "0": "f"\n "1": "o"\n "2": "o"\n}' + ); }); - it('should return Buffer with .toJSON representation', function () { + it('should return Buffer with .toJSON representation', function() { expect(stringify(Buffer.from([0x01]))).to.equal('[\n 1\n]'); expect(stringify(Buffer.from([0x01, 0x02]))).to.equal('[\n 1\n 2\n]'); - expect(stringify(Buffer.from('ABCD'))).to.equal('[\n 65\n 66\n 67\n 68\n]'); + expect(stringify(Buffer.from('ABCD'))).to.equal( + '[\n 65\n 66\n 67\n 68\n]' + ); }); - it('should return Date object with .toISOString() + string prefix', function () { - expect(stringify(new Date(0))).to.equal('[Date: ' + new Date(0).toISOString() + ']'); + it('should return Date object with .toISOString() + string prefix', function() { + expect(stringify(new Date(0))).to.equal( + '[Date: ' + new Date(0).toISOString() + ']' + ); var date = new Date(); // now expect(stringify(date)).to.equal('[Date: ' + date.toISOString() + ']'); }); - it('should return invalid Date object with .toString() + string prefix', function () { - expect(stringify(new Date(''))).to.equal('[Date: ' + new Date('').toString() + ']'); + it('should return invalid Date object with .toString() + string prefix', function() { + expect(stringify(new Date(''))).to.equal( + '[Date: ' + new Date('').toString() + ']' + ); }); - describe('#Number', function () { - it('should show the handle -0 situations', function () { + describe('#Number', function() { + it('should show the handle -0 situations', function() { expect(stringify(-0)).to.eql('-0'); expect(stringify(0)).to.eql('0'); expect(stringify('-0')).to.eql('"-0"'); }); - it('should work well with `NaN` and `Infinity`', function () { + it('should work well with `NaN` and `Infinity`', function() { expect(stringify(NaN)).to.equal('NaN'); expect(stringify(Infinity)).to.equal('Infinity'); expect(stringify(-Infinity)).to.equal('-Infinity'); }); - it('floats and ints', function () { + it('floats and ints', function() { expect(stringify(1)).to.equal('1'); expect(stringify(1.2)).to.equal('1.2'); expect(stringify(1e9)).to.equal('1000000000'); }); }); - describe('canonicalize example', function () { - it('should represent the actual full result', function () { + describe('canonicalize example', function() { + it('should represent the actual full result', function() { var expected = { str: 'string', int: 90, @@ -210,22 +187,16 @@ describe('lib/utils', function () { undef: undefined, regex: /^[a-z|A-Z]/, date: new Date(0), - func: function () {}, + func: function() {}, infi: Infinity, nan: NaN, zero: -0, buffer: Buffer.from([0x01, 0x02]), array: [1, 2, 3], empArr: [], - matrix: [[1], - [ - 2, - 3, - 4 - ] - ], - object: { a: 1, b: 2 }, - canObj: { a: { b: 1, c: 2 }, b: {} }, + matrix: [[1], [2, 3, 4]], + object: {a: 1, b: 2}, + canObj: {a: {b: 1, c: 2}, b: {}}, empObj: {} }; expected.circular = expected; // Make `Circular` situation @@ -282,40 +253,44 @@ describe('lib/utils', function () { }); }); - it('should canonicalize the object', function () { - var travis = { name: 'travis', age: 24 }; - var travis2 = { age: 24, name: 'travis' }; + it('should canonicalize the object', function() { + var travis = {name: 'travis', age: 24}; + var travis2 = {age: 24, name: 'travis'}; expect(stringify(travis)).to.equal(stringify(travis2)); }); - it('should handle circular structures in objects', function () { - var travis = { name: 'travis' }; + it('should handle circular structures in objects', function() { + var travis = {name: 'travis'}; travis.whoami = travis; - expect(stringify(travis)).to.equal('{\n "name": "travis"\n "whoami": [Circular]\n}'); + expect(stringify(travis)).to.equal( + '{\n "name": "travis"\n "whoami": [Circular]\n}' + ); }); - it('should handle circular structures in arrays', function () { + it('should handle circular structures in arrays', function() { var travis = ['travis']; travis.push(travis); expect(stringify(travis)).to.equal('[\n "travis"\n [Circular]\n]'); }); - it('should handle circular structures in functions', function () { - var travis = function () {}; + it('should handle circular structures in functions', function() { + var travis = function() {}; travis.fn = travis; expect(stringify(travis)).to.equal('{\n "fn": [Circular]\n}'); }); - it('should handle various non-undefined, non-null, non-object, non-array, non-date, and non-function values', function () { + it('should handle various non-undefined, non-null, non-object, non-array, non-date, and non-function values', function() { var regexp = new RegExp('(?:)'); var regExpObj = {regexp: regexp}; var regexpString = '/(?:)/'; - expect(stringify(regExpObj)).to.equal('{\n "regexp": ' + regexpString + '\n}'); + expect(stringify(regExpObj)).to.equal( + '{\n "regexp": ' + regexpString + '\n}' + ); expect(stringify(regexp)).to.equal(regexpString); var number = 1; @@ -329,34 +304,42 @@ describe('lib/utils', function () { var booleanObj = {boolean: boolean}; var booleanString = 'false'; - expect(stringify(booleanObj)).to.equal('{\n "boolean": ' + boolean + '\n}'); + expect(stringify(booleanObj)).to.equal( + '{\n "boolean": ' + boolean + '\n}' + ); expect(stringify(boolean)).to.equal(booleanString); var string = 'sneepy'; var stringObj = {string: string}; - expect(stringify(stringObj)).to.equal('{\n "string": "' + string + '"\n}'); + expect(stringify(stringObj)).to.equal( + '{\n "string": "' + string + '"\n}' + ); expect(stringify(string)).to.equal(JSON.stringify(string)); var nullValue = null; - var nullObj = {'null': null}; + var nullObj = {null: null}; var nullString = '[null]'; expect(stringify(nullObj)).to.equal('{\n "null": [null]\n}'); expect(stringify(nullValue)).to.equal(nullString); }); - it('should handle arrays', function () { + it('should handle arrays', function() { var array = ['dave', 'dave', 'dave', 'dave']; var arrayObj = {array: array}; var arrayString = ' "dave"\n "dave"\n "dave"\n "dave"'; - expect(stringify(arrayObj)).to.equal('{\n "array": [\n' + arrayString + '\n ]\n}'); - expect(stringify(array)).to.equal('[' + arrayString.replace(/\s+/g, '\n ') + '\n]'); + expect(stringify(arrayObj)).to.equal( + '{\n "array": [\n' + arrayString + '\n ]\n}' + ); + expect(stringify(array)).to.equal( + '[' + arrayString.replace(/\s+/g, '\n ') + '\n]' + ); }); - it('should handle functions', function () { - var fn = function () {}; + it('should handle functions', function() { + var fn = function() {}; var fnObj = {fn: fn}; var fnString = '[Function]'; @@ -364,59 +347,77 @@ describe('lib/utils', function () { expect(stringify(fn)).to.equal('[Function]'); }); - it('should handle empty objects', function () { + it('should handle empty objects', function() { expect(stringify({})).to.equal('{}'); expect(stringify({foo: {}})).to.equal('{\n "foo": {}\n}'); }); - it('should handle empty arrays', function () { + it('should handle empty arrays', function() { expect(stringify([])).to.equal('[]'); expect(stringify({foo: []})).to.equal('{\n "foo": []\n}'); }); - it('should handle non-empty arrays', function () { + it('should handle non-empty arrays', function() { expect(stringify(['a', 'b', 'c'])).to.equal('[\n "a"\n "b"\n "c"\n]'); }); - it('should handle empty functions (with no properties)', function () { - expect(stringify(function () {})).to.equal('[Function]'); - expect(stringify({foo: function () {}})).to.equal('{\n "foo": [Function]\n}'); - expect(stringify({foo: function () {}, bar: 'baz'})).to.equal('{\n "bar": "baz"\n "foo": [Function]\n}'); + it('should handle empty functions (with no properties)', function() { + expect(stringify(function() {})).to.equal('[Function]'); + expect(stringify({foo: function() {}})).to.equal( + '{\n "foo": [Function]\n}' + ); + expect(stringify({foo: function() {}, bar: 'baz'})).to.equal( + '{\n "bar": "baz"\n "foo": [Function]\n}' + ); }); - it('should handle functions w/ properties', function () { - var fn = function () {}; + it('should handle functions w/ properties', function() { + var fn = function() {}; fn.bar = 'baz'; expect(stringify(fn)).to.equal('{\n "bar": "baz"\n}'); - expect(stringify({foo: fn})).to.equal('{\n "foo": {\n "bar": "baz"\n }\n}'); - }); - - it('should handle undefined values', function () { - expect(stringify({foo: undefined})).to.equal('{\n "foo": [undefined]\n}'); - expect(stringify({foo: 'bar', baz: undefined})).to.equal('{\n "baz": [undefined]\n "foo": "bar"\n}'); + expect(stringify({foo: fn})).to.equal( + '{\n "foo": {\n "bar": "baz"\n }\n}' + ); + }); + + it('should handle undefined values', function() { + expect(stringify({foo: undefined})).to.equal( + '{\n "foo": [undefined]\n}' + ); + expect(stringify({foo: 'bar', baz: undefined})).to.equal( + '{\n "baz": [undefined]\n "foo": "bar"\n}' + ); expect(stringify()).to.equal('[undefined]'); }); - it('should recurse', function () { - expect(stringify({foo: {bar: {baz: {quux: {herp: 'derp'}}}}})).to.equal('{\n "foo": {\n "bar": {\n "baz": {\n "quux": {\n "herp": "derp"\n }\n }\n }\n }\n}'); + it('should recurse', function() { + expect(stringify({foo: {bar: {baz: {quux: {herp: 'derp'}}}}})).to.equal( + '{\n "foo": {\n "bar": {\n "baz": {\n "quux": {\n "herp": "derp"\n }\n }\n }\n }\n}' + ); }); - it('might get confusing', function () { + it('might get confusing', function() { expect(stringify(null)).to.equal('[null]'); }); - it('should not freak out if it sees a primitive twice', function () { - expect(stringify({foo: null, bar: null})).to.equal('{\n "bar": [null]\n "foo": [null]\n}'); - expect(stringify({foo: 1, bar: 1})).to.equal('{\n "bar": 1\n "foo": 1\n}'); + it('should not freak out if it sees a primitive twice', function() { + expect(stringify({foo: null, bar: null})).to.equal( + '{\n "bar": [null]\n "foo": [null]\n}' + ); + expect(stringify({foo: 1, bar: 1})).to.equal( + '{\n "bar": 1\n "foo": 1\n}' + ); }); - it('should stringify dates', function () { + it('should stringify dates', function() { var date = new Date(0); expect(stringify(date)).to.equal('[Date: 1970-01-01T00:00:00.000Z]'); - expect(stringify({date: date})).to.equal('{\n "date": [Date: 1970-01-01T00:00:00.000Z]\n}'); + expect(stringify({date: date})).to.equal( + '{\n "date": [Date: 1970-01-01T00:00:00.000Z]\n}' + ); }); - it('should handle object without an Object prototype', function () { + it('should handle object without an Object prototype', function() { var a; if (Object.create) { a = Object.create(null); @@ -430,28 +431,34 @@ describe('lib/utils', function () { // In old version node.js, Symbol is not available by default. if (typeof global.Symbol === 'function') { - it('should handle Symbol', function () { + it('should handle Symbol', function() { var symbol = Symbol('value'); expect(stringify(symbol)).to.equal('Symbol(value)'); - expect(stringify({symbol: symbol})).to.equal('{\n "symbol": Symbol(value)\n}'); + expect(stringify({symbol: symbol})).to.equal( + '{\n "symbol": Symbol(value)\n}' + ); }); } - it('should handle length properties that cannot be coerced to a number', function () { - expect(stringify({length: {nonBuiltinProperty: 0}})).to.equal('{\n "length": {\n "nonBuiltinProperty": 0\n }\n}'); - expect(stringify({length: 'a string where length should be'})).to.equal('{\n "length": "a string where length should be"\n}'); + it('should handle length properties that cannot be coerced to a number', function() { + expect(stringify({length: {nonBuiltinProperty: 0}})).to.equal( + '{\n "length": {\n "nonBuiltinProperty": 0\n }\n}' + ); + expect(stringify({length: 'a string where length should be'})).to.equal( + '{\n "length": "a string where length should be"\n}' + ); }); }); - describe('type', function () { + describe('type', function() { /* eslint no-extend-native: off */ var type = utils.type; var toString = Object.prototype.toString; - beforeEach(function () { + beforeEach(function() { // some JS engines such as PhantomJS 1.x exhibit this behavior - Object.prototype.toString = function () { + Object.prototype.toString = function() { if (this === global) { return '[object DOMWindow]'; } @@ -459,7 +466,7 @@ describe('lib/utils', function () { }; }); - it('should recognize various types', function () { + it('should recognize various types', function() { expect(type({})).to.equal('object'); expect(type([])).to.equal('array'); expect(type(1)).to.equal('number'); @@ -473,65 +480,59 @@ describe('lib/utils', function () { expect(type(true)).to.equal('boolean'); }); - describe('when toString on null or undefined stringifies window', function () { - it('should recognize null and undefined', function () { + describe('when toString on null or undefined stringifies window', function() { + it('should recognize null and undefined', function() { expect(type(null)).to.equal('null'); expect(type(undefined)).to.equal('undefined'); }); }); - afterEach(function () { + afterEach(function() { Object.prototype.toString = toString; }); }); - describe('parseQuery()', function () { + describe('parseQuery()', function() { var parseQuery = utils.parseQuery; - it('should get queryString and return key-value object', function () { - expect(parseQuery('?foo=1&bar=2&baz=3')) - .to - .eql({ - foo: '1', - bar: '2', - baz: '3' - }); - - expect(parseQuery('?r1=^@(?!.*\\)$)&r2=m{2}&r3=^co.*')) - .to - .eql({ - r1: '^@(?!.*\\)$)', - r2: 'm{2}', - r3: '^co.*' - }); - }); - - it('should parse "+" as a space', function () { - expect(parseQuery('?grep=foo+bar')) - .to - .eql({grep: 'foo bar'}); + it('should get queryString and return key-value object', function() { + expect(parseQuery('?foo=1&bar=2&baz=3')).to.eql({ + foo: '1', + bar: '2', + baz: '3' + }); + + expect(parseQuery('?r1=^@(?!.*\\)$)&r2=m{2}&r3=^co.*')).to.eql({ + r1: '^@(?!.*\\)$)', + r2: 'm{2}', + r3: '^co.*' + }); + }); + + it('should parse "+" as a space', function() { + expect(parseQuery('?grep=foo+bar')).to.eql({grep: 'foo bar'}); }); }); - describe('isPromise', function () { - it('should return true if the value is Promise-ish', function () { - expect(utils.isPromise({ - then: function () { - } - })).to.be(true); + describe('isPromise', function() { + it('should return true if the value is Promise-ish', function() { + expect( + utils.isPromise({ + then: function() {} + }) + ).to.be(true); }); - it('should return false if the value is not an object', function () { + it('should return false if the value is not an object', function() { expect(utils.isPromise(1)).to.be(false); }); - it('should return false if the value is an object w/o a "then" function', - function () { - expect(utils.isPromise({})).to.be(false); - }); + it('should return false if the value is an object w/o a "then" function', function() { + expect(utils.isPromise({})).to.be(false); + }); }); - describe('escape', function () { - it('replaces the usual xml suspects', function () { + describe('escape', function() { + it('replaces the usual xml suspects', function() { expect(utils.escape('a>bc>d>')).to.be('>a>bc>d>'); expect(utils.escape('"a"bc"d"')).to.be('"a"bc"d"'); @@ -541,8 +542,10 @@ describe('lib/utils', function () { expect(utils.escape('&<')).to.be('&amp;&lt;'); }); - it('replaces invalid xml characters', function () { - expect(utils.escape('\x1B[32mfoo\x1B[0m')).to.be('foo'); + it('replaces invalid xml characters', function() { + expect(utils.escape('\x1B[32mfoo\x1B[0m')).to.be( + 'foo' + ); // Ensure we can handle non-trivial unicode characters as well expect(utils.escape('💩')).to.be('💩'); });