Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

implementation of global setup/teardown; closes #4308 (#4360)

Christopher Hiller12db9dbc9dd3
diff --git a/.eslintignore b/.eslintignore
index a7a33c25..bf70c4eb 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -2,6 +2,7 @@ coverage/
mocha.js
*.fixture.js
docs/_site
+docs/api
docs/_dist
docs/example
out/
diff --git a/.wallaby.js b/.wallaby.js
index b23a2446..59083bb5 100644
--- a/.wallaby.js
+++ b/.wallaby.js
@@ -48,6 +48,7 @@ module.exports = () => {
);
require('./test/setup');
},
- debug: true
+ debug: true,
+ runMode: 'onsave'
};
};
diff --git a/docs/index.md b/docs/index.md
index b8396ea3..ebe5f86e 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -78,9 +78,9 @@ In your editor:
```js
var assert = require('assert');
-describe('Array', function () {
- describe('#indexOf()', function () {
- it('should return -1 when the value is not present', function () {
+describe('Array', function() {
+ describe('#indexOf()', function() {
+ it('should return -1 when the value is not present', function() {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
@@ -116,51 +116,65 @@ $ npm test
## Run Cycle Overview
-A brief outline on the order Mocha's components are executed.
-Worth noting that all hooks, `describe` and `it` callbacks are run in the order they are defined (i.e. found in the file).
-
-```
-run 'mocha spec.js'
-|
-spawn child process
-|
-|--------------> inside child process
- process and apply options
- |
- run spec file/s
- |
- |--------------> per spec file
- suite callbacks (e.g., 'describe')
- |
- 'before' root-level pre-hook
- |
- 'before' pre-hook
- |
- |--------------> per test
- 'beforeEach' root-level pre-hook
- |
- 'beforeEach' pre-hook
- |
- test callbacks (e.g., 'it')
- |
- 'afterEach' post-hook
- |
- 'afterEach' root-level post-hook
- |<-------------- per test end
- |
- 'after' post-hook
- |
- 'after' root-level post-hooks
- |<-------------- per spec file end
-|<-------------- inside child process end
-```
+> Updated for v9.0.0.
+
+The following is a mid-level outline of Mocha's "flow of execution" when run in Node.js; the "less important" details have been omitted.
+
+In a browser, test files are loaded by `<script>` tags, and calling `mocha.run()` begins at step 9 [below](#serial-mode).
+
+### Serial Mode
+
+1. User (that's you) executes `mocha`
+2. Loads options from config files, if present
+3. Mocha processes any command-line options provided (see section on [configuration merging](#merging) for details)
+4. If known flags for the `node` executable are found:
+ 1. Mocha will spawn `node` in a child process, executing itself with these flags
+ 2. Otherwise, Mocha does not spawn a child process
+5. Mocha loads modules specified by `--require`
+ 1. If a file loaded this way contains known Mocha-specific exports (e.g., [root hook plugins]), Mocha "registers" these
+ 2. If not, Mocha ignores any exports of a `--require`'d module
+6. Mocha validates any custom reporters or interfaces which were loaded via `--require` or otherwise
+7. Mocha _discovers_ test files; when given no files or directories, it finds files with extensions `.js`, `.mjs` or `.cjs` in the `test` directory (but not its children), relative to the current working directory
+8. The (default) [bdd interface](#bdd) loads the test files _in no particular order_, which are given an interface-specific `global` context (this is how, e.g., `describe()` ends up as a global in a test file)
+ 1. When a test file is loaded, Mocha executes all of its suites and finds--_but does not execute_--any hooks and tests therein.
+ 2. Top-level hooks, tests and suites are all made members of an "invisible" _root suite_; there is only _one_ root suite for the entire process
+9. Mocha runs [global setup fixtures], if any
+10. Starting with the "root" suite, Mocha executes:
+11. Any "before all" hooks (for the _root_ suite, this only happens once; see [root hook plugins])
+12. For each test, Mocha executes:
+ 1. Any "before each" hooks
+ 2. The test (and reports the result)
+ 3. Any "after each" hooks
+13. If the current suite has a child suite, repeat the steps in 10. for each child suite; each child suite _inherits_ any "before each" and "after each" hooks defined in its parent
+14. Any "after all" hooks (for the _root_ suite, this only happens once; see [root hook plugins])
+15. Mocha prints a final summary/epilog, if applicable
+16. Mocha runs [global teardown fixtures], if any
+
+### Parallel Mode
+
+1. Repeat steps 1 through 6 from [Serial Mode](#serial-mode) above, skipping reporter validation
+2. All test files found are put into a queue (they are _not_ loaded by the main process)
+3. Mocha runs [global setup fixtures], if any
+4. Mocha creates a pool of subprocesses ("workers")
+5. _Immediately before_ a worker runs the first test it receives, the worker "bootstraps" itself by:
+ 1. Loading all `--require`'d modules
+ 2. Registering any root hook plugins
+ 3. _Ignoring_ global fixtures and custom reporters
+ 4. Asserting the built-in or custom interface is valid
+6. When a worker receives a test file to run, the worker creates a new Mocha instance _for the single test file_, and:
+7. The worker repeats step 8 from [above](#serial-mode)
+8. The worker repeats step 10 from [above](#serial-mode), with the caveat that the worker _does not_ report test results directly; it holds them in a memory buffer
+9. When the worker completes the test file, buffered results are returned to the main process, which then gives them to the user-specified reporter (`spec` by default)
+10. The worker makes itself available to the pool; the pool gives the worker another test file to run, if any remain
+11. Mocha prints a final summary/epilog, if applicable
+12. Mocha runs [global teardown fixtures], if any
## Detects Multiple Calls to `done()`
If you use callback-based async tests, Mocha will throw an error if `done()` is called multiple times. This is handy for catching accidental double callbacks.
```javascript
-it('double done', function (done) {
+it('double done', function(done) {
// Calling `done()` twice is an error
setImmediate(done);
setImmediate(done);
@@ -203,11 +217,11 @@ Mocha allows you to use any assertion library you wish. In the above example, we
By adding an argument (usually named `done`) to `it()` to a test callback, Mocha will know that it should wait for this function to be called to complete the test. This callback accepts both an `Error` instance (or subclass thereof) _or_ a falsy value; anything else is invalid usage and throws an error (usually causing a failed test).
```js
-describe('User', function () {
- describe('#save()', function () {
- it('should save without error', function (done) {
+describe('User', function() {
+ describe('#save()', function() {
+ it('should save without error', function(done) {
var user = new User('Luna');
- user.save(function (err) {
+ user.save(function(err) {
if (err) done(err);
else done();
});
@@ -219,9 +233,9 @@ describe('User', function () {
Alternatively, use the `done()` callback directly (which will handle an error argument, if it exists):
```js
-describe('User', function () {
- describe('#save()', function () {
- it('should save without error', function (done) {
+describe('User', function() {
+ describe('#save()', function() {
+ it('should save without error', function(done) {
var user = new User('Luna');
user.save(done);
});
@@ -234,14 +248,14 @@ describe('User', function () {
Alternately, instead of using the `done()` callback, you may return a [Promise][mdn-promise]. This is useful if the APIs you are testing return promises instead of taking callbacks:
```js
-beforeEach(function () {
- return db.clear().then(function () {
+beforeEach(function() {
+ return db.clear().then(function() {
return db.save([tobi, loki, jane]);
});
});
-describe('#find()', function () {
- it('respond with matching records', function () {
+describe('#find()', function() {
+ it('respond with matching records', function() {
return db.find({type: 'User'}).should.eventually.have.length(3);
});
});
@@ -255,8 +269,8 @@ In Mocha v3.0.0 and newer, returning a `Promise` _and_ calling `done()` will res
const assert = require('assert');
// antipattern
-it('should complete this test', function (done) {
- return new Promise(function (resolve) {
+it('should complete this test', function(done) {
+ return new Promise(function(resolve) {
assert.ok(true);
resolve();
}).then(done);
@@ -270,13 +284,13 @@ The above test will fail with `Error: Resolution method is overspecified. Specif
If your JS environment supports [async / await][mdn-async], you can also write asynchronous tests like this:
```js
-beforeEach(async function () {
+beforeEach(async function() {
await db.clear();
await db.save([tobi, loki, jane]);
});
-describe('#find()', function () {
- it('responds with matching records', async function () {
+describe('#find()', function() {
+ it('responds with matching records', async function() {
const users = await db.find({type: 'User'});
users.should.have.length(3);
});
@@ -288,9 +302,9 @@ describe('#find()', function () {
When testing synchronous code, omit the callback and Mocha will automatically continue on to the next test.
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it('should return -1 when the value is not present', function () {
+describe('Array', function() {
+ describe('#indexOf()', function() {
+ it('should return -1 when the value is not present', function() {
[1, 2, 3].indexOf(5).should.equal(-1);
[1, 2, 3].indexOf(0).should.equal(-1);
});
@@ -319,20 +333,20 @@ _If you do not need to use_ Mocha's context, lambdas should work. Be aware that
With its default "BDD"-style interface, Mocha provides the hooks `before()`, `after()`, `beforeEach()`, and `afterEach()`. These should be used to set up preconditions and clean up after your tests.
```js
-describe('hooks', function () {
- before(function () {
+describe('hooks', function() {
+ before(function() {
// runs once before the first test in this block
});
- after(function () {
+ after(function() {
// runs once after the last test in this block
});
- beforeEach(function () {
+ beforeEach(function() {
// runs before each test in this block
});
- afterEach(function () {
+ afterEach(function() {
// runs after each test in this block
});
@@ -347,7 +361,7 @@ describe('hooks', function () {
Any hook can be invoked with an optional description, making it easier to pinpoint errors in your tests. If a hook is given a named function, that name will be used if no description is supplied.
```js
-beforeEach(function () {
+beforeEach(function() {
// beforeEach hook
});
@@ -355,7 +369,7 @@ beforeEach(function namedFun() {
// beforeEach:namedFun
});
-beforeEach('some description', function () {
+beforeEach('some description', function() {
// beforeEach:some description
});
```
@@ -365,22 +379,22 @@ beforeEach('some description', function () {
All hooks (`before()`, `after()`, `beforeEach()`, `afterEach()`) may be sync or async as well, behaving much like a regular test-case. For example, you may wish to populate database with dummy content before each test:
```js
-describe('Connection', function () {
+describe('Connection', function() {
var db = new Connection(),
tobi = new User('tobi'),
loki = new User('loki'),
jane = new User('jane');
- beforeEach(function (done) {
- db.clear(function (err) {
+ beforeEach(function(done) {
+ db.clear(function(err) {
if (err) return done(err);
db.save([tobi, loki, jane], done);
});
});
- describe('#find()', function () {
- it('respond with matching records', function (done) {
- db.find({type: 'User'}, function (err, res) {
+ describe('#find()', function() {
+ it('respond with matching records', function(done) {
+ db.find({type: 'User'}, function(err, res) {
if (err) return done(err);
res.should.have.length(3);
done();
@@ -394,7 +408,7 @@ describe('Connection', function () {
A hook defined at the top scope of a test file (outside of a suite) is a _root hook_.
-As of v8.0.0, [Root Hook Plugins](#root-hook-plugins) are the preferred mechanism for setting root hooks.
+As of v8.0.0, [Root Hook Plugins] are the preferred mechanism for setting root hooks.
### Delayed Root Suite
@@ -403,10 +417,10 @@ As of v8.0.0, [Root Hook Plugins](#root-hook-plugins) are the preferred mechanis
If you need to perform asynchronous operations before any of your suites are run, you may delay the root suite. Run `mocha` with the `--delay` flag. This will attach a special callback function, `run()`, to the global context:
```js
-setTimeout(function () {
+setTimeout(function() {
// do some setup
- describe('my suite', function () {
+ describe('my suite', function() {
// ...
});
@@ -419,8 +433,8 @@ setTimeout(function () {
"Pending"--as in "someone should write these test cases eventually"--test-cases are those _without_ a callback:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
+describe('Array', function() {
+ describe('#indexOf()', function() {
// pending test below
it('should return -1 when the value is not present');
});
@@ -439,8 +453,8 @@ The exclusivity feature allows you to run _only_ the specified suite or test-cas
by appending `.only()` to the function. Here's an example of executing only a particular suite:
```js
-describe('Array', function () {
- describe.only('#indexOf()', function () {
+describe('Array', function() {
+ describe.only('#indexOf()', function() {
// ...
});
});
@@ -451,13 +465,13 @@ _Note_: All nested suites will still be executed.
Here's an example of executing an individual test case:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it.only('should return -1 unless present', function () {
+describe('Array', function() {
+ describe('#indexOf()', function() {
+ it.only('should return -1 unless present', function() {
// ...
});
- it('should return the index when present', function () {
+ it('should return the index when present', function() {
// ...
});
});
@@ -467,17 +481,17 @@ describe('Array', function () {
Previous to v3.0.0, `.only()` used string matching to decide which tests to execute; this is no longer the case. In v3.0.0 or newer, `.only()` can be used multiple times to define a subset of tests to run:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it.only('should return -1 unless present', function () {
+describe('Array', function() {
+ describe('#indexOf()', function() {
+ it.only('should return -1 unless present', function() {
// this test will be run
});
- it.only('should return the index when present', function () {
+ it.only('should return the index when present', function() {
// this test will also be run
});
- it('should return -1 if called with a non-Array context', function () {
+ it('should return -1 if called with a non-Array context', function() {
// this test will not be run
});
});
@@ -487,25 +501,25 @@ describe('Array', function () {
You may also choose multiple suites:
```js
-describe('Array', function () {
- describe.only('#indexOf()', function () {
- it('should return -1 unless present', function () {
+describe('Array', function() {
+ describe.only('#indexOf()', function() {
+ it('should return -1 unless present', function() {
// this test will be run
});
- it('should return the index when present', function () {
+ it('should return the index when present', function() {
// this test will also be run
});
});
- describe.only('#concat()', function () {
- it('should return a new Array', function () {
+ describe.only('#concat()', function() {
+ it('should return a new Array', function() {
// this test will also be run
});
});
- describe('#slice()', function () {
- it('should return a new Array', function () {
+ describe('#slice()', function() {
+ it('should return a new Array', function() {
// this test will not be run
});
});
@@ -515,13 +529,13 @@ describe('Array', function () {
But _tests will have precedence_:
```js
-describe('Array', function () {
- describe.only('#indexOf()', function () {
- it.only('should return -1 unless present', function () {
+describe('Array', function() {
+ describe.only('#indexOf()', function() {
+ it.only('should return -1 unless present', function() {
// this test will be run
});
- it('should return the index when present', function () {
+ it('should return the index when present', function() {
// this test will not be run
});
});
@@ -537,13 +551,13 @@ _Note_: Hooks, if present, will still be executed.
This feature is the inverse of `.only()`. By appending `.skip()`, you may tell Mocha to ignore test case(s). Anything skipped will be marked as [pending](#pending-tests), and reported as such. Here's an example of skipping an individual test:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it.skip('should return -1 unless present', function () {
+describe('Array', function() {
+ describe('#indexOf()', function() {
+ it.skip('should return -1 unless present', function() {
// this test will not be run
});
- it('should return the index when present', function () {
+ it('should return the index when present', function() {
// this test will be run
});
});
@@ -553,9 +567,9 @@ describe('Array', function () {
You can also put `.skip()` on an entire suite. This is equivalent to appending `.skip()` onto all tests in the suite. Hooks in the suite are also skipped.
```js
-describe('Array', function () {
- describe.skip('#indexOf()', function () {
- it('should return -1 unless present', function () {
+describe('Array', function() {
+ describe.skip('#indexOf()', function() {
+ it('should return -1 unless present', function() {
// this test will not be run
});
});
@@ -613,21 +627,21 @@ before(function() {
This will skip all `it`, `beforeEach/afterEach`, and `describe` blocks within the suite. `before/after` hooks are skipped unless they are defined at the same level as the hook containing `this.skip()`.
```js
-describe('outer', function () {
- before(function () {
+describe('outer', function() {
+ before(function() {
this.skip();
});
- after(function () {
+ after(function() {
// will be executed
});
- describe('inner', function () {
- before(function () {
+ describe('inner', function() {
+ before(function() {
// will be skipped
});
- after(function () {
+ after(function() {
// will be skipped
});
});
@@ -647,15 +661,15 @@ This feature does re-run a failed test and its corresponding `beforeEach/afterEa
**NOTE**: Example below was written using Selenium webdriver (which [overwrites global Mocha hooks][selenium-webdriver-testing] for `Promise` chain).
```js
-describe('retries', function () {
+describe('retries', function() {
// Retry all tests in this suite up to 4 times
this.retries(4);
- beforeEach(function () {
+ beforeEach(function() {
browser.get('http://www.yahoo.com');
});
- it('should succeed on the 3rd try', function () {
+ it('should succeed on the 3rd try', function() {
// Specify this test to only retry up to 2 times
this.retries(2);
expect($('.foo').isDisplayed()).to.eventually.be.true;
@@ -673,20 +687,20 @@ Take the following example:
var assert = require('chai').assert;
function add() {
- return Array.prototype.slice.call(arguments).reduce(function (prev, curr) {
+ return Array.prototype.slice.call(arguments).reduce(function(prev, curr) {
return prev + curr;
}, 0);
}
-describe('add()', function () {
+describe('add()', function() {
var tests = [
{args: [1, 2], expected: 3},
{args: [1, 2, 3], expected: 6},
- {args: [1, 2, 3, 4], expected: 10},
+ {args: [1, 2, 3, 4], expected: 10}
];
- tests.forEach(function (test) {
- it('correctly adds ' + test.args.length + ' args', function () {
+ tests.forEach(function(test) {
+ it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected);
});
@@ -722,10 +736,10 @@ There are three levels of test duration (depicted in the following image):
To tweak what's considered "slow", you can use the `slow()` method:
```js
-describe('something slow', function () {
+describe('something slow', function() {
this.slow(300000); // five minutes
- it('should take long enough for me to go make a sandwich', function () {
+ it('should take long enough for me to go make a sandwich', function() {
// ...
});
});
@@ -738,14 +752,14 @@ describe('something slow', function () {
Suite-level timeouts may be applied to entire test "suites", or disabled via `this.timeout(0)`. This will be inherited by all nested suites and test-cases that do not override the value.
```js
-describe('a suite of tests', function () {
+describe('a suite of tests', function() {
this.timeout(500);
- it('should take less than 500ms', function (done) {
+ it('should take less than 500ms', function(done) {
setTimeout(done, 300);
});
- it('should take less than 500ms as well', function (done) {
+ it('should take less than 500ms as well', function(done) {
setTimeout(done, 250);
});
});
@@ -756,7 +770,7 @@ describe('a suite of tests', function () {
Test-specific timeouts may also be applied, or the use of `this.timeout(0)` to disable timeouts all together:
```js
-it('should take less than 500ms', function (done) {
+it('should take less than 500ms', function(done) {
this.timeout(500);
setTimeout(done, 300);
});
@@ -767,8 +781,8 @@ it('should take less than 500ms', function (done) {
Hook-level timeouts may also be applied:
```js
-describe('a suite of tests', function () {
- beforeEach(function (done) {
+describe('a suite of tests', function() {
+ beforeEach(function(done) {
this.timeout(3000); // A very long environment setup.
setTimeout(done, 2500);
});
@@ -1066,17 +1080,17 @@ Cause Mocha to only run tests matching the given `regexp`, which is internally c
Suppose, for example, you have "api" related tests, as well as "app" related tests, as shown in the following snippet; One could use `--grep api` or `--grep app` to run one or the other. The same goes for any other part of a suite or test-case title, `--grep users` would be valid as well, or even `--grep GET`.
```js
-describe('api', function () {
- describe('GET /api/users', function () {
- it('respond with an array of users', function () {
+describe('api', function() {
+ describe('GET /api/users', function() {
+ it('respond with an array of users', function() {
// ...
});
});
});
-describe('app', function () {
- describe('GET /users', function () {
- it('respond with an array of users', function () {
+describe('app', function() {
+ describe('GET /users', function() {
+ it('respond with an array of users', function() {
// ...
});
});
@@ -1229,12 +1243,12 @@ A _root hook_ is a hook in a test file which is _not defined_ within a suite. An
// test/setup.js
// root hook to run before every test (even in other files)
-beforeEach(function () {
+beforeEach(function() {
doMySetup();
});
// root hook to run after every test (even in other files)
-afterEach(function () {
+afterEach(function() {
doMyTeardown();
});
```
@@ -1308,7 +1322,7 @@ exports.mochaHooks = {
beforeEach(done) {
// do something before every test
done();
- },
+ }
};
```
@@ -1325,7 +1339,7 @@ export const mochaHooks = {
beforeEach(done) {
// do something before every test
done();
- },
+ }
};
```
@@ -1361,7 +1375,7 @@ export const mochaHooks = {
if (require('os').userInfo().username === 'bob') {
return this.skip();
}
- },
+ }
};
```
@@ -1374,14 +1388,14 @@ Multiple root hooks can be defined in a single plugin, for organizational purpos
export const mochaHooks = {
beforeEach: [
- function (done) {
+ function(done) {
// do something before every test,
// then run the next hook in this array
},
- async function () {
+ async function() {
// async or Promise-returning functions allowed
- },
- ],
+ }
+ ]
};
```
@@ -1397,20 +1411,20 @@ export const mochaHooks = () => {
// root hooks object
return {
beforeEach: [
- function () {
+ function() {
// CI-specific beforeEach
},
- function () {
+ function() {
// some other CI-specific beforeEach
- },
- ],
+ }
+ ]
};
}
// root hooks object
return {
beforeEach() {
// regular beforeEach
- },
+ }
};
};
```
@@ -1428,7 +1442,7 @@ export const mochaHooks = async () => {
return {
beforeEach() {
// something
- },
+ }
};
}
};
@@ -1453,16 +1467,16 @@ For example, given the following file, `test/test.spec.js`, containing root hook
```js
// test/test.spec.js
-beforeEach(function () {
+beforeEach(function() {
// global setup for all tests
});
-after(function () {
+after(function() {
// one-time final cleanup
});
-describe('my test suite', function () {
- it('should have run my global setup', function () {
+describe('my test suite', function() {
+ it('should have run my global setup', function() {
// make assertion
});
});
@@ -1490,8 +1504,8 @@ Your original `test/test.spec.js` should now contain:
```js
// test/test.spec.js
-describe('my test suite', function () {
- it('should have run my global setup', function () {
+describe('my test suite', function() {
+ it('should have run my global setup', function() {
// make assertion
});
});
@@ -1507,6 +1521,138 @@ If you're a library maintainer, and your library uses root hooks, you can migrat
- To maintain backwards compatibility, run your root hooks _if and only if_ `global.beforeEach` (or other relevant hook) exists.
- Instruct your users to `--require <your-package>` when running `mocha`.
+## Global Fixtures
+
+> New in v9.0.0
+
+At first glance, _global fixtures_ seem similar to [root hooks](#root-hook-plugins). However, unlike root hooks, global fixtures:
+
+1. Are _guaranteed_ to execute _once and only once_
+1. Work identically parallel mode, watch mode, and serial mode
+1. Do not share a context with tests, suites, or other hooks
+
+There are two types of global fixtures: [global setup fixtures] and [global teardown fixtures].
+
+### Global Setup Fixtures
+
+To create a global setup fixture, export `mochaGlobalSetup` from a script, e.g.,:
+
+```js
+// fixtures.cjs
+
+// can be async or not
+exports.mochaGlobalSetup = async function() {
+ this.server = await startSomeServer({port: process.env.TEST_PORT});
+ console.log(`server running on port ${this.server.port}`);
+};
+```
+
+...or an ES module:
+
+```js
+// fixtures.mjs
+
+// can be async or not
+export async function mochaGlobalSetup() {
+ this.server = await startSomeServer({port: process.env.TEST_PORT});
+ console.log(`server running on port ${this.server.port}`);
+}
+```
+
+To use it, load this file when running Mocha via `mocha --require fixtures.cjs` (or whatever you have named the file).
+
+> Remember: you can define "requires" in a [configuration file](#configuring-mocha-nodejs).
+
+Now, before Mocha loads and runs your tests, it will execute the above global setup fixture, starting a server for testing. This won't shut _down_ the server when Mocha is done, however! To do that, use a [_global teardown fixture_](#global-teardown-fixtures).
+
+### Global Teardown Fixtures
+
+Just like a [global setup fixture](#global-setup-fixtures), a _global teardown fixture_ can be created by exporting from a "required" script (we can put both types of fixtures in a single file):
+
+```js
+// fixtures.cjs, cont'd
+
+// can be async or not
+exports.mochaGlobalTeardown = async function() {
+ await this.server.stop();
+ console.log('server stopped!');
+};
+```
+
+...or an ES module:
+
+```js
+// fixtures.mjs, cont'd
+
+// can be async or not
+export async function mochaGlobalTeardown() {
+ await this.server.stop();
+ console.log('server stopped!');
+}
+```
+
+You'll note that we used `this` in the fixture examples. Global setup fixtures and global teardown fixtures _share a context_, which means we can add properties to the context object (`this`) in the setup fixture, and reference them later in the teardown fixture. This is more useful when the fixtures are in separate files, since you can just use JS' variable scoping rules instead ([example below](#when-not-to-use-global-fixtures)).
+
+As explained [above](#global-fixtures)--and [below](#when-not-to-use-global-fixtures)--test files _do not_ have access to this context object.
+
+### When To Use Global Fixtures
+
+Global fixtures are good for spinning up a server, opening a socket, or otherwise creating a resource that your tests will repeatedly access via I/O.
+
+### When Not To Use Global Fixtures
+
+If you need to access an in-memory value (such as a file handle or database connection), _don't_ use global fixtures to do this, because your tests will not have access to the value.
+
+> You could be clever and try to get around this restriction by assigning something to the `global` object, but this will _not_ work in parallel mode. It's probably best to play by the rules!
+
+Instead, use the global fixture to _start_ the database, and use [root hook plugins](#root-hook-plugins) or plain ol' [hooks](#hooks) to create a connection.
+
+Here's an example of using global fixtures and "before all" hooks to get the job done. Note that we do not reference the `server` object anywhere in our tests!
+
+First, use a global fixture to start and stop a test server:
+
+```js
+// fixtures.mjs
+
+let server;
+
+export const mochaGlobalSetup = async () => {
+ server = await startSomeServer({port: process.env.TEST_PORT});
+ console.log(`server running on port ${server.port}`);
+};
+
+export const mochaGlobalTeardown = async () => {
+ await server.stop();
+ console.log('server stopped!');
+};
+```
+
+Then, connect to the server in your tests:
+
+```js
+// test.spec.mjs
+
+import {connect} from 'my-server-connector-thingy';
+
+describe('my API', function() {
+ let connection;
+
+ before(async function() {
+ connection = await connect({port: process.env.TEST_PORT});
+ });
+
+ it('should be a nice API', function() {
+ // assertions here
+ });
+
+ after(async function() {
+ return connection.close();
+ });
+});
+```
+
+Finally, use this command to bring it together: `mocha --require fixtures.mjs test.spec.mjs`.
+
## Interfaces
Mocha's "interface" system allows developers to choose their style of DSL. Mocha has **BDD**, **TDD**, **Exports**, **QUnit** and **Require**-style interfaces.
@@ -1520,24 +1666,24 @@ The **BDD** interface provides `describe()`, `context()`, `it()`, `specify()`, `
> All of the previous examples were written using the **BDD** interface.
```js
-describe('Array', function () {
- before(function () {
+describe('Array', function() {
+ before(function() {
// ...
});
- describe('#indexOf()', function () {
- context('when not present', function () {
- it('should not throw an error', function () {
- (function () {
+ describe('#indexOf()', function() {
+ context('when not present', function() {
+ it('should not throw an error', function() {
+ (function() {
[1, 2, 3].indexOf(4);
}.should.not.throw());
});
- it('should return -1', function () {
+ it('should return -1', function() {
[1, 2, 3].indexOf(4).should.equal(-1);
});
});
- context('when present', function () {
- it('should return the index where the element first appears in the array', function () {
+ context('when present', function() {
+ it('should return the index where the element first appears in the array', function() {
[1, 2, 3].indexOf(3).should.equal(2);
});
});
@@ -1550,13 +1696,13 @@ describe('Array', function () {
The **TDD** interface provides `suite()`, `test()`, `suiteSetup()`, `suiteTeardown()`, `setup()`, and `teardown()`:
```js
-suite('Array', function () {
- setup(function () {
+suite('Array', function() {
+ setup(function() {
// ...
});
- suite('#indexOf()', function () {
- test('should return -1 when not present', function () {
+ suite('#indexOf()', function() {
+ test('should return -1 when not present', function() {
assert.equal(-1, [1, 2, 3].indexOf(4));
});
});
@@ -1569,17 +1715,17 @@ The **Exports** interface is much like Mocha's predecessor [expresso][]. The key
```js
module.exports = {
- before: function () {
+ before: function() {
// ...
},
Array: {
'#indexOf()': {
- 'should return -1 when not present': function () {
+ 'should return -1 when not present': function() {
[1, 2, 3].indexOf(4).should.equal(-1);
- },
- },
- },
+ }
+ }
+ }
};
```
@@ -1594,12 +1740,12 @@ function ok(expr, msg) {
suite('Array');
-test('#length', function () {
+test('#length', function() {
var arr = [1, 2, 3];
ok(arr.length == 3);
});
-test('#indexOf()', function () {
+test('#indexOf()', function() {
var arr = [1, 2, 3];
ok(arr.indexOf(1) == 0);
ok(arr.indexOf(2) == 1);
@@ -1608,7 +1754,7 @@ test('#indexOf()', function () {
suite('String');
-test('#length', function () {
+test('#length', function() {
ok('foo'.length == 3);
});
```
@@ -1625,13 +1771,13 @@ var pre = require('mocha').before;
var assertions = require('mocha').it;
var assert = require('chai').assert;
-testCase('Array', function () {
- pre(function () {
+testCase('Array', function() {
+ pre(function() {
// ...
});
- testCase('#indexOf()', function () {
- assertions('should return -1 when not present', function () {
+ testCase('#indexOf()', function() {
+ assertions('should return -1 when not present', function() {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
@@ -1735,9 +1881,9 @@ The Doc reporter outputs a hierarchical HTML body representation of your tests.
For example, suppose you have the following JavaScript:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it('should return -1 when the value is not present', function () {
+describe('Array', function() {
+ describe('#indexOf()', function() {
+ it('should return -1 when the value is not present', function() {
[1, 2, 3].indexOf(5).should.equal(-1);
[1, 2, 3].indexOf(0).should.equal(-1);
});
@@ -1893,7 +2039,7 @@ mocha.setup('tdd');
// This is equivalent to the above.
mocha.setup({
- ui: 'tdd',
+ ui: 'tdd'
});
// Examples of options:
@@ -1908,7 +2054,7 @@ mocha.setup({
retries: 3,
slow: '100',
timeout: '2000',
- ui: 'bdd',
+ ui: 'bdd'
});
```
@@ -2241,3 +2387,7 @@ or the [source](https://github.com/mochajs/mocha/blob/master/lib/mocha.js).
[wallaby.js]: https://wallabyjs.com/
[yargs-configobject-extends]: http://yargs.js.org/docs/#api-configobject-extends-keyword
[zsh-globbing]: http://zsh.sourceforge.net/Doc/Release/Expansion.html#Recursive-Globbing
+[root hook plugins]: #root-hook-plugins
+[global setup fixtures]: #global-setup-fixtures
+[global teardown fixtures]: #global-teardown-fixtures
+[global fixtures]: #global-fixtures
diff --git a/lib/cli/run-helpers.js b/lib/cli/run-helpers.js
index 017d914f..6856a5a7 100644
--- a/lib/cli/run-helpers.js
+++ b/lib/cli/run-helpers.js
@@ -12,10 +12,10 @@ const path = require('path');
const debug = require('debug')('mocha:cli:run:helpers');
const {watchRun, watchParallelRun} = require('./watch-run');
const collectFiles = require('./collect-files');
-const {type} = require('../utils');
const {format} = require('util');
-const {createInvalidPluginError, createUnsupportedError} = require('../errors');
+const {createInvalidLegacyPluginError} = require('../errors');
const {requireOrImport} = require('../esm-utils');
+const PluginLoader = require('../plugin-loader');
/**
* Exits Mocha when tests + code under test has finished execution (default)
@@ -79,12 +79,12 @@ exports.list = str =>
*
* Returns array of `mochaHooks` exports, if any.
* @param {string[]} requires - Modules to require
- * @returns {Promise<MochaRootHookObject|MochaRootHookFunction>} Any root hooks
+ * @returns {Promise<object>} Plugin implementations
* @private
*/
-exports.handleRequires = async (requires = []) => {
- const acc = [];
- for (const mod of requires) {
+exports.handleRequires = async (requires = [], {ignoredPlugins = []} = {}) => {
+ const pluginLoader = PluginLoader.create({ignore: ignoredPlugins});
+ for await (const mod of requires) {
let modpath = mod;
// this is relative to cwd
if (fs.existsSync(mod) || fs.existsSync(`${mod}.js`)) {
@@ -92,49 +92,18 @@ exports.handleRequires = async (requires = []) => {
debug('resolved required file %s to %s', mod, modpath);
}
const requiredModule = await requireOrImport(modpath);
- if (
- requiredModule &&
- typeof requiredModule === 'object' &&
- requiredModule.mochaHooks
- ) {
- const mochaHooksType = type(requiredModule.mochaHooks);
- if (/function$/.test(mochaHooksType) || mochaHooksType === 'object') {
- debug('found root hooks in required file %s', mod);
- acc.push(requiredModule.mochaHooks);
- } else {
- throw createUnsupportedError(
- 'mochaHooks must be an object or a function returning (or fulfilling with) an object'
- );
+ if (requiredModule && typeof requiredModule === 'object') {
+ if (pluginLoader.load(requiredModule)) {
+ debug('found one or more plugin implementations in %s', modpath);
}
}
debug('loaded required module "%s"', mod);
}
- return acc;
-};
-
-/**
- * Loads root hooks as exported via `mochaHooks` from required files.
- * These can be sync/async functions returning objects, or just objects.
- * Flattens to a single object.
- * @param {Array<MochaRootHookObject|MochaRootHookFunction>} rootHooks - Array of root hooks
- * @private
- * @returns {MochaRootHookObject}
- */
-exports.loadRootHooks = async rootHooks => {
- const rootHookObjects = await Promise.all(
- rootHooks.map(async hook => (/function$/.test(type(hook)) ? hook() : hook))
- );
-
- return rootHookObjects.reduce(
- (acc, hook) => {
- acc.beforeAll = acc.beforeAll.concat(hook.beforeAll || []);
- acc.beforeEach = acc.beforeEach.concat(hook.beforeEach || []);
- acc.afterAll = acc.afterAll.concat(hook.afterAll || []);
- acc.afterEach = acc.afterEach.concat(hook.afterEach || []);
- return acc;
- },
- {beforeAll: [], beforeEach: [], afterAll: [], afterEach: []}
- );
+ const plugins = await pluginLoader.finalize();
+ if (Object.keys(plugins).length) {
+ debug('finalized plugin implementations: %O', plugins);
+ }
+ return plugins;
};
/**
@@ -236,7 +205,7 @@ exports.runMocha = async (mocha, options) => {
* name
* @private
*/
-exports.validatePlugin = (opts, pluginType, map = {}) => {
+exports.validateLegacyPlugin = (opts, pluginType, map = {}) => {
/**
* This should be a unique identifier; either a string (present in `map`),
* or a resolvable (via `require.resolve`) module ID/path.
@@ -245,14 +214,14 @@ exports.validatePlugin = (opts, pluginType, map = {}) => {
const pluginId = opts[pluginType];
if (Array.isArray(pluginId)) {
- throw createInvalidPluginError(
+ throw createInvalidLegacyPluginError(
`"--${pluginType}" can only be specified once`,
pluginType
);
}
- const unknownError = err =>
- createInvalidPluginError(
+ const createUnknownError = err =>
+ createInvalidLegacyPluginError(
format('Could not load %s "%s":\n\n %O', pluginType, pluginId, err),
pluginType,
pluginId
@@ -268,10 +237,10 @@ exports.validatePlugin = (opts, pluginType, map = {}) => {
try {
opts[pluginType] = require(path.resolve(pluginId));
} catch (err) {
- throw unknownError(err);
+ throw createUnknownError(err);
}
} else {
- throw unknownError(err);
+ throw createUnknownError(err);
}
}
}
diff --git a/lib/cli/run.js b/lib/cli/run.js
index 6582a4e2..a8c8b619 100644
--- a/lib/cli/run.js
+++ b/lib/cli/run.js
@@ -19,8 +19,7 @@ const {
const {
list,
handleRequires,
- validatePlugin,
- loadRootHooks,
+ validateLegacyPlugin,
runMocha
} = require('./run-helpers');
const {ONE_AND_DONES, ONE_AND_DONE_ARGS} = require('./one-and-dones');
@@ -339,13 +338,10 @@ exports.builder = yargs =>
// currently a failing middleware does not work nicely with yargs' `fail()`.
try {
// load requires first, because it can impact "plugin" validation
- const rawRootHooks = await handleRequires(argv.require);
- validatePlugin(argv, 'reporter', Mocha.reporters);
- validatePlugin(argv, 'ui', Mocha.interfaces);
-
- if (rawRootHooks && rawRootHooks.length) {
- argv.rootHooks = await loadRootHooks(rawRootHooks);
- }
+ const plugins = await handleRequires(argv.require);
+ validateLegacyPlugin(argv, 'reporter', Mocha.reporters);
+ validateLegacyPlugin(argv, 'ui', Mocha.interfaces);
+ Object.assign(argv, plugins);
} catch (err) {
// this could be a bad --require, bad reporter, ui, etc.
console.error(`\n${symbols.error} ${ansi.red('ERROR:')}`, err);
diff --git a/lib/cli/watch-run.js b/lib/cli/watch-run.js
index d36a5839..3bac5503 100644
--- a/lib/cli/watch-run.js
+++ b/lib/cli/watch-run.js
@@ -1,5 +1,6 @@
'use strict';
+const logSymbols = require('log-symbols');
const debug = require('debug')('mocha:cli:watch');
const path = require('path');
const chokidar = require('chokidar');
@@ -32,6 +33,7 @@ exports.watchParallelRun = (
fileCollectParams
) => {
debug('creating parallel watcher');
+
return createWatcher(mocha, {
watchFiles,
watchIgnore,
@@ -68,9 +70,6 @@ exports.watchParallelRun = (
newMocha.lazyLoadFiles(true);
return newMocha;
},
- afterRun({watcher}) {
- blastCache(watcher);
- },
fileCollectParams
});
};
@@ -91,7 +90,6 @@ exports.watchParallelRun = (
*/
exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
debug('creating serial watcher');
- // list of all test files
return createWatcher(mocha, {
watchFiles,
@@ -128,9 +126,6 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
return newMocha;
},
- afterRun({watcher}) {
- blastCache(watcher);
- },
fileCollectParams
});
};
@@ -141,7 +136,6 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
* @param {Object} opts
* @param {BeforeWatchRun} [opts.beforeRun] - Function to call before
* `mocha.run()`
- * @param {AfterWatchRun} [opts.afterRun] - Function to call after `mocha.run()`
* @param {string[]} [opts.watchFiles] - List of paths and patterns to watch. If
* not provided all files with an extension included in
* `fileCollectionParams.extension` are watched. See first argument of
@@ -155,13 +149,17 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
*/
const createWatcher = (
mocha,
- {watchFiles, watchIgnore, beforeRun, afterRun, fileCollectParams}
+ {watchFiles, watchIgnore, beforeRun, fileCollectParams}
) => {
if (!watchFiles) {
watchFiles = fileCollectParams.extension.map(ext => `**/*.${ext}`);
}
debug('ignoring files matching: %s', watchIgnore);
+ let globalFixtureContext;
+
+ // we handle global fixtures manually
+ mocha.enableGlobalSetup(false).enableGlobalTeardown(false);
const watcher = chokidar.watch(watchFiles, {
ignored: watchIgnore,
@@ -169,11 +167,14 @@ const createWatcher = (
});
const rerunner = createRerunner(mocha, watcher, {
- beforeRun,
- afterRun
+ beforeRun
});
- watcher.on('ready', () => {
+ watcher.on('ready', async () => {
+ if (!globalFixtureContext) {
+ debug('triggering global setup');
+ globalFixtureContext = await mocha.runGlobalSetup();
+ }
rerunner.run();
});
@@ -185,10 +186,39 @@ const createWatcher = (
process.on('exit', () => {
showCursor();
});
- process.on('SIGINT', () => {
+
+ // this is for testing.
+ // win32 cannot gracefully shutdown via a signal from a parent
+ // process; a `SIGINT` from a parent will cause the process
+ // to immediately exit. during normal course of operation, a user
+ // will type Ctrl-C and the listener will be invoked, but this
+ // is not possible in automated testing.
+ // there may be another way to solve this, but it too will be a hack.
+ // for our watch tests on win32 we must _fork_ mocha with an IPC channel
+ if (process.connected) {
+ process.on('message', msg => {
+ if (msg === 'SIGINT') {
+ process.emit('SIGINT');
+ }
+ });
+ }
+
+ let exiting = false;
+ process.on('SIGINT', async () => {
showCursor();
- console.log('\n');
- process.exit(128 + 2);
+ console.error(`${logSymbols.warning} [mocha] cleaning up, please wait...`);
+ if (!exiting) {
+ exiting = true;
+ if (mocha.hasGlobalTeardownFixtures()) {
+ debug('running global teardown');
+ try {
+ await mocha.runGlobalTeardown(globalFixtureContext);
+ } catch (err) {
+ console.error(err);
+ }
+ }
+ process.exit(130);
+ }
});
// Keyboard shortcut for restarting when "rs\n" is typed (ala Nodemon)
@@ -212,12 +242,11 @@ const createWatcher = (
* @param {FSWatcher} watcher - chokidar `FSWatcher` instance
* @param {Object} [opts] - Options!
* @param {BeforeWatchRun} [opts.beforeRun] - Function to call before `mocha.run()`
- * @param {AfterWatchRun} [opts.afterRun] - Function to call after `mocha.run()`
* @returns {Rerunner}
* @ignore
* @private
*/
-const createRerunner = (mocha, watcher, {beforeRun, afterRun} = {}) => {
+const createRerunner = (mocha, watcher, {beforeRun} = {}) => {
// Set to a `Runner` when mocha is running. Set to `null` when mocha is not
// running.
let runner = null;
@@ -226,16 +255,15 @@ const createRerunner = (mocha, watcher, {beforeRun, afterRun} = {}) => {
let rerunScheduled = false;
const run = () => {
- mocha = beforeRun ? beforeRun({mocha, watcher}) : mocha;
-
+ mocha = beforeRun ? beforeRun({mocha, watcher}) || mocha : mocha;
runner = mocha.run(() => {
debug('finished watch run');
runner = null;
- afterRun && afterRun({mocha, watcher});
+ blastCache(watcher);
if (rerunScheduled) {
rerun();
} else {
- debug('waiting for changes...');
+ console.error(`${logSymbols.info} [mocha] waiting for changes...`);
}
});
};
@@ -333,15 +361,6 @@ const blastCache = watcher => {
* @returns {Mocha}
*/
-/**
- * Callback to be run after `mocha.run()` completes. Typically used to clear
- * require cache.
- * @callback AfterWatchRun
- * @private
- * @param {{mocha: Mocha, watcher: FSWatcher}} options
- * @returns {void}
- */
-
/**
* Object containing run control methods
* @typedef {Object} Rerunner
diff --git a/lib/errors.js b/lib/errors.js
index 56e01c04..6f6c8e6a 100644
--- a/lib/errors.js
+++ b/lib/errors.js
@@ -1,12 +1,57 @@
'use strict';
-var format = require('util').format;
+const {format} = require('util');
/**
- * Factory functions to create throwable error objects
- * @module Errors
+ * Contains error codes, factory functions to create throwable error objects,
+ * and warning/deprecation functions.
+ * @module
*/
+/**
+ * process.emitWarning or a polyfill
+ * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options
+ * @ignore
+ */
+const emitWarning = (msg, type) => {
+ if (process.emitWarning) {
+ process.emitWarning(msg, type);
+ } else {
+ process.nextTick(function() {
+ console.warn(type + ': ' + msg);
+ });
+ }
+};
+
+/**
+ * Show a deprecation warning. Each distinct message is only displayed once.
+ * Ignores empty messages.
+ *
+ * @param {string} [msg] - Warning to print
+ * @private
+ */
+const deprecate = msg => {
+ msg = String(msg);
+ if (msg && !deprecate.cache[msg]) {
+ deprecate.cache[msg] = true;
+ emitWarning(msg, 'DeprecationWarning');
+ }
+};
+deprecate.cache = {};
+
+/**
+ * Show a generic warning.
+ * Ignores empty messages.
+ *
+ * @param {string} [msg] - Warning to print
+ * @private
+ */
+const warn = msg => {
+ if (msg) {
+ emitWarning(msg);
+ }
+};
+
/**
* When Mocha throw exceptions (or otherwise errors), it attempts to assign a
* `code` property to the `Error` object, for easier handling. These are the
@@ -71,7 +116,17 @@ var constants = {
/**
* Use of `only()` w/ `--forbid-only` results in this error.
*/
- FORBIDDEN_EXCLUSIVITY: 'ERR_MOCHA_FORBIDDEN_EXCLUSIVITY'
+ FORBIDDEN_EXCLUSIVITY: 'ERR_MOCHA_FORBIDDEN_EXCLUSIVITY',
+
+ /**
+ * To be thrown when a user-defined plugin implementation (e.g., `mochaHooks`) is invalid
+ */
+ INVALID_PLUGIN_IMPLEMENTATION: 'ERR_MOCHA_INVALID_PLUGIN_IMPLEMENTATION',
+
+ /**
+ * To be thrown when a builtin or third-party plugin definition (the _definition_ of `mochaHooks`) is invalid
+ */
+ INVALID_PLUGIN_DEFINITION: 'ERR_MOCHA_INVALID_PLUGIN_DEFINITION'
};
/**
@@ -221,7 +276,7 @@ function createFatalError(message, value) {
* @public
* @returns {Error}
*/
-function createInvalidPluginError(message, pluginType, pluginId) {
+function createInvalidLegacyPluginError(message, pluginType, pluginId) {
switch (pluginType) {
case 'reporter':
return createInvalidReporterError(message, pluginId);
@@ -232,6 +287,21 @@ function createInvalidPluginError(message, pluginType, pluginId) {
}
}
+/**
+ * **DEPRECATED**. Use {@link createInvalidLegacyPluginError} instead Dynamically creates a plugin-type-specific error based on plugin type
+ * @deprecated
+ * @param {string} message - Error message
+ * @param {"reporter"|"interface"} pluginType - Plugin type. Future: expand as needed
+ * @param {string} [pluginId] - Name/path of plugin, if any
+ * @throws When `pluginType` is not known
+ * @public
+ * @returns {Error}
+ */
+function createInvalidPluginError(...args) {
+ deprecate('Use createInvalidLegacyPluginError() instead');
+ return createInvalidLegacyPluginError(...args);
+}
+
/**
* Creates an error object to be thrown when a mocha object's `run` method is executed while it is already disposed.
* @param {string} message The error message to be displayed.
@@ -315,20 +385,59 @@ function createForbiddenExclusivityError(mocha) {
return err;
}
+/**
+ * Creates an error object to be thrown when a plugin definition is invalid
+ * @param {string} msg - Error message
+ * @param {PluginDefinition} [pluginDef] - Problematic plugin definition
+ * @public
+ * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}
+ */
+function createInvalidPluginDefinitionError(msg, pluginDef) {
+ const err = new Error(msg);
+ err.code = constants.INVALID_PLUGIN_DEFINITION;
+ err.pluginDef = pluginDef;
+ return err;
+}
+
+/**
+ * Creates an error object to be thrown when a plugin implementation (user code) is invalid
+ * @param {string} msg - Error message
+ * @param {Object} [opts] - Plugin definition and user-supplied implementation
+ * @param {PluginDefinition} [opts.pluginDef] - Plugin Definition
+ * @param {*} [opts.pluginImpl] - Plugin Implementation (user-supplied)
+ * @public
+ * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}
+ */
+function createInvalidPluginImplementationError(
+ msg,
+ {pluginDef, pluginImpl} = {}
+) {
+ const err = new Error(msg);
+ err.code = constants.INVALID_PLUGIN_IMPLEMENTATION;
+ err.pluginDef = pluginDef;
+ err.pluginImpl = pluginImpl;
+ return err;
+}
+
module.exports = {
- createInvalidArgumentTypeError: createInvalidArgumentTypeError,
- createInvalidArgumentValueError: createInvalidArgumentValueError,
- createInvalidExceptionError: createInvalidExceptionError,
- createInvalidInterfaceError: createInvalidInterfaceError,
- createInvalidReporterError: createInvalidReporterError,
- createMissingArgumentError: createMissingArgumentError,
- createNoFilesMatchPatternError: createNoFilesMatchPatternError,
- createUnsupportedError: createUnsupportedError,
- createInvalidPluginError: createInvalidPluginError,
- createMochaInstanceAlreadyDisposedError: createMochaInstanceAlreadyDisposedError,
- createMochaInstanceAlreadyRunningError: createMochaInstanceAlreadyRunningError,
- createFatalError: createFatalError,
- createMultipleDoneError: createMultipleDoneError,
- createForbiddenExclusivityError: createForbiddenExclusivityError,
- constants: constants
+ constants,
+ createFatalError,
+ createForbiddenExclusivityError,
+ createInvalidArgumentTypeError,
+ createInvalidArgumentValueError,
+ createInvalidExceptionError,
+ createInvalidInterfaceError,
+ createInvalidLegacyPluginError,
+ createInvalidPluginDefinitionError,
+ createInvalidPluginError,
+ createInvalidPluginImplementationError,
+ createInvalidReporterError,
+ createMissingArgumentError,
+ createMochaInstanceAlreadyDisposedError,
+ createMochaInstanceAlreadyRunningError,
+ createMultipleDoneError,
+ createNoFilesMatchPatternError,
+ createUnsupportedError,
+ deprecate,
+ warn
};
diff --git a/lib/mocha.js b/lib/mocha.js
index 350df62d..611c33a9 100644
--- a/lib/mocha.js
+++ b/lib/mocha.js
@@ -18,15 +18,18 @@ var esmUtils = utils.supportsEsModules(true)
: undefined;
var createStatsCollector = require('./stats-collector');
const {
- createUnsupportedError,
- createInvalidInterfaceError,
+ warn,
createInvalidReporterError,
+ createInvalidInterfaceError,
createMochaInstanceAlreadyDisposedError,
- createMochaInstanceAlreadyRunningError
+ createMochaInstanceAlreadyRunningError,
+ createUnsupportedError
} = require('./errors');
-var EVENT_FILE_PRE_REQUIRE = Suite.constants.EVENT_FILE_PRE_REQUIRE;
-var EVENT_FILE_POST_REQUIRE = Suite.constants.EVENT_FILE_POST_REQUIRE;
-var EVENT_FILE_REQUIRE = Suite.constants.EVENT_FILE_REQUIRE;
+const {
+ EVENT_FILE_PRE_REQUIRE,
+ EVENT_FILE_POST_REQUIRE,
+ EVENT_FILE_REQUIRE
+} = Suite.constants;
var sQuote = utils.sQuote;
var debug = require('debug')('mocha:mocha');
@@ -128,8 +131,8 @@ exports.Test = require('./test');
* suite with
* @param {boolean} [options.isWorker] - Should be `true` if `Mocha` process is running in a worker process.
*/
-function Mocha(options) {
- options = utils.assign({}, mocharc, options || {});
+function Mocha(options = {}) {
+ options = {...mocharc, ...options};
this.files = [];
this.options = options;
// root suite
@@ -205,6 +208,11 @@ function Mocha(options) {
*/
this.isWorker = Boolean(options.isWorker);
+ this.globalSetup(options.globalSetup)
+ .globalTeardown(options.globalTeardown)
+ .enableGlobalSetup(options.enableGlobalSetup)
+ .enableGlobalTeardown(options.enableGlobalTeardown);
+
if (
options.parallel &&
(typeof options.jobs === 'undefined' || options.jobs > 1)
@@ -277,25 +285,21 @@ Mocha.prototype.reporter = function(reporterName, reporterOptions) {
try {
reporter = require(reporterName);
} catch (err) {
- if (
- err.code === 'MODULE_NOT_FOUND' ||
- err.message.indexOf('Cannot find module') >= 0
- ) {
+ if (err.code === 'MODULE_NOT_FOUND') {
// Try to load reporters from a path (absolute or relative)
try {
reporter = require(path.resolve(utils.cwd(), reporterName));
} catch (_err) {
- _err.code === 'MODULE_NOT_FOUND' ||
- _err.message.indexOf('Cannot find module') >= 0
- ? utils.warn(sQuote(reporterName) + ' reporter not found')
- : utils.warn(
+ _err.code === 'MODULE_NOT_FOUND'
+ ? warn(sQuote(reporterName) + ' reporter not found')
+ : warn(
sQuote(reporterName) +
' reporter blew up with error:\n' +
err.stack
);
}
} else {
- utils.warn(
+ warn(
sQuote(reporterName) + ' reporter blew up with error:\n' + err.stack
);
}
@@ -965,11 +969,10 @@ Mocha.prototype.run = function(fn) {
if (this.files.length && !this._lazyLoadFiles) {
this.loadFiles();
}
- var self = this;
var suite = this.suite;
var options = this.options;
options.files = this.files;
- var runner = new this._runnerClass(suite, {
+ const runner = new this._runnerClass(suite, {
delay: options.delay,
cleanReferencesAfterRun: this._cleanReferencesAfterRun
});
@@ -996,22 +999,42 @@ Mocha.prototype.run = function(fn) {
exports.reporters.Base.inlineDiffs = options.inlineDiffs;
exports.reporters.Base.hideDiff = !options.diff;
- function done(failures) {
- self._previousRunner = runner;
- if (self._cleanReferencesAfterRun) {
- self._state = mochaStates.REFERENCES_CLEANED;
- } else {
- self._state = mochaStates.INIT;
- }
+ const done = failures => {
+ this._previousRunner = runner;
+ this._state = this._cleanReferencesAfterRun
+ ? mochaStates.REFERENCES_CLEANED
+ : mochaStates.INIT;
fn = fn || utils.noop;
- if (reporter.done) {
+ if (typeof reporter.done === 'function') {
reporter.done(failures, fn);
} else {
fn(failures);
}
- }
+ };
+
+ const runAsync = async runner => {
+ const context =
+ this.options.enableGlobalSetup && this.hasGlobalSetupFixtures()
+ ? await this.runGlobalSetup(runner)
+ : {};
+ const failureCount = await runner.runAsync({
+ files: this.files,
+ options
+ });
+ if (this.options.enableGlobalTeardown && this.hasGlobalTeardownFixtures()) {
+ await this.runGlobalTeardown(runner, {context});
+ }
+ return failureCount;
+ };
- return runner.run(done, {files: this.files, options: options});
+ // no "catch" here is intentional. errors coming out of
+ // Runner#run are considered uncaught/unhandled and caught
+ // by the `process` event listeners.
+ // also: returning anything other than `runner` would be a breaking
+ // change
+ runAsync(runner).then(done);
+
+ return runner;
};
/**
@@ -1019,26 +1042,28 @@ Mocha.prototype.run = function(fn) {
* @param {MochaRootHookObject} [hooks] - Hooks to assign to root suite
* @chainable
*/
-Mocha.prototype.rootHooks = function rootHooks(hooks) {
- if (utils.type(hooks) === 'object') {
- var beforeAll = [].concat(hooks.beforeAll || []);
- var beforeEach = [].concat(hooks.beforeEach || []);
- var afterAll = [].concat(hooks.afterAll || []);
- var afterEach = [].concat(hooks.afterEach || []);
- var rootSuite = this.suite;
- beforeAll.forEach(function(hook) {
- rootSuite.beforeAll(hook);
- });
- beforeEach.forEach(function(hook) {
- rootSuite.beforeEach(hook);
- });
- afterAll.forEach(function(hook) {
- rootSuite.afterAll(hook);
- });
- afterEach.forEach(function(hook) {
- rootSuite.afterEach(hook);
- });
- }
+Mocha.prototype.rootHooks = function rootHooks({
+ beforeAll = [],
+ beforeEach = [],
+ afterAll = [],
+ afterEach = []
+} = {}) {
+ beforeAll = utils.castArray(beforeAll);
+ beforeEach = utils.castArray(beforeEach);
+ afterAll = utils.castArray(afterAll);
+ afterEach = utils.castArray(afterEach);
+ beforeAll.forEach(hook => {
+ this.suite.beforeAll(hook);
+ });
+ beforeEach.forEach(hook => {
+ this.suite.beforeEach(hook);
+ });
+ afterAll.forEach(hook => {
+ this.suite.afterAll(hook);
+ });
+ afterEach.forEach(hook => {
+ this.suite.afterEach(hook);
+ });
return this;
};
@@ -1047,18 +1072,21 @@ Mocha.prototype.rootHooks = function rootHooks(hooks) {
*
* Must be run before calling {@link Mocha#run}. Changes the `Runner` class to
* use; also enables lazy file loading if not already done so.
+ *
+ * Warning: when passed `false` and lazy loading has been enabled _via any means_ (including calling `parallelMode(true)`), this method will _not_ disable lazy loading. Lazy loading is a prerequisite for parallel
+ * mode, but parallel mode is _not_ a prerequisite for lazy loading!
* @param {boolean} [enable] - If `true`, enable; otherwise disable.
* @throws If run in browser
- * @throws If Mocha not in "INIT" state
+ * @throws If Mocha not in `INIT` state
* @returns {Mocha}
* @chainable
* @public
*/
-Mocha.prototype.parallelMode = function parallelMode(enable) {
+Mocha.prototype.parallelMode = function parallelMode(enable = true) {
if (utils.isBrowser()) {
throw createUnsupportedError('parallel mode is only supported in Node.js');
}
- var parallel = enable === true;
+ const parallel = Boolean(enable);
if (
parallel === this.options.parallel &&
this._lazyLoadFiles &&
@@ -1100,8 +1128,144 @@ Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {
};
/**
- * An alternative way to define root hooks that works with parallel runs.
+ * Configures one or more global setup fixtures.
+ *
+ * If given no parameters, _unsets_ any previously-set fixtures.
+ * @chainable
+ * @public
+ * @param {MochaGlobalFixture|MochaGlobalFixture[]} [setupFns] - Global setup fixture(s)
+ * @returns {Mocha}
+ */
+Mocha.prototype.globalSetup = function globalSetup(setupFns = []) {
+ setupFns = utils.castArray(setupFns);
+ this.options.globalSetup = setupFns;
+ debug('configured %d global setup functions', setupFns.length);
+ return this;
+};
+
+/**
+ * Configures one or more global teardown fixtures.
+ *
+ * If given no parameters, _unsets_ any previously-set fixtures.
+ * @chainable
+ * @public
+ * @param {MochaGlobalFixture|MochaGlobalFixture[]} [teardownFns] - Global teardown fixture(s)
+ * @returns {Mocha}
+ */
+Mocha.prototype.globalTeardown = function globalTeardown(teardownFns = []) {
+ teardownFns = utils.castArray(teardownFns);
+ this.options.globalTeardown = teardownFns;
+ debug('configured %d global teardown functions', teardownFns.length);
+ return this;
+};
+
+/**
+ * Run any global setup fixtures sequentially, if any.
+ *
+ * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalSetup` option is `false`; see {@link Mocha#enableGlobalSetup}.
+ *
+ * The context object this function resolves with should be consumed by {@link Mocha#runGlobalTeardown}.
+ * @param {object} [context] - Context object if already have one
+ * @public
+ * @returns {Promise<object>} Context object
+ */
+Mocha.prototype.runGlobalSetup = async function runGlobalSetup(context = {}) {
+ const {globalSetup} = this.options;
+ if (globalSetup && globalSetup.length) {
+ debug('run(): global setup starting');
+ await this._runGlobalFixtures(globalSetup, context);
+ debug('run(): global setup complete');
+ }
+ return context;
+};
+
+/**
+ * Run any global teardown fixtures sequentially, if any.
+ *
+ * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalTeardown` option is `false`; see {@link Mocha#enableGlobalTeardown}.
+ *
+ * Should be called with context object returned by {@link Mocha#runGlobalSetup}, if applicable.
+ * @param {object} [context] - Context object if already have one
+ * @public
+ * @returns {Promise<object>} Context object
+ */
+Mocha.prototype.runGlobalTeardown = async function runGlobalTeardown(
+ context = {}
+) {
+ const {globalTeardown} = this.options;
+ if (globalTeardown && globalTeardown.length) {
+ debug('run(): global teardown starting');
+ await this._runGlobalFixtures(globalTeardown, context);
+ }
+ debug('run(): global teardown complete');
+ return context;
+};
+
+/**
+ * Run global fixtures sequentially with context `context`
* @private
+ * @param {MochaGlobalFixture[]} [fixtureFns] - Fixtures to run
+ * @param {object} [context] - context object
+ * @returns {Promise<object>} context object
+ */
+Mocha.prototype._runGlobalFixtures = async function _runGlobalFixtures(
+ fixtureFns = [],
+ context = {}
+) {
+ for await (const fixtureFn of fixtureFns) {
+ await fixtureFn.call(context);
+ }
+ return context;
+};
+
+/**
+ * Toggle execution of any global setup fixture(s)
+ *
+ * @chainable
+ * @public
+ * @param {boolean } [enabled=true] - If `false`, do not run global setup fixture
+ * @returns {Mocha}
+ */
+Mocha.prototype.enableGlobalSetup = function enableGlobalSetup(enabled = true) {
+ this.options.enableGlobalSetup = Boolean(enabled);
+ return this;
+};
+
+/**
+ * Toggle execution of any global teardown fixture(s)
+ *
+ * @chainable
+ * @public
+ * @param {boolean } [enabled=true] - If `false`, do not run global teardown fixture
+ * @returns {Mocha}
+ */
+Mocha.prototype.enableGlobalTeardown = function enableGlobalTeardown(
+ enabled = true
+) {
+ this.options.enableGlobalTeardown = Boolean(enabled);
+ return this;
+};
+
+/**
+ * Returns `true` if one or more global setup fixtures have been supplied.
+ * @public
+ * @returns {boolean}
+ */
+Mocha.prototype.hasGlobalSetupFixtures = function hasGlobalSetupFixtures() {
+ return Boolean(this.options.globalSetup.length);
+};
+
+/**
+ * Returns `true` if one or more global teardown fixtures have been supplied.
+ * @public
+ * @returns {boolean}
+ */
+Mocha.prototype.hasGlobalTeardownFixtures = function hasGlobalTeardownFixtures() {
+ return Boolean(this.options.globalTeardown.length);
+};
+
+/**
+ * An alternative way to define root hooks that works with parallel runs.
* @typedef {Object} MochaRootHookObject
* @property {Function|Function[]} [beforeAll] - "Before all" hook(s)
* @property {Function|Function[]} [beforeEach] - "Before each" hook(s)
@@ -1111,7 +1275,40 @@ Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {
/**
* An function that returns a {@link MochaRootHookObject}, either sync or async.
- * @private
- * @callback MochaRootHookFunction
+ @callback MochaRootHookFunction
* @returns {MochaRootHookObject|Promise<MochaRootHookObject>}
*/
+
+/**
+ * A function that's invoked _once_ which is either sync or async.
+ * Can be a "teardown" or "setup". These will all share the same context.
+ * @callback MochaGlobalFixture
+ * @returns {void|Promise<void>}
+ */
+
+/**
+ * An object making up all necessary parts of a plugin loader and aggregator
+ * @typedef {Object} PluginDefinition
+ * @property {string} exportName - Named export to use
+ * @property {string} [optionName] - Option name for Mocha constructor (use `exportName` if omitted)
+ * @property {PluginValidator} [validate] - Validator function
+ * @property {PluginFinalizer} [finalize] - Finalizer/aggregator function
+ */
+
+/**
+ * A (sync) function to assert a user-supplied plugin implementation is valid.
+ *
+ * Defined in a {@link PluginDefinition}.
+
+ * @callback PluginValidator
+ * @param {*} value - Value to check
+ * @this {PluginDefinition}
+ * @returns {void}
+ */
+
+/**
+ * A function to finalize plugins impls of a particular ilk
+ * @callback PluginFinalizer
+ * @param {Array<*>} impls - User-supplied implementations
+ * @returns {Promise<*>|*}
+ */
diff --git a/lib/nodejs/parallel-buffered-runner.js b/lib/nodejs/parallel-buffered-runner.js
index ee8635ab..a079bbd5 100644
--- a/lib/nodejs/parallel-buffered-runner.js
+++ b/lib/nodejs/parallel-buffered-runner.js
@@ -14,6 +14,18 @@ const {BufferedWorkerPool} = require('./buffered-worker-pool');
const {setInterval, clearInterval} = global;
const {createMap} = require('../utils');
+/**
+ * List of options to _not_ serialize for transmission to workers
+ */
+const DENY_OPTIONS = [
+ 'globalSetup',
+ 'globalTeardown',
+ 'parallel',
+ 'p',
+ 'jobs',
+ 'j'
+];
+
/**
* Outputs a debug statement with worker stats
* @param {BufferedWorkerPool} pool - Worker pool
@@ -235,6 +247,11 @@ class ParallelBufferedRunner extends Runner {
this.emit(EVENT_RUN_BEGIN);
+ options = {...options};
+ DENY_OPTIONS.forEach(opt => {
+ delete options[opt];
+ });
+
const results = await allSettled(
files.map(this._createFileRunner(pool, options))
);
@@ -257,6 +274,7 @@ class ParallelBufferedRunner extends Runner {
if (this._state === ABORTING) {
return;
}
+
this.emit(EVENT_RUN_END);
debug('run(): completing with failure count %d', this.failures);
callback(this.failures);
diff --git a/lib/nodejs/worker.js b/lib/nodejs/worker.js
index 81abb6bb..2f002fa0 100644
--- a/lib/nodejs/worker.js
+++ b/lib/nodejs/worker.js
@@ -12,11 +12,7 @@ const {
} = require('../errors');
const workerpool = require('workerpool');
const Mocha = require('../mocha');
-const {
- handleRequires,
- validatePlugin,
- loadRootHooks
-} = require('../cli/run-helpers');
+const {handleRequires, validateLegacyPlugin} = require('../cli/run-helpers');
const d = require('debug');
const debug = d.debug(`mocha:parallel:worker:${process.pid}`);
const isDebugEnabled = d.enabled(`mocha:parallel:worker:${process.pid}`);
@@ -45,9 +41,13 @@ if (workerpool.isMainThread) {
* @param {Options} argv - Command-line options
*/
let bootstrap = async argv => {
- const rawRootHooks = await handleRequires(argv.require);
- rootHooks = await loadRootHooks(rawRootHooks);
- validatePlugin(argv, 'ui', Mocha.interfaces);
+ // globalSetup and globalTeardown do not run in workers
+ const plugins = await handleRequires(argv.require, {
+ ignoredPlugins: ['mochaGlobalSetup', 'mochaGlobalTeardown']
+ });
+ validateLegacyPlugin(argv, 'ui', Mocha.interfaces);
+
+ rootHooks = plugins.rootHooks;
bootstrap = () => {};
debug('bootstrap(): finished with args: %O', argv);
};
@@ -125,6 +125,7 @@ async function run(filepath, serializedOptions = '{}') {
mocha.run(result => {
// Runner adds these; if we don't remove them, we'll get a leak.
process.removeAllListeners('uncaughtException');
+ process.removeAllListeners('unhandledRejection');
try {
const serialized = serialize(result);
diff --git a/lib/plugin-loader.js b/lib/plugin-loader.js
new file mode 100644
index 00000000..075ad91b
--- /dev/null
+++ b/lib/plugin-loader.js
@@ -0,0 +1,286 @@
+/**
+ * Provides a way to load "plugins" as provided by the user.
+ *
+ * Currently supports:
+ *
+ * - Root hooks
+ * - Global fixtures (setup/teardown)
+ * @private
+ * @module plugin
+ */
+
+'use strict';
+
+const debug = require('debug')('mocha:plugin-loader');
+const {
+ createInvalidPluginDefinitionError,
+ createInvalidPluginImplementationError
+} = require('./errors');
+const {castArray} = require('./utils');
+
+/**
+ * Built-in plugin definitions.
+ */
+const MochaPlugins = [
+ /**
+ * Root hook plugin definition
+ * @type {PluginDefinition}
+ */
+ {
+ exportName: 'mochaHooks',
+ optionName: 'rootHooks',
+ validate(value) {
+ if (
+ Array.isArray(value) ||
+ (typeof value !== 'function' && typeof value !== 'object')
+ ) {
+ throw createInvalidPluginImplementationError(
+ `mochaHooks must be an object or a function returning (or fulfilling with) an object`
+ );
+ }
+ },
+ async finalize(rootHooks) {
+ if (rootHooks.length) {
+ const rootHookObjects = await Promise.all(
+ rootHooks.map(async hook =>
+ typeof hook === 'function' ? hook() : hook
+ )
+ );
+
+ return rootHookObjects.reduce(
+ (acc, hook) => {
+ hook = {
+ beforeAll: [],
+ beforeEach: [],
+ afterAll: [],
+ afterEach: [],
+ ...hook
+ };
+ return {
+ beforeAll: [...acc.beforeAll, ...castArray(hook.beforeAll)],
+ beforeEach: [...acc.beforeEach, ...castArray(hook.beforeEach)],
+ afterAll: [...acc.afterAll, ...castArray(hook.afterAll)],
+ afterEach: [...acc.afterEach, ...castArray(hook.afterEach)]
+ };
+ },
+ {beforeAll: [], beforeEach: [], afterAll: [], afterEach: []}
+ );
+ }
+ }
+ },
+ /**
+ * Global setup fixture plugin definition
+ * @type {PluginDefinition}
+ */
+ {
+ exportName: 'mochaGlobalSetup',
+ optionName: 'globalSetup',
+ validate(value) {
+ let isValid = true;
+ if (Array.isArray(value)) {
+ if (value.some(item => typeof item !== 'function')) {
+ isValid = false;
+ }
+ } else if (typeof value !== 'function') {
+ isValid = false;
+ }
+ if (!isValid) {
+ throw createInvalidPluginImplementationError(
+ `mochaGlobalSetup must be a function or an array of functions`,
+ {pluginDef: this, pluginImpl: value}
+ );
+ }
+ }
+ },
+ /**
+ * Global teardown fixture plugin definition
+ * @type {PluginDefinition}
+ */
+ {
+ exportName: 'mochaGlobalTeardown',
+ optionName: 'globalTeardown',
+ validate(value) {
+ let isValid = true;
+ if (Array.isArray(value)) {
+ if (value.some(item => typeof item !== 'function')) {
+ isValid = false;
+ }
+ } else if (typeof value !== 'function') {
+ isValid = false;
+ }
+ if (!isValid) {
+ throw createInvalidPluginImplementationError(
+ `mochaGlobalTeardown must be a function or an array of functions`,
+ {pluginDef: this, pluginImpl: value}
+ );
+ }
+ }
+ }
+];
+
+/**
+ * Contains a registry of [plugin definitions]{@link PluginDefinition} and discovers plugin implementations in user-supplied code.
+ *
+ * - [load()]{@link #load} should be called for all required modules
+ * - The result of [finalize()]{@link #finalize} should be merged into the options for the [Mocha]{@link Mocha} constructor.
+ * @private
+ */
+class PluginLoader {
+ /**
+ * Initializes plugin names, plugin map, etc.
+ * @param {PluginLoaderOptions} [opts] - Options
+ */
+ constructor({pluginDefs = MochaPlugins, ignore = []} = {}) {
+ /**
+ * Map of registered plugin defs
+ * @type {Map<string,PluginDefinition>}
+ */
+ this.registered = new Map();
+
+ /**
+ * Cache of known `optionName` values for checking conflicts
+ * @type {Set<string>}
+ */
+ this.knownOptionNames = new Set();
+
+ /**
+ * Cache of known `exportName` values for checking conflicts
+ * @type {Set<string>}
+ */
+ this.knownExportNames = new Set();
+
+ /**
+ * Map of user-supplied plugin implementations
+ * @type {Map<string,Array<*>>}
+ */
+ this.loaded = new Map();
+
+ /**
+ * Set of ignored plugins by export name
+ * @type {Set<string>}
+ */
+ this.ignoredExportNames = new Set(castArray(ignore));
+
+ castArray(pluginDefs).forEach(pluginDef => {
+ this.register(pluginDef);
+ });
+
+ debug(
+ 'registered %d plugin defs (%d ignored)',
+ this.registered.size,
+ this.ignoredExportNames.size
+ );
+ }
+
+ /**
+ * Register a plugin
+ * @param {PluginDefinition} pluginDef - Plugin definition
+ */
+ register(pluginDef) {
+ if (!pluginDef || typeof pluginDef !== 'object') {
+ throw createInvalidPluginDefinitionError(
+ 'pluginDef is non-object or falsy',
+ pluginDef
+ );
+ }
+ if (!pluginDef.exportName) {
+ throw createInvalidPluginDefinitionError(
+ `exportName is expected to be a non-empty string`,
+ pluginDef
+ );
+ }
+ let {exportName} = pluginDef;
+ if (this.ignoredExportNames.has(exportName)) {
+ debug(
+ 'refusing to register ignored plugin with export name "%s"',
+ exportName
+ );
+ return;
+ }
+ exportName = String(exportName);
+ pluginDef.optionName = String(pluginDef.optionName || exportName);
+ if (this.knownExportNames.has(exportName)) {
+ throw createInvalidPluginDefinitionError(
+ `Plugin definition conflict: ${exportName}; exportName must be unique`,
+ pluginDef
+ );
+ }
+ this.loaded.set(exportName, []);
+ this.registered.set(exportName, pluginDef);
+ this.knownExportNames.add(exportName);
+ this.knownOptionNames.add(pluginDef.optionName);
+ debug('registered plugin def "%s"', exportName);
+ }
+
+ /**
+ * Inspects a module's exports for known plugins and keeps them in memory.
+ *
+ * @param {*} requiredModule - The exports of a module loaded via `--require`
+ * @returns {boolean} If one or more plugins was found, return `true`.
+ */
+ load(requiredModule) {
+ // we should explicitly NOT fail if other stuff is exported.
+ // we only care about the plugins we know about.
+ if (requiredModule && typeof requiredModule === 'object') {
+ return Array.from(this.knownExportNames).reduce(
+ (pluginImplFound, pluginName) => {
+ const pluginImpl = requiredModule[pluginName];
+ if (pluginImpl) {
+ const plugin = this.registered.get(pluginName);
+ if (typeof plugin.validate === 'function') {
+ plugin.validate(pluginImpl);
+ }
+ this.loaded.set(pluginName, [
+ ...this.loaded.get(pluginName),
+ ...castArray(pluginImpl)
+ ]);
+ return true;
+ }
+ return pluginImplFound;
+ },
+ false
+ );
+ }
+ return false;
+ }
+
+ /**
+ * Call the `finalize()` function of each known plugin definition on the plugins found by [load()]{@link PluginLoader#load}.
+ *
+ * Output suitable for passing as input into {@link Mocha} constructor.
+ * @returns {Promise<object>} Object having keys corresponding to registered plugin definitions' `optionName` prop (or `exportName`, if none), and the values are the implementations as provided by a user.
+ */
+ async finalize() {
+ const finalizedPlugins = Object.create(null);
+
+ for await (const [exportName, pluginImpls] of this.loaded.entries()) {
+ if (pluginImpls.length) {
+ const plugin = this.registered.get(exportName);
+ finalizedPlugins[plugin.optionName] =
+ typeof plugin.finalize === 'function'
+ ? await plugin.finalize(pluginImpls)
+ : pluginImpls;
+ }
+ }
+
+ debug('finalized plugins: %O', finalizedPlugins);
+ return finalizedPlugins;
+ }
+
+ /**
+ * Constructs a {@link PluginLoader}
+ * @param {PluginLoaderOptions} [opts] - Plugin loader options
+ */
+ static create({pluginDefs = MochaPlugins, ignore = []} = {}) {
+ return new PluginLoader({pluginDefs, ignore});
+ }
+}
+
+module.exports = PluginLoader;
+
+/**
+ * Options for {@link PluginLoader}
+ * @typedef {Object} PluginLoaderOptions
+ * @property {PluginDefinition[]} [pluginDefs] - Plugin definitions
+ * @property {string[]} [ignore] - A list of plugins to ignore when loading
+ */
diff --git a/lib/runner.js b/lib/runner.js
index 876d64fb..dde356f9 100644
--- a/lib/runner.js
+++ b/lib/runner.js
@@ -8,7 +8,6 @@ var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Pending = require('./pending');
var utils = require('./utils');
-var inherits = utils.inherits;
var debug = require('debug')('mocha:runner');
var Runnable = require('./runnable');
var Suite = require('./suite');
@@ -128,54 +127,59 @@ var constants = utils.defineConstants(
}
);
-module.exports = Runner;
-
-/**
- * Initialize a `Runner` at the Root {@link Suite}, which represents a hierarchy of {@link Suite|Suites} and {@link Test|Tests}.
- *
- * @extends external:EventEmitter
- * @public
- * @class
- * @param {Suite} suite - Root suite
- * @param {Object|boolean} [opts] - Options. If `boolean`, whether or not to delay execution of root suite until ready (for backwards compatibility).
- * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready.
- * @param {boolean} [opts.cleanReferencesAfterRun] - Whether to clean references to test fns and hooks when a suite is done.
- */
-function Runner(suite, opts) {
- if (opts === undefined) {
- opts = {};
- }
- if (typeof opts === 'boolean') {
- this._delay = opts;
- opts = {};
- } else {
- this._delay = opts.delay;
- }
- var self = this;
- this._globals = [];
- this._abort = false;
- this.suite = suite;
- this._opts = opts;
- this.state = constants.STATE_IDLE;
- this.total = suite.total();
- this.failures = 0;
- this._eventListeners = [];
- this.on(constants.EVENT_TEST_END, function(test) {
- if (test.type === 'test' && test.retriedTest() && test.parent) {
- var idx =
- test.parent.tests && test.parent.tests.indexOf(test.retriedTest());
- if (idx > -1) test.parent.tests[idx] = test;
+class Runner extends EventEmitter {
+ /**
+ * Initialize a `Runner` at the Root {@link Suite}, which represents a hierarchy of {@link Suite|Suites} and {@link Test|Tests}.
+ *
+ * @extends external:EventEmitter
+ * @public
+ * @class
+ * @param {Suite} suite - Root suite
+ * @param {Object|boolean} [opts] - Options. If `boolean`, whether or not to delay execution of root suite until ready (for backwards compatibility).
+ * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready.
+ * @param {boolean} [opts.cleanReferencesAfterRun] - Whether to clean references to test fns and hooks when a suite is done.
+ */
+ constructor(suite, opts) {
+ super();
+ if (opts === undefined) {
+ opts = {};
}
- self.checkGlobals(test);
- });
- this.on(constants.EVENT_HOOK_END, function(hook) {
- self.checkGlobals(hook);
- });
- this._defaultGrep = /.*/;
- this.grep(this._defaultGrep);
- this.globals(this.globalProps());
+ if (typeof opts === 'boolean') {
+ // TODO: deprecate this
+ this._delay = opts;
+ opts = {};
+ } else {
+ this._delay = opts.delay;
+ }
+ var self = this;
+ this._globals = [];
+ this._abort = false;
+ this.suite = suite;
+ this._opts = opts;
+ this.state = constants.STATE_IDLE;
+ this.total = suite.total();
+ this.failures = 0;
+ /**
+ * @type {Map<EventEmitter,Map<string,Set<EventListener>>>}
+ */
+ this._eventListeners = new Map();
+ this.on(constants.EVENT_TEST_END, function(test) {
+ if (test.type === 'test' && test.retriedTest() && test.parent) {
+ var idx =
+ test.parent.tests && test.parent.tests.indexOf(test.retriedTest());
+ if (idx > -1) test.parent.tests[idx] = test;
+ }
+ self.checkGlobals(test);
+ });
+ this.on(constants.EVENT_HOOK_END, function(hook) {
+ self.checkGlobals(hook);
+ });
+ this._defaultGrep = /.*/;
+ this.grep(this._defaultGrep);
+ this.globals(this.globalProps());
- this.uncaught = this._uncaught.bind(this);
+ this.uncaught = this._uncaught.bind(this);
+ }
}
/**
@@ -186,11 +190,6 @@ function Runner(suite, opts) {
*/
Runner.immediately = global.setImmediate || process.nextTick;
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-inherits(Runner, EventEmitter);
-
/**
* Replacement for `target.on(eventName, listener)` that does bookkeeping to remove them when this runner instance is disposed.
* @param {EventEmitter} target - The `EventEmitter`
@@ -199,8 +198,36 @@ inherits(Runner, EventEmitter);
* @private
*/
Runner.prototype._addEventListener = function(target, eventName, listener) {
+ debug(
+ '_addEventListener(): adding for event %s; %d current listeners',
+ eventName,
+ target.listenerCount(eventName)
+ );
+ /* istanbul ignore next */
+ if (
+ this._eventListeners.has(target) &&
+ this._eventListeners.get(target).has(eventName) &&
+ this._eventListeners
+ .get(target)
+ .get(eventName)
+ .has(listener)
+ ) {
+ debug(
+ 'warning: tried to attach duplicate event listener for %s',
+ eventName
+ );
+ return;
+ }
target.on(eventName, listener);
- this._eventListeners.push([target, eventName, listener]);
+ const targetListeners = this._eventListeners.has(target)
+ ? this._eventListeners.get(target)
+ : new Map();
+ const targetEventListeners = targetListeners.has(eventName)
+ ? targetListeners.get(eventName)
+ : new Set();
+ targetEventListeners.add(listener);
+ targetListeners.set(eventName, targetEventListeners);
+ this._eventListeners.set(target, targetListeners);
};
/**
@@ -211,21 +238,22 @@ Runner.prototype._addEventListener = function(target, eventName, listener) {
* @private
*/
Runner.prototype._removeEventListener = function(target, eventName, listener) {
- var eventListenerIndex = -1;
- for (var i = 0; i < this._eventListeners.length; i++) {
- var eventListenerDescriptor = this._eventListeners[i];
- if (
- eventListenerDescriptor[0] === target &&
- eventListenerDescriptor[1] === eventName &&
- eventListenerDescriptor[2] === listener
- ) {
- eventListenerIndex = i;
- break;
+ target.removeListener(eventName, listener);
+
+ if (this._eventListeners.has(target)) {
+ const targetListeners = this._eventListeners.get(target);
+ if (targetListeners.has(eventName)) {
+ const targetEventListeners = targetListeners.get(eventName);
+ targetEventListeners.delete(listener);
+ if (!targetEventListeners.size) {
+ targetListeners.delete(eventName);
+ }
}
- }
- if (eventListenerIndex !== -1) {
- var removedListener = this._eventListeners.splice(eventListenerIndex, 1)[0];
- removedListener[0].removeListener(removedListener[1], removedListener[2]);
+ if (!targetListeners.size) {
+ this._eventListeners.delete(target);
+ }
+ } else {
+ debug('trying to remove listener for untracked object %s', target);
}
};
@@ -235,12 +263,14 @@ Runner.prototype._removeEventListener = function(target, eventName, listener) {
*/
Runner.prototype.dispose = function() {
this.removeAllListeners();
- this._eventListeners.forEach(function(eventListenerDescriptor) {
- eventListenerDescriptor[0].removeListener(
- eventListenerDescriptor[1],
- eventListenerDescriptor[2]
- );
+ this._eventListeners.forEach((targetListeners, target) => {
+ targetListeners.forEach((targetEventListeners, eventName) => {
+ targetEventListeners.forEach(listener => {
+ target.removeListener(eventName, listener);
+ });
+ });
});
+ this._eventListeners.clear();
};
/**
@@ -976,73 +1006,92 @@ Runner.prototype._uncaught = function(err) {
* @memberof Runner
* @param {Function} fn - Callback when finished
* @param {{files: string[], options: Options}} [opts] - For subclasses
- * @return {Runner} Runner instance.
+ * @returns {Runner} Runner instance.
*/
-Runner.prototype.run = function(fn, opts) {
- var self = this;
+Runner.prototype.run = function(fn, opts = {}) {
var rootSuite = this.suite;
+ var options = opts.options || {};
+ debug('run(): got options: %O', options);
fn = fn || function() {};
- function start() {
+ const end = () => {
+ debug('run(): root suite completed; emitting %s', constants.EVENT_RUN_END);
+ this.emit(constants.EVENT_RUN_END);
+ };
+
+ const begin = () => {
+ debug('run(): emitting %s', constants.EVENT_RUN_BEGIN);
+ this.emit(constants.EVENT_RUN_BEGIN);
+ debug('run(): emitted %s', constants.EVENT_RUN_BEGIN);
+
+ this.runSuite(rootSuite, async () => {
+ end();
+ });
+ };
+
+ const prepare = () => {
debug('run(): starting');
// If there is an `only` filter
if (rootSuite.hasOnly()) {
rootSuite.filterOnly();
debug('run(): filtered exclusive Runnables');
}
- self.state = constants.STATE_RUNNING;
- if (self._delay) {
- self.emit(constants.EVENT_DELAY_END);
+ this.state = constants.STATE_RUNNING;
+ if (this._delay) {
+ this.emit(constants.EVENT_DELAY_END);
debug('run(): "delay" ended');
}
- debug('run(): emitting %s', constants.EVENT_RUN_BEGIN);
- self.emit(constants.EVENT_RUN_BEGIN);
- debug('run(): emitted %s', constants.EVENT_RUN_BEGIN);
- self.runSuite(rootSuite, function() {
- debug(
- 'run(): root suite completed; emitting %s',
- constants.EVENT_RUN_END
- );
- self.emit(constants.EVENT_RUN_END);
- debug('run(): emitted %s', constants.EVENT_RUN_END);
- });
- }
+ return begin();
+ };
// references cleanup to avoid memory leaks
if (this._opts.cleanReferencesAfterRun) {
- this.on(constants.EVENT_SUITE_END, function(suite) {
+ this.on(constants.EVENT_SUITE_END, suite => {
suite.cleanReferences();
});
}
// callback
this.on(constants.EVENT_RUN_END, function() {
- self.state = constants.STATE_STOPPED;
- debug(constants.EVENT_RUN_END);
+ this.state = constants.STATE_STOPPED;
debug('run(): emitted %s', constants.EVENT_RUN_END);
- fn(self.failures);
+ fn(this.failures);
});
- self._removeEventListener(process, 'uncaughtException', self.uncaught);
- self._addEventListener(process, 'uncaughtException', self.uncaught);
+ this._removeEventListener(process, 'uncaughtException', this.uncaught);
+ this._removeEventListener(process, 'unhandledRejection', this.uncaught);
+ this._addEventListener(process, 'uncaughtException', this.uncaught);
+ this._addEventListener(process, 'unhandledRejection', this.uncaught);
if (this._delay) {
// for reporters, I guess.
// might be nice to debounce some dots while we wait.
this.emit(constants.EVENT_DELAY_BEGIN, rootSuite);
- rootSuite.once(EVENT_ROOT_SUITE_RUN, start);
+ rootSuite.once(EVENT_ROOT_SUITE_RUN, prepare);
debug('run(): waiting for green light due to --delay');
} else {
- Runner.immediately(function() {
- start();
- });
+ Runner.immediately(prepare);
}
return this;
};
+/**
+ * Like {@link Runner#run}, but does not accept a callback and returns a `Promise` instead of a `Runner`.
+ * This function cannot reject; an `unhandledRejection` event will bubble up to the `process` object instead.
+ * @public
+ * @memberof Runner
+ * @param {Object} [opts] - Options for {@link Runner#run}
+ * @returns {Promise<number>} Failure count
+ */
+Runner.prototype.runAsync = async function runAsync(opts = {}) {
+ return new Promise(resolve => {
+ this.run(resolve, opts);
+ });
+};
+
/**
* Cleanly abort execution.
*
@@ -1133,3 +1182,5 @@ Runner.constants = constants;
* @external EventEmitter
* @see {@link https://nodejs.org/api/events.html#events_class_eventemitter}
*/
+
+module.exports = Runner;
diff --git a/lib/suite.js b/lib/suite.js
index e9d45d94..5df005e6 100644
--- a/lib/suite.js
+++ b/lib/suite.js
@@ -10,8 +10,7 @@ var utils = require('./utils');
var inherits = utils.inherits;
var debug = require('debug')('mocha:suite');
var milliseconds = require('ms');
-var errors = require('./errors');
-var createInvalidArgumentTypeError = errors.createInvalidArgumentTypeError;
+const errors = require('./errors');
/**
* Expose `Suite`.
@@ -48,7 +47,7 @@ Suite.create = function(parent, title) {
*/
function Suite(title, parentContext, isRoot) {
if (!utils.isString(title)) {
- throw createInvalidArgumentTypeError(
+ throw errors.createInvalidArgumentTypeError(
'Suite argument "title" must be a string. Received type "' +
typeof title +
'"',
@@ -78,7 +77,7 @@ function Suite(title, parentContext, isRoot) {
this.on('newListener', function(event) {
if (deprecatedEvents[event]) {
- utils.deprecate(
+ errors.deprecate(
'Event "' +
event +
'" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm'
diff --git a/lib/utils.js b/lib/utils.js
index e6eed672..a349827e 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -12,8 +12,7 @@
var path = require('path');
var util = require('util');
var he = require('he');
-
-var assign = (exports.assign = require('object.assign').getPolyfill());
+const errors = require('./errors');
/**
* Inherit the prototype methods from one constructor into another.
@@ -378,50 +377,6 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) {
return canonicalizedObj;
};
-/**
- * process.emitWarning or a polyfill
- * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options
- * @ignore
- */
-function emitWarning(msg, type) {
- if (process.emitWarning) {
- process.emitWarning(msg, type);
- } else {
- process.nextTick(function() {
- console.warn(type + ': ' + msg);
- });
- }
-}
-
-/**
- * Show a deprecation warning. Each distinct message is only displayed once.
- * Ignores empty messages.
- *
- * @param {string} [msg] - Warning to print
- * @private
- */
-exports.deprecate = function deprecate(msg) {
- msg = String(msg);
- if (msg && !deprecate.cache[msg]) {
- deprecate.cache[msg] = true;
- emitWarning(msg, 'DeprecationWarning');
- }
-};
-exports.deprecate.cache = {};
-
-/**
- * Show a generic warning.
- * Ignores empty messages.
- *
- * @param {string} [msg] - Warning to print
- * @private
- */
-exports.warn = function warn(msg) {
- if (msg) {
- emitWarning(msg);
- }
-};
-
/**
* @summary
* This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)
@@ -575,7 +530,7 @@ exports.noop = function() {};
* @returns {Object} An object with no prototype, having `...obj` properties
*/
exports.createMap = function(obj) {
- return assign.apply(
+ return Object.assign.apply(
null,
[Object.create(null)].concat(Array.prototype.slice.call(arguments))
);
@@ -665,12 +620,39 @@ exports.isBrowser = function isBrowser() {
*/
exports.lookupFiles = (...args) => {
if (exports.isBrowser()) {
- throw require('./errors').createUnsupportedError(
+ throw errors.createUnsupportedError(
'lookupFiles() is only supported in Node.js!'
);
}
- exports.deprecate(
+ errors.deprecate(
'`lookupFiles()` in module `mocha/lib/utils` has moved to module `mocha/lib/cli` and will be removed in the next major revision of Mocha'
);
return require('./cli').lookupFiles(...args);
};
+
+/*
+ * Casts `value` to an array; useful for optionally accepting array parameters
+ *
+ * It follows these rules, depending on `value`. If `value` is...
+ * 1. `undefined`: return an empty Array
+ * 2. `null`: return an array with a single `null` element
+ * 3. Any other object: return the value of `Array.from()` _if_ the object is iterable
+ * 4. otherwise: return an array with a single element, `value`
+ * @param {*} value - Something to cast to an Array
+ * @returns {Array<*>}
+ */
+exports.castArray = function castArray(value) {
+ if (value === undefined) {
+ return [];
+ }
+ if (value === null) {
+ return [null];
+ }
+ if (
+ typeof value === 'object' &&
+ (typeof value[Symbol.iterator] === 'function' || value.length !== undefined)
+ ) {
+ return Array.from(value);
+ }
+ return [value];
+};
diff --git a/package-lock.json b/package-lock.json
index 1dc3dee9..12ccfc1f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -4394,6 +4394,12 @@
"p-locate": "^4.1.0"
}
},
+ "lodash": {
+ "version": "4.17.15",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz",
+ "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==",
+ "dev": true
+ },
"p-locate": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
@@ -5428,16 +5434,16 @@
"integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw=="
},
"browser-sync": {
- "version": "2.26.7",
- "resolved": "https://registry.npmjs.org/browser-sync/-/browser-sync-2.26.7.tgz",
- "integrity": "sha512-lY3emme0OyvA2ujEMpRmyRy9LY6gHLuTr2/ABxhIm3lADOiRXzP4dgekvnDrQqZ/Ec2Fz19lEjm6kglSG5766w==",
+ "version": "2.26.12",
+ "resolved": "https://registry.npmjs.org/browser-sync/-/browser-sync-2.26.12.tgz",
+ "integrity": "sha512-1GjAe+EpZQJgtKhWsxklEjpaMV0DrRylpHRvZWgOphDQt+bfLZjfynl/j1WjSFIx8ozj9j78g6Yk4TqD3gKaMA==",
"dev": true,
"requires": {
- "browser-sync-client": "^2.26.6",
- "browser-sync-ui": "^2.26.4",
+ "browser-sync-client": "^2.26.12",
+ "browser-sync-ui": "^2.26.12",
"bs-recipes": "1.3.4",
"bs-snippet-injector": "^2.0.1",
- "chokidar": "^2.0.4",
+ "chokidar": "^3.4.1",
"connect": "3.6.6",
"connect-history-api-fallback": "^1",
"dev-ip": "^1.0.1",
@@ -5446,10 +5452,10 @@
"etag": "^1.8.1",
"fresh": "^0.5.2",
"fs-extra": "3.0.1",
- "http-proxy": "1.15.2",
+ "http-proxy": "^1.18.1",
"immutable": "^3",
- "localtunnel": "1.9.2",
- "micromatch": "^3.1.10",
+ "localtunnel": "^2.0.0",
+ "micromatch": "^4.0.2",
"opn": "5.3.0",
"portscanner": "2.1.1",
"qs": "6.2.3",
@@ -5461,938 +5467,164 @@
"serve-static": "1.13.2",
"server-destroy": "1.0.1",
"socket.io": "2.1.1",
- "ua-parser-js": "0.7.17",
- "yargs": "6.4.0"
+ "ua-parser-js": "^0.7.18",
+ "yargs": "^15.4.1"
},
"dependencies": {
- "ansi-regex": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",
- "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=",
- "dev": true
- },
- "anymatch": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz",
- "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==",
- "dev": true,
- "requires": {
- "micromatch": "^3.1.4",
- "normalize-path": "^2.1.1"
- },
- "dependencies": {
- "normalize-path": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz",
- "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=",
- "dev": true,
- "requires": {
- "remove-trailing-separator": "^1.0.1"
- }
- }
- }
- },
- "binary-extensions": {
- "version": "1.13.1",
- "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.13.1.tgz",
- "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==",
- "dev": true
- },
- "braces": {
- "version": "2.3.2",
- "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz",
- "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==",
- "dev": true,
- "requires": {
- "arr-flatten": "^1.1.0",
- "array-unique": "^0.3.2",
- "extend-shallow": "^2.0.1",
- "fill-range": "^4.0.0",
- "isobject": "^3.0.1",
- "repeat-element": "^1.1.2",
- "snapdragon": "^0.8.1",
- "snapdragon-node": "^2.0.1",
- "split-string": "^3.0.2",
- "to-regex": "^3.0.1"
- }
- },
- "camelcase": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz",
- "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=",
- "dev": true
- },
- "chokidar": {
- "version": "2.1.8",
- "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.8.tgz",
- "integrity": "sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg==",
+ "ansi-styles": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz",
+ "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==",
"dev": true,
"requires": {
- "anymatch": "^2.0.0",
- "async-each": "^1.0.1",
- "braces": "^2.3.2",
- "fsevents": "^1.2.7",
- "glob-parent": "^3.1.0",
- "inherits": "^2.0.3",
- "is-binary-path": "^1.0.0",
- "is-glob": "^4.0.0",
- "normalize-path": "^3.0.0",
- "path-is-absolute": "^1.0.0",
- "readdirp": "^2.2.1",
- "upath": "^1.1.1"
+ "@types/color-name": "^1.1.1",
+ "color-convert": "^2.0.1"
}
},
"cliui": {
- "version": "3.2.0",
- "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz",
- "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=",
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
+ "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
"dev": true,
"requires": {
- "string-width": "^1.0.1",
- "strip-ansi": "^3.0.1",
- "wrap-ansi": "^2.0.0"
+ "string-width": "^4.2.0",
+ "strip-ansi": "^6.0.0",
+ "wrap-ansi": "^6.2.0"
}
},
- "eventemitter3": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-1.2.0.tgz",
- "integrity": "sha1-HIaZHYFq0eUEdQ5zh0Ik7PO+xQg=",
- "dev": true
- },
- "extend-shallow": {
+ "color-convert": {
"version": "2.0.1",
- "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
- "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
- "dev": true,
- "requires": {
- "is-extendable": "^0.1.0"
- }
- },
- "fill-range": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz",
- "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=",
- "dev": true,
- "requires": {
- "extend-shallow": "^2.0.1",
- "is-number": "^3.0.0",
- "repeat-string": "^1.6.1",
- "to-regex-range": "^2.1.0"
- }
- },
- "fs-extra": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-3.0.1.tgz",
- "integrity": "sha1-N5TzeMWLNC6n27sjCVEJxLO2IpE=",
- "dev": true,
- "requires": {
- "graceful-fs": "^4.1.2",
- "jsonfile": "^3.0.0",
- "universalify": "^0.1.0"
- }
- },
- "fsevents": {
- "version": "1.2.12",
- "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.12.tgz",
- "integrity": "sha512-Ggd/Ktt7E7I8pxZRbGIs7vwqAPscSESMrCSkx2FtWeqmheJgCo2R74fTsZFCifr0VTPwqRpPv17+6b8Zp7th0Q==",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
- "optional": true,
"requires": {
- "bindings": "^1.5.0",
- "nan": "^2.12.1",
- "node-pre-gyp": "*"
- },
- "dependencies": {
- "abbrev": {
- "version": "1.1.1",
- "resolved": false,
- "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
- "dev": true,
- "optional": true
- },
- "ansi-regex": {
- "version": "2.1.1",
- "resolved": false,
- "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=",
- "dev": true,
- "optional": true
- },
- "aproba": {
- "version": "1.2.0",
- "resolved": false,
- "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==",
- "dev": true,
- "optional": true
- },
- "are-we-there-yet": {
- "version": "1.1.5",
- "resolved": false,
- "integrity": "sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w==",
- "dev": true,
- "optional": true,
- "requires": {
- "delegates": "^1.0.0",
- "readable-stream": "^2.0.6"
- }
- },
- "balanced-match": {
- "version": "1.0.0",
- "resolved": false,
- "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
- "dev": true,
- "optional": true
- },
- "brace-expansion": {
- "version": "1.1.11",
- "resolved": false,
- "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
- "dev": true,
- "optional": true,
- "requires": {
- "balanced-match": "^1.0.0",
- "concat-map": "0.0.1"
- }
- },
- "chownr": {
- "version": "1.1.4",
- "resolved": false,
- "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
- "dev": true,
- "optional": true
- },
- "code-point-at": {
- "version": "1.1.0",
- "resolved": false,
- "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=",
- "dev": true,
- "optional": true
- },
- "concat-map": {
- "version": "0.0.1",
- "resolved": false,
- "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
- "dev": true,
- "optional": true
- },
- "console-control-strings": {
- "version": "1.1.0",
- "resolved": false,
- "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=",
- "dev": true,
- "optional": true
- },
- "core-util-is": {
- "version": "1.0.2",
- "resolved": false,
- "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=",
- "dev": true,
- "optional": true
- },
- "debug": {
- "version": "3.2.6",
- "resolved": false,
- "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==",
- "dev": true,
- "optional": true,
- "requires": {
- "ms": "^2.1.1"
- }
- },
- "deep-extend": {
- "version": "0.6.0",
- "resolved": false,
- "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
- "dev": true,
- "optional": true
- },
- "delegates": {
- "version": "1.0.0",
- "resolved": false,
- "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=",
- "dev": true,
- "optional": true
- },
- "detect-libc": {
- "version": "1.0.3",
- "resolved": false,
- "integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=",
- "dev": true,
- "optional": true
- },
- "fs-minipass": {
- "version": "1.2.7",
- "resolved": false,
- "integrity": "sha512-GWSSJGFy4e9GUeCcbIkED+bgAoFyj7XF1mV8rma3QW4NIqX9Kyx79N/PF61H5udOV3aY1IaMLs6pGbH71nlCTA==",
- "dev": true,
- "optional": true,
- "requires": {
- "minipass": "^2.6.0"
- }
- },
- "fs.realpath": {
- "version": "1.0.0",
- "resolved": false,
- "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
- "dev": true,
- "optional": true
- },
- "gauge": {
- "version": "2.7.4",
- "resolved": false,
- "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=",
- "dev": true,
- "optional": true,
- "requires": {
- "aproba": "^1.0.3",
- "console-control-strings": "^1.0.0",
- "has-unicode": "^2.0.0",
- "object-assign": "^4.1.0",
- "signal-exit": "^3.0.0",
- "string-width": "^1.0.1",
- "strip-ansi": "^3.0.1",
- "wide-align": "^1.1.0"
- }
- },
- "glob": {
- "version": "7.1.6",
- "resolved": false,
- "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==",
- "dev": true,
- "optional": true,
- "requires": {
- "fs.realpath": "^1.0.0",
- "inflight": "^1.0.4",
- "inherits": "2",
- "minimatch": "^3.0.4",
- "once": "^1.3.0",
- "path-is-absolute": "^1.0.0"
- }
- },
- "has-unicode": {
- "version": "2.0.1",
- "resolved": false,
- "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=",
- "dev": true,
- "optional": true
- },
- "iconv-lite": {
- "version": "0.4.24",
- "resolved": false,
- "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
- "dev": true,
- "optional": true,
- "requires": {
- "safer-buffer": ">= 2.1.2 < 3"
- }
- },
- "ignore-walk": {
- "version": "3.0.3",
- "resolved": false,
- "integrity": "sha512-m7o6xuOaT1aqheYHKf8W6J5pYH85ZI9w077erOzLje3JsB1gkafkAhHHY19dqjulgIZHFm32Cp5uNZgcQqdJKw==",
- "dev": true,
- "optional": true,
- "requires": {
- "minimatch": "^3.0.4"
- }
- },
- "inflight": {
- "version": "1.0.6",
- "resolved": false,
- "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
- "dev": true,
- "optional": true,
- "requires": {
- "once": "^1.3.0",
- "wrappy": "1"
- }
- },
- "inherits": {
- "version": "2.0.4",
- "resolved": false,
- "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
- "dev": true,
- "optional": true
- },
- "ini": {
- "version": "1.3.5",
- "resolved": false,
- "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==",
- "dev": true,
- "optional": true
- },
- "is-fullwidth-code-point": {
- "version": "1.0.0",
- "resolved": false,
- "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=",
- "dev": true,
- "optional": true,
- "requires": {
- "number-is-nan": "^1.0.0"
- }
- },
- "isarray": {
- "version": "1.0.0",
- "resolved": false,
- "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=",
- "dev": true,
- "optional": true
- },
- "minimatch": {
- "version": "3.0.4",
- "resolved": false,
- "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
- "dev": true,
- "optional": true,
- "requires": {
- "brace-expansion": "^1.1.7"
- }
- },
- "minimist": {
- "version": "1.2.5",
- "resolved": false,
- "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
- "dev": true,
- "optional": true
- },
- "minipass": {
- "version": "2.9.0",
- "resolved": false,
- "integrity": "sha512-wxfUjg9WebH+CUDX/CdbRlh5SmfZiy/hpkxaRI16Y9W56Pa75sWgd/rvFilSgrauD9NyFymP/+JFV3KwzIsJeg==",
- "dev": true,
- "optional": true,
- "requires": {
- "safe-buffer": "^5.1.2",
- "yallist": "^3.0.0"
- }
- },
- "minizlib": {
- "version": "1.3.3",
- "resolved": false,
- "integrity": "sha512-6ZYMOEnmVsdCeTJVE0W9ZD+pVnE8h9Hma/iOwwRDsdQoePpoX56/8B6z3P9VNwppJuBKNRuFDRNRqRWexT9G9Q==",
- "dev": true,
- "optional": true,
- "requires": {
- "minipass": "^2.9.0"
- }
- },
- "mkdirp": {
- "version": "0.5.3",
- "resolved": false,
- "integrity": "sha512-P+2gwrFqx8lhew375MQHHeTlY8AuOJSrGf0R5ddkEndUkmwpgUob/vQuBD1V22/Cw1/lJr4x+EjllSezBThzBg==",
- "dev": true,
- "optional": true,
- "requires": {
- "minimist": "^1.2.5"
- }
- },
- "ms": {
- "version": "2.1.2",
- "resolved": false,
- "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
- "dev": true,
- "optional": true
- },
- "needle": {
- "version": "2.3.3",
- "resolved": false,
- "integrity": "sha512-EkY0GeSq87rWp1hoq/sH/wnTWgFVhYlnIkbJ0YJFfRgEFlz2RraCjBpFQ+vrEgEdp0ThfyHADmkChEhcb7PKyw==",
- "dev": true,
- "optional": true,
- "requires": {
- "debug": "^3.2.6",
- "iconv-lite": "^0.4.4",
- "sax": "^1.2.4"
- }
- },
- "node-pre-gyp": {
- "version": "0.14.0",
- "resolved": false,
- "integrity": "sha512-+CvDC7ZttU/sSt9rFjix/P05iS43qHCOOGzcr3Ry99bXG7VX953+vFyEuph/tfqoYu8dttBkE86JSKBO2OzcxA==",
- "dev": true,
- "optional": true,
- "requires": {
- "detect-libc": "^1.0.2",
- "mkdirp": "^0.5.1",
- "needle": "^2.2.1",
- "nopt": "^4.0.1",
- "npm-packlist": "^1.1.6",
- "npmlog": "^4.0.2",
- "rc": "^1.2.7",
- "rimraf": "^2.6.1",
- "semver": "^5.3.0",
- "tar": "^4.4.2"
- }
- },
- "nopt": {
- "version": "4.0.3",
- "resolved": false,
- "integrity": "sha512-CvaGwVMztSMJLOeXPrez7fyfObdZqNUK1cPAEzLHrTybIua9pMdmmPR5YwtfNftIOMv3DPUhFaxsZMNTQO20Kg==",
- "dev": true,
- "optional": true,
- "requires": {
- "abbrev": "1",
- "osenv": "^0.1.4"
- }
- },
- "npm-bundled": {
- "version": "1.1.1",
- "resolved": false,
- "integrity": "sha512-gqkfgGePhTpAEgUsGEgcq1rqPXA+tv/aVBlgEzfXwA1yiUJF7xtEt3CtVwOjNYQOVknDk0F20w58Fnm3EtG0fA==",
- "dev": true,
- "optional": true,
- "requires": {
- "npm-normalize-package-bin": "^1.0.1"
- }
- },
- "npm-normalize-package-bin": {
- "version": "1.0.1",
- "resolved": false,
- "integrity": "sha512-EPfafl6JL5/rU+ot6P3gRSCpPDW5VmIzX959Ob1+ySFUuuYHWHekXpwdUZcKP5C+DS4GEtdJluwBjnsNDl+fSA==",
- "dev": true,
- "optional": true
- },
- "npm-packlist": {
- "version": "1.4.8",
- "resolved": false,
- "integrity": "sha512-5+AZgwru5IevF5ZdnFglB5wNlHG1AOOuw28WhUq8/8emhBmLv6jX5by4WJCh7lW0uSYZYS6DXqIsyZVIXRZU9A==",
- "dev": true,
- "optional": true,
- "requires": {
- "ignore-walk": "^3.0.1",
- "npm-bundled": "^1.0.1",
- "npm-normalize-package-bin": "^1.0.1"
- }
- },
- "npmlog": {
- "version": "4.1.2",
- "resolved": false,
- "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==",
- "dev": true,
- "optional": true,
- "requires": {
- "are-we-there-yet": "~1.1.2",
- "console-control-strings": "~1.1.0",
- "gauge": "~2.7.3",
- "set-blocking": "~2.0.0"
- }
- },
- "number-is-nan": {
- "version": "1.0.1",
- "resolved": false,
- "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=",
- "dev": true,
- "optional": true
- },
- "object-assign": {
- "version": "4.1.1",
- "resolved": false,
- "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=",
- "dev": true,
- "optional": true
- },
- "once": {
- "version": "1.4.0",
- "resolved": false,
- "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
- "dev": true,
- "optional": true,
- "requires": {
- "wrappy": "1"
- }
- },
- "os-homedir": {
- "version": "1.0.2",
- "resolved": false,
- "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=",
- "dev": true,
- "optional": true
- },
- "os-tmpdir": {
- "version": "1.0.2",
- "resolved": false,
- "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=",
- "dev": true,
- "optional": true
- },
- "osenv": {
- "version": "0.1.5",
- "resolved": false,
- "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==",
- "dev": true,
- "optional": true,
- "requires": {
- "os-homedir": "^1.0.0",
- "os-tmpdir": "^1.0.0"
- }
- },
- "path-is-absolute": {
- "version": "1.0.1",
- "resolved": false,
- "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=",
- "dev": true,
- "optional": true
- },
- "process-nextick-args": {
- "version": "2.0.1",
- "resolved": false,
- "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
- "dev": true,
- "optional": true
- },
- "rc": {
- "version": "1.2.8",
- "resolved": false,
- "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
- "dev": true,
- "optional": true,
- "requires": {
- "deep-extend": "^0.6.0",
- "ini": "~1.3.0",
- "minimist": "^1.2.0",
- "strip-json-comments": "~2.0.1"
- }
- },
- "readable-stream": {
- "version": "2.3.7",
- "resolved": false,
- "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
- "dev": true,
- "optional": true,
- "requires": {
- "core-util-is": "~1.0.0",
- "inherits": "~2.0.3",
- "isarray": "~1.0.0",
- "process-nextick-args": "~2.0.0",
- "safe-buffer": "~5.1.1",
- "string_decoder": "~1.1.1",
- "util-deprecate": "~1.0.1"
- }
- },
- "rimraf": {
- "version": "2.7.1",
- "resolved": false,
- "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
- "dev": true,
- "optional": true,
- "requires": {
- "glob": "^7.1.3"
- }
- },
- "safe-buffer": {
- "version": "5.1.2",
- "resolved": false,
- "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
- "dev": true,
- "optional": true
- },
- "safer-buffer": {
- "version": "2.1.2",
- "resolved": false,
- "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
- "dev": true,
- "optional": true
- },
- "sax": {
- "version": "1.2.4",
- "resolved": false,
- "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==",
- "dev": true,
- "optional": true
- },
- "semver": {
- "version": "5.7.1",
- "resolved": false,
- "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==",
- "dev": true,
- "optional": true
- },
- "set-blocking": {
- "version": "2.0.0",
- "resolved": false,
- "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=",
- "dev": true,
- "optional": true
- },
- "signal-exit": {
- "version": "3.0.2",
- "resolved": false,
- "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=",
- "dev": true,
- "optional": true
- },
- "string-width": {
- "version": "1.0.2",
- "resolved": false,
- "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=",
- "dev": true,
- "optional": true,
- "requires": {
- "code-point-at": "^1.0.0",
- "is-fullwidth-code-point": "^1.0.0",
- "strip-ansi": "^3.0.0"
- }
- },
- "string_decoder": {
- "version": "1.1.1",
- "resolved": false,
- "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
- "dev": true,
- "optional": true,
- "requires": {
- "safe-buffer": "~5.1.0"
- }
- },
- "strip-ansi": {
- "version": "3.0.1",
- "resolved": false,
- "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
- "dev": true,
- "optional": true,
- "requires": {
- "ansi-regex": "^2.0.0"
- }
- },
- "strip-json-comments": {
- "version": "2.0.1",
- "resolved": false,
- "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=",
- "dev": true,
- "optional": true
- },
- "tar": {
- "version": "4.4.13",
- "resolved": false,
- "integrity": "sha512-w2VwSrBoHa5BsSyH+KxEqeQBAllHhccyMFVHtGtdMpF4W7IRWfZjFiQceJPChOeTsSDVUpER2T8FA93pr0L+QA==",
- "dev": true,
- "optional": true,
- "requires": {
- "chownr": "^1.1.1",
- "fs-minipass": "^1.2.5",
- "minipass": "^2.8.6",
- "minizlib": "^1.2.1",
- "mkdirp": "^0.5.0",
- "safe-buffer": "^5.1.2",
- "yallist": "^3.0.3"
- }
- },
- "util-deprecate": {
- "version": "1.0.2",
- "resolved": false,
- "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=",
- "dev": true,
- "optional": true
- },
- "wide-align": {
- "version": "1.1.3",
- "resolved": false,
- "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==",
- "dev": true,
- "optional": true,
- "requires": {
- "string-width": "^1.0.2 || 2"
- }
- },
- "wrappy": {
- "version": "1.0.2",
- "resolved": false,
- "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
- "dev": true,
- "optional": true
- },
- "yallist": {
- "version": "3.1.1",
- "resolved": false,
- "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
- "dev": true,
- "optional": true
- }
- }
- },
- "get-caller-file": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz",
- "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==",
- "dev": true
- },
- "glob-parent": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz",
- "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=",
- "dev": true,
- "requires": {
- "is-glob": "^3.1.0",
- "path-dirname": "^1.0.0"
- },
- "dependencies": {
- "is-glob": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz",
- "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=",
- "dev": true,
- "requires": {
- "is-extglob": "^2.1.0"
- }
- }
- }
- },
- "http-proxy": {
- "version": "1.15.2",
- "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.15.2.tgz",
- "integrity": "sha1-ZC/cr/5S00SNK9o7AHnpQJBk2jE=",
- "dev": true,
- "requires": {
- "eventemitter3": "1.x.x",
- "requires-port": "1.x.x"
- }
- },
- "is-binary-path": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz",
- "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=",
- "dev": true,
- "requires": {
- "binary-extensions": "^1.0.0"
- }
- },
- "is-buffer": {
- "version": "1.1.6",
- "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
- "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
- "dev": true
- },
- "is-fullwidth-code-point": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz",
- "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=",
- "dev": true,
- "requires": {
- "number-is-nan": "^1.0.0"
- }
- },
- "is-number": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz",
- "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=",
- "dev": true,
- "requires": {
- "kind-of": "^3.0.2"
+ "color-name": "~1.1.4"
}
},
- "kind-of": {
- "version": "3.2.2",
- "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
- "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true
+ },
+ "emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "dev": true
+ },
+ "find-up": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
+ "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
"dev": true,
"requires": {
- "is-buffer": "^1.1.5"
+ "locate-path": "^5.0.0",
+ "path-exists": "^4.0.0"
}
},
- "readdirp": {
- "version": "2.2.1",
- "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.2.1.tgz",
- "integrity": "sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ==",
+ "fs-extra": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-3.0.1.tgz",
+ "integrity": "sha1-N5TzeMWLNC6n27sjCVEJxLO2IpE=",
"dev": true,
"requires": {
- "graceful-fs": "^4.1.11",
- "micromatch": "^3.1.10",
- "readable-stream": "^2.0.2"
+ "graceful-fs": "^4.1.2",
+ "jsonfile": "^3.0.0",
+ "universalify": "^0.1.0"
}
},
- "require-main-filename": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz",
- "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=",
+ "is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true
},
- "string-width": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
- "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=",
+ "locate-path": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
+ "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
"dev": true,
"requires": {
- "code-point-at": "^1.0.0",
- "is-fullwidth-code-point": "^1.0.0",
- "strip-ansi": "^3.0.0"
+ "p-locate": "^4.1.0"
}
},
- "strip-ansi": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
- "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
+ "micromatch": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz",
+ "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==",
"dev": true,
"requires": {
- "ansi-regex": "^2.0.0"
+ "braces": "^3.0.1",
+ "picomatch": "^2.0.5"
}
},
- "to-regex-range": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz",
- "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=",
+ "p-locate": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
+ "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
"dev": true,
"requires": {
- "is-number": "^3.0.0",
- "repeat-string": "^1.6.1"
+ "p-limit": "^2.2.0"
}
},
- "which-module": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/which-module/-/which-module-1.0.0.tgz",
- "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=",
- "dev": true
+ "string-width": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz",
+ "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==",
+ "dev": true,
+ "requires": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.0"
+ }
},
"wrap-ansi": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz",
- "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=",
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
+ "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
"dev": true,
"requires": {
- "string-width": "^1.0.1",
- "strip-ansi": "^3.0.1"
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
}
},
- "y18n": {
- "version": "3.2.1",
- "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz",
- "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=",
- "dev": true
- },
"yargs": {
- "version": "6.4.0",
- "resolved": "https://registry.npmjs.org/yargs/-/yargs-6.4.0.tgz",
- "integrity": "sha1-gW4ahm1VmMzzTlWW3c4i2S2kkNQ=",
+ "version": "15.4.1",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
+ "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
"dev": true,
"requires": {
- "camelcase": "^3.0.0",
- "cliui": "^3.2.0",
- "decamelize": "^1.1.1",
- "get-caller-file": "^1.0.1",
- "os-locale": "^1.4.0",
- "read-pkg-up": "^1.0.1",
+ "cliui": "^6.0.0",
+ "decamelize": "^1.2.0",
+ "find-up": "^4.1.0",
+ "get-caller-file": "^2.0.1",
"require-directory": "^2.1.1",
- "require-main-filename": "^1.0.1",
+ "require-main-filename": "^2.0.0",
"set-blocking": "^2.0.0",
- "string-width": "^1.0.2",
- "which-module": "^1.0.0",
- "window-size": "^0.2.0",
- "y18n": "^3.2.1",
- "yargs-parser": "^4.1.0"
+ "string-width": "^4.2.0",
+ "which-module": "^2.0.0",
+ "y18n": "^4.0.0",
+ "yargs-parser": "^18.1.2"
}
},
"yargs-parser": {
- "version": "4.2.1",
- "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-4.2.1.tgz",
- "integrity": "sha1-KczqwNxPA8bIe0qfIX3RjJ90hxw=",
+ "version": "18.1.3",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
+ "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
"dev": true,
"requires": {
- "camelcase": "^3.0.0"
+ "camelcase": "^5.0.0",
+ "decamelize": "^1.2.0"
}
}
}
},
"browser-sync-client": {
- "version": "2.26.6",
- "resolved": "https://registry.npmjs.org/browser-sync-client/-/browser-sync-client-2.26.6.tgz",
- "integrity": "sha512-mGrkZdNzttKdf/16I+y+2dTQxoMCIpKbVIMJ/uP8ZpnKu9f9qa/2CYVtLtbjZG8nsM14EwiCrjuFTGBEnT3Gjw==",
+ "version": "2.26.12",
+ "resolved": "https://registry.npmjs.org/browser-sync-client/-/browser-sync-client-2.26.12.tgz",
+ "integrity": "sha512-bEBDRkufKxrIfjOsIB1FN9itUEXr2oLtz1AySgSSr80K2AWzmtoYnxtVASx/i40qFrSdeI31pNvdCjHivihLVA==",
"dev": true,
"requires": {
"etag": "1.8.1",
@@ -6402,9 +5634,9 @@
}
},
"browser-sync-ui": {
- "version": "2.26.4",
- "resolved": "https://registry.npmjs.org/browser-sync-ui/-/browser-sync-ui-2.26.4.tgz",
- "integrity": "sha512-u20P3EsZoM8Pt+puoi3BU3KlbQAH1lAcV+/O4saF26qokrBqIDotmGonfWwoRbUmdxZkM9MBmA0K39ZTG1h4sA==",
+ "version": "2.26.12",
+ "resolved": "https://registry.npmjs.org/browser-sync-ui/-/browser-sync-ui-2.26.12.tgz",
+ "integrity": "sha512-PkAJNf/TfCFTCkQUfXplR2Kp/+/lbCWFO9lrgLZsmxIhvMLx2pYZFBbTBIaem8qjXhld9ZcESUC8EdU5VWFJgQ==",
"dev": true,
"requires": {
"async-each-series": "0.1.1",
@@ -9303,9 +8535,9 @@
"dev": true
},
"elliptic": {
- "version": "6.5.2",
- "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.2.tgz",
- "integrity": "sha512-f4x70okzZbIQl/NSRLkI/+tteV/9WqL98zx+SQ69KbXxmVrmjwsNUPn/gYJJ0sHvEak24cZgHIPegRePAtA/xw==",
+ "version": "6.5.3",
+ "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.3.tgz",
+ "integrity": "sha512-IMqzv5wNQf+E6aHeIqATs0tOLeOTwj1QKbRcS3jBbYkl5oLAserA8yJTT7/VyHUYG91PRmPyeQDObKLPpeS4dw==",
"dev": true,
"requires": {
"bn.js": "^4.4.0",
@@ -12406,6 +11638,12 @@
"p-locate": "^4.1.0"
}
},
+ "lodash": {
+ "version": "4.17.15",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz",
+ "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==",
+ "dev": true
+ },
"p-locate": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
@@ -12892,12 +12130,6 @@
"loose-envify": "^1.0.0"
}
},
- "invert-kv": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz",
- "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=",
- "dev": true
- },
"ip-regex": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz",
@@ -14425,15 +13657,6 @@
"readable-stream": "^2.0.5"
}
},
- "lcid": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz",
- "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=",
- "dev": true,
- "requires": {
- "invert-kv": "^1.0.0"
- }
- },
"lcov-parse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/lcov-parse/-/lcov-parse-1.0.0.tgz",
@@ -15091,140 +14314,93 @@
}
},
"localtunnel": {
- "version": "1.9.2",
- "resolved": "https://registry.npmjs.org/localtunnel/-/localtunnel-1.9.2.tgz",
- "integrity": "sha512-NEKF7bDJE9U3xzJu3kbayF0WTvng6Pww7tzqNb/XtEARYwqw7CKEX7BvOMg98FtE9es2CRizl61gkV3hS8dqYg==",
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/localtunnel/-/localtunnel-2.0.0.tgz",
+ "integrity": "sha512-g6E0aLgYYDvQDxIjIXkgJo2+pHj3sGg4Wz/XP3h2KtZnRsWPbOQY+hw1H8Z91jep998fkcVE9l+kghO+97vllg==",
"dev": true,
"requires": {
"axios": "0.19.0",
"debug": "4.1.1",
"openurl": "1.1.1",
- "yargs": "6.6.0"
+ "yargs": "13.3.0"
},
"dependencies": {
"ansi-regex": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",
- "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=",
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
+ "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==",
"dev": true
},
- "camelcase": {
+ "find-up": {
"version": "3.0.0",
- "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz",
- "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=",
- "dev": true
- },
- "cliui": {
- "version": "3.2.0",
- "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz",
- "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz",
+ "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==",
"dev": true,
"requires": {
- "string-width": "^1.0.1",
- "strip-ansi": "^3.0.1",
- "wrap-ansi": "^2.0.0"
+ "locate-path": "^3.0.0"
}
},
- "debug": {
- "version": "4.1.1",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
- "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
+ "locate-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz",
+ "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==",
"dev": true,
"requires": {
- "ms": "^2.1.1"
+ "p-locate": "^3.0.0",
+ "path-exists": "^3.0.0"
}
},
- "get-caller-file": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz",
- "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==",
- "dev": true
- },
- "is-fullwidth-code-point": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz",
- "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=",
+ "p-locate": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz",
+ "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==",
"dev": true,
"requires": {
- "number-is-nan": "^1.0.0"
+ "p-limit": "^2.0.0"
}
},
- "require-main-filename": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz",
- "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=",
+ "path-exists": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz",
+ "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=",
"dev": true
},
"string-width": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
- "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=",
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz",
+ "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==",
"dev": true,
"requires": {
- "code-point-at": "^1.0.0",
- "is-fullwidth-code-point": "^1.0.0",
- "strip-ansi": "^3.0.0"
+ "emoji-regex": "^7.0.1",
+ "is-fullwidth-code-point": "^2.0.0",
+ "strip-ansi": "^5.1.0"
}
},
"strip-ansi": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
- "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
- "dev": true,
- "requires": {
- "ansi-regex": "^2.0.0"
- }
- },
- "which-module": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/which-module/-/which-module-1.0.0.tgz",
- "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=",
- "dev": true
- },
- "wrap-ansi": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz",
- "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=",
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz",
+ "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==",
"dev": true,
"requires": {
- "string-width": "^1.0.1",
- "strip-ansi": "^3.0.1"
+ "ansi-regex": "^4.1.0"
}
},
- "y18n": {
- "version": "3.2.1",
- "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz",
- "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=",
- "dev": true
- },
"yargs": {
- "version": "6.6.0",
- "resolved": "https://registry.npmjs.org/yargs/-/yargs-6.6.0.tgz",
- "integrity": "sha1-eC7CHvQDNF+DCoCMo9UTr1YGUgg=",
+ "version": "13.3.0",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.0.tgz",
+ "integrity": "sha512-2eehun/8ALW8TLoIl7MVaRUrg+yCnenu8B4kBlRxj3GJGDKU1Og7sMXPNm1BYyM1DOJmTZ4YeN/Nwxv+8XJsUA==",
"dev": true,
"requires": {
- "camelcase": "^3.0.0",
- "cliui": "^3.2.0",
- "decamelize": "^1.1.1",
- "get-caller-file": "^1.0.1",
- "os-locale": "^1.4.0",
- "read-pkg-up": "^1.0.1",
+ "cliui": "^5.0.0",
+ "find-up": "^3.0.0",
+ "get-caller-file": "^2.0.1",
"require-directory": "^2.1.1",
- "require-main-filename": "^1.0.1",
+ "require-main-filename": "^2.0.0",
"set-blocking": "^2.0.0",
- "string-width": "^1.0.2",
- "which-module": "^1.0.0",
- "y18n": "^3.2.1",
- "yargs-parser": "^4.2.0"
- }
- },
- "yargs-parser": {
- "version": "4.2.1",
- "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-4.2.1.tgz",
- "integrity": "sha1-KczqwNxPA8bIe0qfIX3RjJ90hxw=",
- "dev": true,
- "requires": {
- "camelcase": "^3.0.0"
+ "string-width": "^3.0.0",
+ "which-module": "^2.0.0",
+ "y18n": "^4.0.0",
+ "yargs-parser": "^13.1.1"
}
}
}
@@ -15238,9 +14414,9 @@
}
},
"lodash": {
- "version": "4.17.15",
- "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz",
- "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==",
+ "version": "4.17.20",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz",
+ "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==",
"dev": true
},
"lodash._reinterpolate": {
@@ -17664,15 +16840,6 @@
"integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=",
"dev": true
},
- "os-locale": {
- "version": "1.4.0",
- "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz",
- "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=",
- "dev": true,
- "requires": {
- "lcid": "^1.0.0"
- }
- },
"os-tmpdir": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
@@ -23193,16 +22360,14 @@
"has-ansi": "^2.0.0",
"strip-ansi": "^3.0.0",
"supports-color": "^2.0.0"
- },
- "dependencies": {
- "escape-string-regexp": {
- "version": "1.0.5",
- "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
- "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=",
- "dev": true
- }
}
},
+ "escape-string-regexp": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
+ "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=",
+ "dev": true
+ },
"strip-ansi": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
@@ -23426,6 +22591,26 @@
"integrity": "sha512-gVweAectJU3ebq//Ferr2JUY4WKSDe5N+z0FvjDncLGyHmIDoxgY/2Ie4qfEIDm4IS7OA6Rmdm7pdEEdMcV/xQ==",
"dev": true
},
+ "touch": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz",
+ "integrity": "sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==",
+ "dev": true,
+ "requires": {
+ "nopt": "~1.0.10"
+ },
+ "dependencies": {
+ "nopt": {
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz",
+ "integrity": "sha1-bd0hvSoxQXuScn3Vhfim83YI6+4=",
+ "dev": true,
+ "requires": {
+ "abbrev": "1"
+ }
+ }
+ }
+ },
"tough-cookie": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-3.0.1.tgz",
@@ -23587,9 +22772,9 @@
}
},
"ua-parser-js": {
- "version": "0.7.17",
- "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.17.tgz",
- "integrity": "sha512-uRdSdu1oA1rncCQL7sCj8vSyZkgtL7faaw9Tc9rZ3mGgraQ7+Pdx7w5mnOSF3gw9ZNG6oc+KXfkon3bKuROm0g==",
+ "version": "0.7.21",
+ "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.21.tgz",
+ "integrity": "sha512-+O8/qh/Qj8CgC6eYBVBykMrNtp5Gebn4dlGD/kKXVkJNDwyrAwSIqwz8CDf+tsAIWVycKcku6gIXJ0qwx/ZXaQ==",
"dev": true
},
"uc.micro": {
@@ -23704,6 +22889,18 @@
"integrity": "sha512-ciEWOd9kJ9sgyzP8Sai9VdMDiGeoKjeaovyzIUgGw82o0OW1/LbLD2Cf8Cs6cBrtLQdzElBFOe8veMt/bSC49g==",
"dev": true
},
+ "unexpected-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/unexpected-map/-/unexpected-map-2.0.0.tgz",
+ "integrity": "sha512-Dy5EZ2RNHAh6oNGjKQ5FLWynqdPcCUuV+iDMHsDGQnJscmNX2LHPbG4vrV9p7bpahyeu3j/1LZYKPyBJQ+0Cfw==",
+ "dev": true
+ },
+ "unexpected-set": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/unexpected-set/-/unexpected-set-3.0.0.tgz",
+ "integrity": "sha512-BpSxTQ4pfE4tRILlDALU0YEIzCkbdi6nWNcqKVux63cL1qF0So/XtG+fzfMxGiDHvQ1339CwRZGIzvy5i/ow7Q==",
+ "dev": true
+ },
"unexpected-sinon": {
"version": "10.11.2",
"resolved": "https://registry.npmjs.org/unexpected-sinon/-/unexpected-sinon-10.11.2.tgz",
@@ -26007,12 +25204,6 @@
"string-width": "^2.1.1"
}
},
- "window-size": {
- "version": "0.2.0",
- "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.2.0.tgz",
- "integrity": "sha1-tDFbtCFKPXBY6+7okuE/ok2YsHU=",
- "dev": true
- },
"wipe-node-cache": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/wipe-node-cache/-/wipe-node-cache-2.1.2.tgz",
diff --git a/package.json b/package.json
index 3fb8e4f8..5853a92d 100644
--- a/package.json
+++ b/package.json
@@ -65,7 +65,6 @@
"log-symbols": "4.0.0",
"minimatch": "3.0.4",
"ms": "2.1.2",
- "object.assign": "4.1.0",
"promise.allsettled": "1.0.2",
"serialize-javascript": "4.0.0",
"strip-json-comments": "3.0.1",
@@ -145,8 +144,11 @@
"svgo": "^1.3.2",
"through2": "^4.0.2",
"to-vfile": "^6.1.0",
+ "touch": "^3.1.0",
"unexpected": "^11.14.0",
"unexpected-eventemitter": "^2.2.0",
+ "unexpected-map": "^2.0.0",
+ "unexpected-set": "^3.0.0",
"unexpected-sinon": "^10.11.2",
"update-notifier": "^4.1.0",
"uslug": "^1.0.4",
diff --git a/test/assertions.js b/test/assertions.js
index 3bc72ffa..8dd682d9 100644
--- a/test/assertions.js
+++ b/test/assertions.js
@@ -1,6 +1,7 @@
'use strict';
const {version} = require('../package.json');
+const escapeRe = require('escape-string-regexp');
module.exports = {
name: 'unexpected-mocha-internal',
@@ -10,9 +11,10 @@ module.exports = {
.addType({
name: 'RawResult',
base: 'object',
- identify: function(v) {
+ identify(v) {
return (
- Object.prototype.toString.call(v) === '[object Object]' &&
+ v !== null &&
+ typeof v === 'object' &&
typeof v.output === 'string' &&
'code' in v && // may be null
Array.isArray(v.args)
@@ -20,23 +22,27 @@ module.exports = {
}
})
.addType({
- name: 'JSONRunResult',
+ name: 'JSONResult',
base: 'object',
- identify: function(v) {
+ identify(v) {
return (
- Object.prototype.toString.call(v) === '[object Object]' &&
- Object.prototype.toString.call(v.stats) === '[object Object]' &&
+ v !== null &&
+ typeof v === 'object' &&
+ v.stats !== null &&
+ typeof v.stats === 'object' &&
Array.isArray(v.failures) &&
- typeof v.code === 'number'
+ typeof v.code === 'number' &&
+ typeof v.command === 'string'
);
}
})
.addType({
- name: 'RawRunResult',
+ name: 'SummarizedResult',
base: 'object',
- identify: function(v) {
+ identify(v) {
return (
- Object.prototype.toString.call(v) === '[object Object]' &&
+ v !== null &&
+ typeof v === 'object' &&
typeof v.passing === 'number' &&
typeof v.failing === 'number' &&
typeof v.pending === 'number' &&
@@ -46,8 +52,8 @@ module.exports = {
}
})
.addAssertion(
- '<JSONRunResult> [not] to have (passed|succeeded)',
- function(expect, result) {
+ '<JSONResult> [not] to have (passed|succeeded)',
+ (expect, result) => {
expect(result, 'to satisfy', {
code: expect.it('[not] to be', 0),
stats: {
@@ -58,37 +64,34 @@ module.exports = {
}
)
.addAssertion(
- '<RawRunResult|RawResult> [not] to have (passed|succeeded)',
- function(expect, result) {
+ '<SummarizedResult|RawResult> [not] to have (passed|succeeded)',
+ (expect, result) => {
expect(result, '[not] to have property', 'code', 0);
}
)
.addAssertion(
- '<RawRunResult|JSONRunResult> [not] to have completed with [exit] code <number>',
- function(expect, result, code) {
+ '<SummarizedResult|JSONResult> [not] to have completed with [exit] code <number>',
+ (expect, result, code) => {
expect(result.code, '[not] to be', code);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have passed (with|having) count <number>',
- function(expect, result, count) {
+ '<JSONResult> [not] to have passed (with|having) count <number>',
+ (expect, result, count) => {
expect(result, '[not] to pass').and('[not] to satisfy', {
stats: {passes: expect.it('to be', count)}
});
}
)
.addAssertion(
- '<JSONRunResult> [not] to have failed (with|having) count <number>',
- function(expect, result, count) {
+ '<JSONResult> [not] to have failed (with|having) count <number>',
+ (expect, result, count) => {
expect(result, '[not] to have failed').and('[not] to satisfy', {
stats: {failures: expect.it('to be', count)}
});
}
)
- .addAssertion('<JSONRunResult> [not] to have failed', function(
- expect,
- result
- ) {
+ .addAssertion('<JSONResult> [not] to have failed', (expect, result) => {
expect(result, '[not] to satisfy', {
code: expect.it('to be greater than', 0),
stats: {
@@ -97,17 +100,17 @@ module.exports = {
failures: expect.it('to be non-empty')
});
})
- .addAssertion('<RawRunResult|RawResult> [not] to have failed', function(
- expect,
- result
- ) {
- expect(result, '[not] to satisfy', {
- code: expect.it('to be greater than', 0)
- });
- })
.addAssertion(
- '<RawRunResult|RawResult> [not] to have failed (with|having) output <any>',
- function(expect, result, output) {
+ '<SummarizedResult|RawResult> [not] to have failed',
+ (expect, result) => {
+ expect(result, '[not] to satisfy', {
+ code: expect.it('to be greater than', 0)
+ });
+ }
+ )
+ .addAssertion(
+ '<SummarizedResult|RawResult> [not] to have failed (with|having) output <any>',
+ (expect, result, output) => {
expect(result, '[not] to satisfy', {
code: expect.it('to be greater than', 0),
output: output
@@ -115,8 +118,8 @@ module.exports = {
}
)
.addAssertion(
- '<RawRunResult|RawResult> [not] to have passed (with|having) output <any>',
- function(expect, result, output) {
+ '<SummarizedResult|RawResult> [not] to have passed (with|having) output <any>',
+ (expect, result, output) => {
expect(result, '[not] to satisfy', {
code: 0,
output: output
@@ -124,51 +127,51 @@ module.exports = {
}
)
.addAssertion(
- '<RawRunResult> [not] to have failed [test] count <number>',
- function(expect, result, count) {
+ '<SummarizedResult> [not] to have failed [test] count <number>',
+ (expect, result, count) => {
expect(result.failing, '[not] to be', count);
}
)
.addAssertion(
- '<RawRunResult> [not] to have passed [test] count <number>',
- function(expect, result, count) {
+ '<SummarizedResult> [not] to have passed [test] count <number>',
+ (expect, result, count) => {
expect(result.passing, '[not] to be', count);
}
)
.addAssertion(
- '<RawRunResult> [not] to have pending [test] count <number>',
- function(expect, result, count) {
+ '<SummarizedResult> [not] to have pending [test] count <number>',
+ (expect, result, count) => {
expect(result.pending, '[not] to be', count);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have test count <number>',
- function(expect, result, count) {
+ '<JSONResult> [not] to have test count <number>',
+ (expect, result, count) => {
expect(result.stats.tests, '[not] to be', count);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have failed [test] count <number>',
- function(expect, result, count) {
+ '<JSONResult> [not] to have failed [test] count <number>',
+ (expect, result, count) => {
expect(result.stats.failures, '[not] to be', count);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have passed [test] count <number>',
- function(expect, result, count) {
+ '<JSONResult> [not] to have passed [test] count <number>',
+ (expect, result, count) => {
expect(result.stats.passes, '[not] to be', count);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have pending [test] count <number>',
- function(expect, result, count) {
+ '<JSONResult> [not] to have pending [test] count <number>',
+ (expect, result, count) => {
expect(result.stats.pending, '[not] to be', count);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have run (test|tests) <string+>',
- function(expect, result, titles) {
- Array.prototype.slice.call(arguments, 2).forEach(function(title) {
+ '<JSONResult> [not] to have run (test|tests) <string+>',
+ (expect, result, ...titles) => {
+ titles.forEach(title => {
expect(
result,
'[not] to have a value satisfying',
@@ -178,9 +181,9 @@ module.exports = {
}
)
.addAssertion(
- '<JSONRunResult> [not] to have failed (test|tests) <string+>',
- function(expect, result, titles) {
- Array.prototype.slice.call(arguments, 2).forEach(function(title) {
+ '<JSONResult> [not] to have failed (test|tests) <string+>',
+ (expect, result, ...titles) => {
+ titles.forEach(title => {
expect(result.failures, '[not] to have an item satisfying', {
title: title
});
@@ -188,23 +191,9 @@ module.exports = {
}
)
.addAssertion(
- '<JSONRunResult> [not] to have failed with (error|errors) <any+>',
- function(expect, result, errors) {
- Array.prototype.slice.call(arguments, 2).forEach(function(error) {
- expect(result, '[not] to have failed').and('[not] to satisfy', {
- failures: expect.it('to have an item satisfying', {
- err: expect
- .it('to satisfy', error)
- .or('to satisfy', {message: error})
- })
- });
- });
- }
- )
- .addAssertion(
- '<JSONRunResult> [not] to have (error|errors) <any+>',
- function(expect, result, errors) {
- Array.prototype.slice.call(arguments, 2).forEach(function(error) {
+ '<JSONResult> [not] to have (error|errors) <any+>',
+ (expect, result, ...errors) => {
+ errors.forEach(error => {
expect(result, '[not] to satisfy', {
failures: expect.it('to have an item satisfying', {
err: expect
@@ -216,9 +205,9 @@ module.exports = {
}
)
.addAssertion(
- '<JSONRunResult> [not] to have passed (test|tests) <string+>',
- function(expect, result, titles) {
- Array.prototype.slice.call(arguments, 2).forEach(function(title) {
+ '<JSONResult> [not] to have passed (test|tests) <string+>',
+ (expect, result, ...titles) => {
+ titles.forEach(title => {
expect(result.passes, '[not] to have an item satisfying', {
title: title
});
@@ -226,95 +215,77 @@ module.exports = {
}
)
.addAssertion(
- '<JSONRunResult> [not] to have test order <string> <array>',
- function(expect, result, state, titles) {
+ '<JSONResult> [not] to have test order <string> <array>',
+ (expect, result, state, titles) => {
expect(
result[state].slice(0, titles.length),
'[not] to satisfy',
- titles.map(function(title) {
+ titles.map(title => {
return typeof title === 'string' ? {title: title} : title;
})
);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have passed test order <array>',
- function(expect, result, titles) {
+ '<JSONResult> [not] to have passed test order <array>',
+ (expect, result, titles) => {
expect(result, '[not] to have test order', 'passes', titles);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have passed test order <string+>',
- function(expect, result, titles) {
- expect(
- result,
- '[not] to have test order',
- 'passes',
- Array.prototype.slice.call(arguments, 2)
- );
+ '<JSONResult> [not] to have passed test order <string+>',
+ (expect, result, ...titles) => {
+ expect(result, '[not] to have test order', 'passes', titles);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have failed test order <array>',
- function(expect, result, titles) {
+ '<JSONResult> [not] to have failed test order <array>',
+ (expect, result, titles) => {
expect(result, '[not] to have test order', 'failures', titles);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have failed test order <string+>',
- function(expect, result, titles) {
- expect(
- result,
- '[not] to have test order',
- 'failures',
- Array.prototype.slice.call(arguments, 2)
- );
+ '<JSONResult> [not] to have failed test order <string+>',
+ (expect, result, ...titles) => {
+ expect(result, '[not] to have test order', 'failures', titles);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have pending test order <array>',
- function(expect, result, titles) {
+ '<JSONResult> [not] to have pending test order <array>',
+ (expect, result, titles) => {
expect(result, '[not] to have test order', 'pending', titles);
}
)
.addAssertion(
- '<JSONRunResult> [not] to have pending test order <string+>',
- function(expect, result, titles) {
- expect(
- result,
- '[not] to have test order',
- 'pending',
- Array.prototype.slice.call(arguments, 2)
- );
+ '<JSONResult> [not] to have pending test order <string+>',
+ (expect, result, ...titles) => {
+ expect(result, '[not] to have test order', 'pending', titles);
}
)
- .addAssertion('<JSONRunResult> [not] to have pending tests', function(
- expect,
- result
- ) {
- expect(result.stats.pending, '[not] to be greater than', 0);
- })
- .addAssertion('<JSONRunResult> [not] to have passed tests', function(
- expect,
- result
- ) {
- expect(result.stats.passes, '[not] to be greater than', 0);
- })
- .addAssertion('<JSONRunResult> [not] to have failed tests', function(
- expect,
- result
- ) {
- expect(result.stats.failed, '[not] to be greater than', 0);
- })
- .addAssertion('<JSONRunResult> [not] to have tests', function(
- expect,
- result
- ) {
+ .addAssertion(
+ '<JSONResult> [not] to have pending tests',
+ (expect, result) => {
+ expect(result.stats.pending, '[not] to be greater than', 0);
+ }
+ )
+ .addAssertion(
+ '<JSONResult> [not] to have passed tests',
+ (expect, result) => {
+ expect(result.stats.passes, '[not] to be greater than', 0);
+ }
+ )
+ .addAssertion(
+ '<JSONResult> [not] to have failed tests',
+ (expect, result) => {
+ expect(result.stats.failed, '[not] to be greater than', 0);
+ }
+ )
+ .addAssertion('<JSONResult> [not] to have tests', (expect, result) => {
expect(result.stats.tests, '[not] to be greater than', 0);
})
.addAssertion(
- '<JSONRunResult> [not] to have retried test <string>',
- function(expect, result, title) {
+ '<JSONResult> [not] to have retried test <string>',
+ (expect, result, title) => {
expect(result.tests, '[not] to have an item satisfying', {
title: title,
currentRetry: expect.it('to be positive')
@@ -322,8 +293,8 @@ module.exports = {
}
)
.addAssertion(
- '<JSONRunResult> [not] to have retried test <string> <number>',
- function(expect, result, title, count) {
+ '<JSONResult> [not] to have retried test <string> <number>',
+ (expect, result, title, count) => {
expect(result.tests, '[not] to have an item satisfying', {
title: title,
currentRetry: count
@@ -331,14 +302,40 @@ module.exports = {
}
)
.addAssertion(
- '<RawResult|RawRunResult> [not] to contain [output] <any>',
- function(expect, result, output) {
+ '<JSONResult> [not] to have failed with (error|errors) <any+>',
+ function(expect, result, ...errors) {
+ errors.forEach(error => {
+ expect(result, '[not] to have failed').and('[not] to satisfy', {
+ failures: expect.it('to have an item satisfying', {
+ err: expect
+ .it('to satisfy', error)
+ .or('to satisfy', {message: error})
+ })
+ });
+ });
+ }
+ )
+ .addAssertion(
+ '<RawResult|SummarizedResult> [not] to contain [output] <any>',
+ (expect, result, output) => {
expect(result.output, '[not] to satisfy', output);
}
)
.addAssertion(
- '<RawResult|RawRunResult|JSONRunResult> to have [exit] code <number>',
- function(expect, result, code) {
+ '<RawResult|SummarizedResult> to contain [output] once <any>',
+ (expect, result, output) => {
+ if (typeof output === 'string') {
+ output = escapeRe(output);
+ } else if (!(output instanceof RegExp)) {
+ throw new TypeError('expected a string or regexp');
+ }
+ output = new RegExp(output, 'g');
+ expect(result.output.match(output), 'to have length', 1);
+ }
+ )
+ .addAssertion(
+ '<RawResult|SummarizedResult|JSONResult> to have [exit] code <number>',
+ (expect, result, code) => {
expect(result.code, 'to be', code);
}
);
diff --git a/test/browser-specific/setup.js b/test/browser-specific/setup.js
index 6809f3b2..61134666 100644
--- a/test/browser-specific/setup.js
+++ b/test/browser-specific/setup.js
@@ -4,5 +4,7 @@ process.stdout = require('browser-stdout')();
global.expect = require('unexpected')
.clone()
+ .use(require('unexpected-set'))
+ .use(require('unexpected-map'))
.use(require('unexpected-sinon'))
.use(require('unexpected-eventemitter'));
diff --git a/test/integration/fixtures/deprecate.fixture.js b/test/integration/fixtures/deprecate.fixture.js
index cf988846..031ad74a 100644
--- a/test/integration/fixtures/deprecate.fixture.js
+++ b/test/integration/fixtures/deprecate.fixture.js
@@ -1,9 +1,9 @@
'use strict';
-var utils = require("../../../lib/utils");
+var errors = require("../../../lib/errors");
it('consolidates identical calls to deprecate', function() {
- utils.deprecate("suite foo did a deprecated thing");
- utils.deprecate("suite foo did a deprecated thing");
- utils.deprecate("suite bar did a deprecated thing");
+ errors.deprecate("suite foo did a deprecated thing");
+ errors.deprecate("suite foo did a deprecated thing");
+ errors.deprecate("suite bar did a deprecated thing");
});
diff --git a/test/integration/fixtures/plugins/global-fixtures/global-setup-teardown-multiple.fixture.js b/test/integration/fixtures/plugins/global-fixtures/global-setup-teardown-multiple.fixture.js
new file mode 100644
index 00000000..9ae6805e
--- /dev/null
+++ b/test/integration/fixtures/plugins/global-fixtures/global-setup-teardown-multiple.fixture.js
@@ -0,0 +1,20 @@
+'use strict';
+
+exports.mochaGlobalSetup = [
+ async function() {
+ this.foo = 0;
+ },
+ function() {
+ this.foo = this.foo + 1;
+ }
+];
+
+exports.mochaGlobalTeardown = [
+ async function() {
+ this.foo = this.foo + 1;
+ },
+ function() {
+ this.foo = this.foo + 1;
+ console.log(`teardown: this.foo = ${this.foo}`);
+ }
+];
diff --git a/test/integration/fixtures/plugins/global-fixtures/global-setup-teardown.fixture.js b/test/integration/fixtures/plugins/global-fixtures/global-setup-teardown.fixture.js
new file mode 100644
index 00000000..aec78c44
--- /dev/null
+++ b/test/integration/fixtures/plugins/global-fixtures/global-setup-teardown.fixture.js
@@ -0,0 +1,10 @@
+'use strict';
+
+exports.mochaGlobalSetup = async function() {
+ this.foo = 'bar';
+ console.log(`setup: this.foo = ${this.foo}`);
+};
+
+exports.mochaGlobalTeardown = async function() {
+ console.log(`teardown: this.foo = ${this.foo}`);
+};
diff --git a/test/integration/fixtures/plugins/global-fixtures/global-setup.fixture.js b/test/integration/fixtures/plugins/global-fixtures/global-setup.fixture.js
new file mode 100644
index 00000000..63e7c2e5
--- /dev/null
+++ b/test/integration/fixtures/plugins/global-fixtures/global-setup.fixture.js
@@ -0,0 +1,6 @@
+'use strict';
+
+exports.mochaGlobalSetup = async function() {
+ console.log(`setup schmetup`);
+};
+
diff --git a/test/integration/fixtures/plugins/global-fixtures/global-teardown.fixture.js b/test/integration/fixtures/plugins/global-fixtures/global-teardown.fixture.js
new file mode 100644
index 00000000..5d37c4f0
--- /dev/null
+++ b/test/integration/fixtures/plugins/global-fixtures/global-teardown.fixture.js
@@ -0,0 +1,5 @@
+'use strict';
+
+exports.mochaGlobalTeardown = async function() {
+ console.log('teardown schmeardown');
+};
diff --git a/test/integration/fixtures/options/require/esm/package.json b/test/integration/fixtures/plugins/root-hooks/esm/package.json
similarity index 100%
rename from test/integration/fixtures/options/require/esm/package.json
rename to test/integration/fixtures/plugins/root-hooks/esm/package.json
diff --git a/test/integration/fixtures/options/require/esm/root-hook-defs-esm.fixture.js b/test/integration/fixtures/plugins/root-hooks/esm/root-hook-defs-esm.fixture.js
similarity index 100%
rename from test/integration/fixtures/options/require/esm/root-hook-defs-esm.fixture.js
rename to test/integration/fixtures/plugins/root-hooks/esm/root-hook-defs-esm.fixture.js
diff --git a/test/integration/fixtures/options/require/root-hook-defs-a.fixture.js b/test/integration/fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js
similarity index 100%
rename from test/integration/fixtures/options/require/root-hook-defs-a.fixture.js
rename to test/integration/fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js
diff --git a/test/integration/fixtures/options/require/root-hook-defs-b.fixture.js b/test/integration/fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js
similarity index 100%
rename from test/integration/fixtures/options/require/root-hook-defs-b.fixture.js
rename to test/integration/fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js
diff --git a/test/integration/fixtures/options/require/root-hook-defs-c.fixture.js b/test/integration/fixtures/plugins/root-hooks/root-hook-defs-c.fixture.js
similarity index 100%
rename from test/integration/fixtures/options/require/root-hook-defs-c.fixture.js
rename to test/integration/fixtures/plugins/root-hooks/root-hook-defs-c.fixture.js
diff --git a/test/integration/fixtures/options/require/root-hook-defs-d.fixture.js b/test/integration/fixtures/plugins/root-hooks/root-hook-defs-d.fixture.js
similarity index 100%
rename from test/integration/fixtures/options/require/root-hook-defs-d.fixture.js
rename to test/integration/fixtures/plugins/root-hooks/root-hook-defs-d.fixture.js
diff --git a/test/integration/fixtures/options/require/root-hook-defs-esm-broken.fixture.js b/test/integration/fixtures/plugins/root-hooks/root-hook-defs-esm-broken.fixture.js
similarity index 100%
rename from test/integration/fixtures/options/require/root-hook-defs-esm-broken.fixture.js
rename to test/integration/fixtures/plugins/root-hooks/root-hook-defs-esm-broken.fixture.js
diff --git a/test/integration/fixtures/options/require/root-hook-defs-esm.fixture.mjs b/test/integration/fixtures/plugins/root-hooks/root-hook-defs-esm.fixture.mjs
similarity index 100%
rename from test/integration/fixtures/options/require/root-hook-defs-esm.fixture.mjs
rename to test/integration/fixtures/plugins/root-hooks/root-hook-defs-esm.fixture.mjs
diff --git a/test/integration/fixtures/options/require/root-hook-test-2.fixture.js b/test/integration/fixtures/plugins/root-hooks/root-hook-test-2.fixture.js
similarity index 100%
rename from test/integration/fixtures/options/require/root-hook-test-2.fixture.js
rename to test/integration/fixtures/plugins/root-hooks/root-hook-test-2.fixture.js
diff --git a/test/integration/fixtures/options/require/root-hook-test.fixture.js b/test/integration/fixtures/plugins/root-hooks/root-hook-test.fixture.js
similarity index 100%
rename from test/integration/fixtures/options/require/root-hook-test.fixture.js
rename to test/integration/fixtures/plugins/root-hooks/root-hook-test.fixture.js
diff --git a/test/integration/helpers.js b/test/integration/helpers.js
index 64752624..5435b1dd 100644
--- a/test/integration/helpers.js
+++ b/test/integration/helpers.js
@@ -1,71 +1,33 @@
'use strict';
-var format = require('util').format;
-var spawn = require('cross-spawn').spawn;
-var path = require('path');
-var Base = require('../../lib/reporters/base');
-var debug = require('debug')('mocha:tests:integration:helpers');
-var DEFAULT_FIXTURE = resolveFixturePath('__default__');
-var MOCHA_EXECUTABLE = require.resolve('../../bin/mocha');
-var _MOCHA_EXECUTABLE = require.resolve('../../bin/_mocha');
+const escapeRegExp = require('escape-string-regexp');
+const os = require('os');
+const fs = require('fs-extra');
+const {format} = require('util');
+const path = require('path');
+const Base = require('../../lib/reporters/base');
+const debug = require('debug')('mocha:tests:integration:helpers');
+const touch = require('touch');
-module.exports = {
- DEFAULT_FIXTURE: DEFAULT_FIXTURE,
-
- /**
- * regular expression used for splitting lines based on new line / dot symbol.
- */
- splitRegExp: new RegExp('[\\n' + Base.symbols.dot + ']+'),
-
- /**
- * Invokes the mocha binary. Accepts an array of additional command line args
- * to pass. The callback is invoked with the exit code and output. Optional
- * current working directory as final parameter.
- *
- * By default, `STDERR` is ignored. Pass `{stdio: 'pipe'}` as `opts` if you
- * want it.
- *
- * In most cases runMocha should be used instead.
- *
- * Example response:
- * {
- * code: 1,
- * output: '...'
- * }
- *
- * @param {Array<string>} args - Extra args to mocha executable
- * @param {Function} done - Callback
- * @param {Object} [opts] - Options for `spawn()`
- */
- invokeMocha: invokeMocha,
-
- invokeMochaAsync: invokeMochaAsync,
-
- invokeNode: invokeNode,
-
- getSummary: getSummary,
+/**
+ * Path to `mocha` executable
+ */
+const MOCHA_EXECUTABLE = require.resolve('../../bin/mocha');
- /**
- * Resolves the path to a fixture to the full path.
- */
- resolveFixturePath: resolveFixturePath,
+/**
+ * regular expression used for splitting lines based on new line / dot symbol.
+ */
+const SPLIT_DOT_REPORTER_REGEXP = new RegExp('[\\n' + Base.symbols.dot + ']+');
- toJSONRunResult: toJSONRunResult,
+/**
+ * Name of "default" fixture file.
+ */
+const DEFAULT_FIXTURE = '__default__';
- /**
- * Given a regexp-like string, escape it so it can be used with the `RegExp` constructor
- * @param {string} str - string to be escaped
- * @returns {string} Escaped string
- */
- escapeRegExp: function escapeRegExp(str) {
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
- },
-
- runMocha: runMocha,
- runMochaJSON: runMochaJSON,
- runMochaAsync: runMochaAsync,
- runMochaJSONAsync: runMochaJSONAsync
-};
+/**
+ * Path to "default" fixture file
+ */
+const DEFAULT_FIXTURE_PATH = resolveFixturePath(DEFAULT_FIXTURE);
/**
* Invokes the mocha binary for the given fixture with color output disabled.
@@ -86,76 +48,65 @@ module.exports = {
* }
*
* @param {string} fixturePath - Path to fixture .js file
- * @param {string[]} args - Extra args to mocha executable
- * @param {Function} fn - Callback
+ * @param {string[]|SummarizedResultCallback} args - Extra args to mocha executable
+ * @param {SummarizedResultCallback|Object} done - Callback
* @param {Object} [opts] - Options for `spawn()`
- * @returns {ChildProcess} Mocha process
+ * @returns {ChildProcess} Subprocess process
*/
-function runMocha(fixturePath, args, fn, opts) {
+function runMocha(fixturePath, args, done, opts = {}) {
if (typeof args === 'function') {
- opts = fn;
- fn = args;
+ opts = done;
+ done = args;
args = [];
}
- var path;
-
- path = resolveFixturePath(fixturePath);
- args = args || [];
-
- return invokeSubMocha(
- args.concat(path),
- function(err, res) {
+ return invokeMocha(
+ [...args, resolveFixturePath(fixturePath)],
+ (err, res) => {
if (err) {
- return fn(err);
+ return done(err);
}
- fn(null, getSummary(res));
+ done(null, getSummary(res));
},
opts
);
}
/**
- * Invokes the mocha binary for the given fixture using the JSON reporter,
- * returning the parsed output, as well as exit code.
+ * Invokes the mocha executable for the given fixture using the `json` reporter,
+ * calling callback `done` with parsed output.
+ *
+ * Use when you expect `mocha` _not_ to fail (test failures OK); the output from
+ * the `json` reporter--and thus the entire subprocess--must be valid JSON!
*
* By default, `STDERR` is ignored. Pass `{stdio: 'pipe'}` as `opts` if you
* want it.
- * @param {string} fixturePath - Path from __dirname__
- * @param {string[]} args - Array of args
- * @param {Function} fn - Callback
+ * @param {string} fixturePath - Path from `__dirname__`
+ * @param {string[]|JSONResultCallback} args - Args to `mocha` or callback
+ * @param {JSONResultCallback|Object} done - Callback or options
* @param {Object} [opts] - Opts for `spawn()`
- * @returns {*} Parsed object
+ * @returns {ChildProcess} Subprocess instance
*/
-function runMochaJSON(fixturePath, args, fn, opts) {
+function runMochaJSON(fixturePath, args, done, opts) {
if (typeof args === 'function') {
- opts = fn;
- fn = args;
+ opts = done;
+ done = args;
args = [];
}
- var path;
-
- path = resolveFixturePath(fixturePath);
- args = (args || []).concat('--reporter', 'json', path);
-
return invokeMocha(
- args,
- function(err, res) {
+ [...args, '--reporter', 'json', resolveFixturePath(fixturePath)],
+ (err, res) => {
if (err) {
- return fn(err);
+ return done(err);
}
- var result;
+ let result;
try {
- // attempt to catch a JSON parsing error *only* here.
- // previously, the callback was called within this `try` block,
- // which would result in errors thrown from the callback
- // getting caught by the `catch` block below.
- result = toJSONRunResult(res);
+ result = toJSONResult(res);
} catch (err) {
- return fn(
+ return done(
new Error(
format(
'Failed to parse JSON reporter output. Error:\n%O\nResult:\n%O',
@@ -165,7 +116,7 @@ function runMochaJSON(fixturePath, args, fn, opts) {
)
);
}
- fn(null, result);
+ done(null, result);
},
opts
);
@@ -202,6 +153,7 @@ function runMochaAsync(fixturePath, args, opts) {
* @param {string} fixturePath - Path to (or name of, or basename of) fixture file
* @param {Options} [args] - Command-line args
* @param {Object} [opts] - Options for `child_process.spawn`
+ * @returns {Promise<JSONResult>}
*/
function runMochaJSONAsync(fixturePath, args, opts) {
return new Promise(function(resolve, reject) {
@@ -220,17 +172,15 @@ function runMochaJSONAsync(fixturePath, args, opts) {
}
/**
- * Coerce output as returned by _spawnMochaWithListeners using JSON reporter into a JSONRunResult as
+ * Coerce output as returned by _spawnMochaWithListeners using JSON reporter into a JSONResult as
* recognized by our custom unexpected assertions
- * @param {string} result - Raw stdout from Mocha run using JSON reporter
- * @private
+ * @param {RawResult} result - Raw stdout from Mocha run using JSON reporter
+ * @returns {JSONResult}
*/
-function toJSONRunResult(result) {
- var code = result.code;
+function toJSONResult(result) {
+ const {code, command, output} = result;
try {
- result = JSON.parse(result.output);
- result.code = code;
- return result;
+ return {...JSON.parse(output), code, command};
} catch (err) {
throw new Error(
`Couldn't parse JSON: ${err.message}\n\nOriginal result output: ${result.output}`
@@ -251,12 +201,13 @@ function toJSONRunResult(result) {
* - The {@link DEFAULT_FIXTURE} file is used if no arguments are provided.
*
* @param {string[]|*} [args] - Arguments to `spawn`
- * @returns string[]
+ * @returns {string[]}
*/
-function defaultArgs(args) {
- var newArgs = (!args || !args.length ? [DEFAULT_FIXTURE] : args).concat([
+function defaultArgs(args = [DEFAULT_FIXTURE_PATH]) {
+ const newArgs = [
+ ...(!args.length ? [DEFAULT_FIXTURE_PATH] : args),
'--no-color'
- ]);
+ ];
if (!newArgs.some(arg => /--(no-)?bail/.test(arg))) {
newArgs.push('--no-bail');
}
@@ -266,15 +217,26 @@ function defaultArgs(args) {
return newArgs;
}
-function invokeMocha(args, fn, opts) {
+/**
+ * Invoke `mocha` with default arguments. Calls `done` upon exit. Does _not_ accept a fixture path.
+ *
+ * Good for testing error conditions. This is low-level, and you likely want
+ * {@link runMocha} or even {@link runMochaJSON} if you are running test fixtures.
+ *
+ * @param {string[]|RawResultCallback} args - Args to `mocha` or callback
+ * @param {RawResultCallback|Object} done - Callback or options
+ * @param {Object} [opts] - Options
+ * @returns {ChildProcess}
+ */
+function invokeMocha(args, done, opts = {}) {
if (typeof args === 'function') {
- opts = fn;
- fn = args;
+ opts = done;
+ done = args;
args = [];
}
- return _spawnMochaWithListeners(
+ return createSubprocess(
defaultArgs([MOCHA_EXECUTABLE].concat(args)),
- fn,
+ done,
opts
);
}
@@ -290,12 +252,12 @@ function invokeMocha(args, fn, opts) {
*
* @param {string[]} args - Array of args
* @param {Object} [opts] - Opts for `spawn()`
- * @returns {[ChildProcess|Promise<Result>]}
+ * @returns {[import('child_process').ChildProcess,Promise<RawResult>]} A tuple of process and result promise
*/
-function invokeMochaAsync(args, opts) {
+function invokeMochaAsync(args, opts = {}) {
let mochaProcess;
const resultPromise = new Promise((resolve, reject) => {
- mochaProcess = _spawnMochaWithListeners(
+ mochaProcess = createSubprocess(
defaultArgs([MOCHA_EXECUTABLE].concat(args)),
(err, result) => {
if (err) {
@@ -311,62 +273,74 @@ function invokeMochaAsync(args, opts) {
}
/**
- * Invokes Node without Mocha binary with the given arguments,
- * when Mocha is used programmatically.
+ * Invokes subprocess with currently-running `node`.
+ *
+ * Useful for running certain fixtures as scripts.
+ *
+ * @param {string[]|RawResultCallback} args - Args to `mocha` or callback
+ * @param {RawResultCallback|Object} done - Callback or options
+ * @param {Object} [opts] - Options
+ * @returns {ChildProcess}
*/
-function invokeNode(args, fn, opts) {
+function invokeNode(args, done, opts = {}) {
if (typeof args === 'function') {
- opts = fn;
- fn = args;
+ opts = done;
+ done = args;
args = [];
}
- return _spawnMochaWithListeners(args, fn, opts);
-}
-
-function invokeSubMocha(args, fn, opts) {
- if (typeof args === 'function') {
- opts = fn;
- fn = args;
- args = [];
- }
- return _spawnMochaWithListeners(
- defaultArgs([_MOCHA_EXECUTABLE].concat(args)),
- fn,
- opts
- );
+ return createSubprocess(args, done, opts);
}
/**
- * Spawns Mocha in a subprocess and returns an object containing its output and exit code
+ * Creates a subprocess and calls callback `done` when it has exited.
+ *
+ * This is the most low-level function and should _not_ be exported.
*
* @param {string[]} args - Path to executable and arguments
- * @param {Function} fn - Callback
- * @param {Object|string} [opts] - Options to `cross-spawn`, or 'pipe' for shortcut to `{stdio: pipe}`
- * @returns {ChildProcess}
- * @private
+ * @param {RawResultCallback} done - Callback
+ * @param {Object|string} [opts] - Options to `cross-spawn` or `child_process.fork` or 'pipe' for shortcut to `{stdio: pipe}`
+ * @param {boolean} [opts.fork] - If `true`, use `child_process.fork` instead
+ * @returns {import('child_process').ChildProcess}
*/
-function _spawnMochaWithListeners(args, fn, opts) {
- var output = '';
- opts = opts || {};
+function createSubprocess(args, done, opts = {}) {
+ let output = '';
+
if (opts === 'pipe') {
opts = {stdio: ['inherit', 'pipe', 'pipe']};
}
- var env = Object.assign({}, process.env);
+
+ const env = {...process.env};
// prevent DEBUG from borking STDERR when piping, unless explicitly set via `opts`
delete env.DEBUG;
- opts = Object.assign(
- {
- cwd: process.cwd(),
- stdio: ['inherit', 'pipe', 'inherit'],
- env: env
- },
- opts
- );
+ opts = {
+ cwd: process.cwd(),
+ stdio: ['inherit', 'pipe', 'inherit'],
+ env,
+ ...opts
+ };
- debug('spawning: %s', [process.execPath].concat(args).join(' '));
- var mocha = spawn(process.execPath, args, opts);
- var listener = function(data) {
+ /**
+ * @type {import('child_process').ChildProcess}
+ */
+ let mocha;
+ if (opts.fork) {
+ const {fork} = require('child_process');
+ // to use ipc, we need a fourth item in `stdio` array.
+ // opts.stdio is usually an array of length 3, but it could be smaller
+ // (pad with `null`)
+ for (let i = opts.stdio.length; i < 4; i++) {
+ opts.stdio.push(i === 3 ? 'ipc' : null);
+ }
+ debug('forking: %s', args.join(' '));
+ mocha = fork(args[0], args.slice(1), opts);
+ } else {
+ const {spawn} = require('cross-spawn');
+ debug('spawning: %s', [process.execPath].concat(args).join(' '));
+ mocha = spawn(process.execPath, args, opts);
+ }
+
+ const listener = data => {
output += data;
};
@@ -374,13 +348,13 @@ function _spawnMochaWithListeners(args, fn, opts) {
if (mocha.stderr) {
mocha.stderr.on('data', listener);
}
- mocha.on('error', fn);
+ mocha.on('error', done);
- mocha.on('close', function(code) {
- fn(null, {
- output: output,
- code: code,
- args: args,
+ mocha.on('close', code => {
+ done(null, {
+ output,
+ code,
+ args,
command: args.join(' ')
});
});
@@ -388,13 +362,19 @@ function _spawnMochaWithListeners(args, fn, opts) {
return mocha;
}
+/**
+ * Given a fixture "name" (a relative path from `${__dirname}/fixtures`),
+ * with or without extension, or an absolute path, resolve a fixture filepath
+ * @param {string} fixture - Fixture name
+ * @returns {string} Resolved filepath
+ */
function resolveFixturePath(fixture) {
if (path.extname(fixture) !== '.js' && path.extname(fixture) !== '.mjs') {
fixture += '.fixture.js';
}
return path.isAbsolute(fixture)
? fixture
- : path.join('test', 'integration', 'fixtures', fixture);
+ : path.resolve(__dirname, 'fixtures', fixture);
}
/**
@@ -414,6 +394,171 @@ function getSummary(res) {
}, res);
}
+/**
+ * Runs the mocha executable in watch mode calls `change` and returns the
+ * raw result.
+ *
+ * The function starts mocha with the given arguments and `--watch` and
+ * waits until the first test run has completed. Then it calls `change`
+ * and waits until the second test run has been completed. Mocha is
+ * killed and the result is returned.
+ *
+ * On Windows, this will call `child_process.fork()` instead of `cross-spawn.spawn()`.
+ *
+ * **Exit code will always be 0**
+ * @param {string[]} args - Array of argument strings
+ * @param {object|string} opts - If a `string`, then `cwd`, otherwise options for `cross-spawn.spawn` or `child_process.fork`
+ * @param {Function} change - A potentially `Promise`-returning callback to execute which will change a watched file
+ * @returns {Promise<RawResult>}
+ */
+async function runMochaWatchAsync(args, opts, change) {
+ if (typeof opts === 'string') {
+ opts = {cwd: opts};
+ }
+ opts = {sleepMs: 2000, ...opts, fork: process.platform === 'win32'};
+ opts.stdio = ['pipe', 'pipe', 'inherit'];
+ const [mochaProcess, resultPromise] = invokeMochaAsync(
+ [...args, '--watch'],
+ opts
+ );
+ await sleep(opts.sleepMs);
+ await change(mochaProcess);
+ await sleep(opts.sleepMs);
+
+ if (
+ !(mochaProcess.connected
+ ? mochaProcess.send('SIGINT')
+ : mochaProcess.kill('SIGINT'))
+ ) {
+ throw new Error('failed to send signal to subprocess');
+ }
+
+ const res = await resultPromise;
+
+ // we kill the process with `SIGINT`, so it will always appear as "failed" to our
+ // custom assertions (a non-zero exit code 130). just change it to 0.
+ res.code = 0;
+ return res;
+}
+
+/**
+ * Runs the mocha executable in watch mode calls `change` and returns the
+ * JSON result.
+ *
+ * The function starts mocha with the given arguments and `--watch` and
+ * waits until the first test run has completed. Then it calls `change`
+ * and waits until the second test run has been completed. Mocha is
+ * killed and the result is returned.
+ *
+ * On Windows, this will call `child_process.fork()` instead of `cross-spawn.spawn()`.
+ *
+ * **Exit code will always be 0**
+ * @param {string[]} args - Array of argument strings
+ * @param {object|string} opts - If a `string`, then `cwd`, otherwise options for `cross-spawn.spawn` or `child_process.fork`
+ * @param {Function} change - A potentially `Promise`-returning callback to execute which will change a watched file
+ * @returns {Promise<JSONResult>}
+ */
+async function runMochaWatchJSONAsync(args, opts, change) {
+ const res = await runMochaWatchAsync(
+ [...args, '--reporter', 'json'],
+ opts,
+ change
+ );
+ return (
+ res.output
+ // eslint-disable-next-line no-control-regex
+ .replace(/\u001b\[\?25./g, '')
+ .split('\u001b[2K')
+ .map(x => JSON.parse(x))
+ );
+}
+
+/**
+ * Synchronously touch a file. Creates
+ * the file and all its parent directories if necessary.
+ *
+ * @param {string} filepath - Path to file
+ */
+function touchFile(filepath) {
+ fs.ensureDirSync(path.dirname(filepath));
+ touch.sync(filepath);
+}
+
+/**
+ * Synchronously replace all substrings matched by `pattern` with
+ * `replacement` in the contents of file at `filepath`
+ *
+ * @param {string} filepath - Path to file
+ * @param {RegExp|string} pattern - Search pattern
+ * @param {string} replacement - Replacement
+ */
+function replaceFileContents(filepath, pattern, replacement) {
+ const contents = fs.readFileSync(filepath, 'utf-8');
+ const newContents = contents.replace(pattern, replacement);
+ fs.writeFileSync(filepath, newContents, 'utf-8');
+}
+
+/**
+ * Synchronously copy a fixture to the given destination file path.
+ * Creates parent directories of the destination path if necessary.
+ *
+ * @param {string} fixtureName - Relative path from __dirname to fixture, or absolute path
+ * @param {*} dest - Destination directory
+ */
+function copyFixture(fixtureName, dest) {
+ const fixtureSource = resolveFixturePath(fixtureName);
+ fs.ensureDirSync(path.dirname(dest));
+ fs.copySync(fixtureSource, dest);
+}
+
+/**
+ * Creates a temporary directory
+ * @returns {Promise<CreateTempDirResult>} Temp dir path and cleanup function
+ */
+const createTempDir = async () => {
+ const dirpath = await fs.mkdtemp(path.join(os.tmpdir(), 'mocha-'));
+ return {
+ dirpath,
+ removeTempDir: async () => {
+ return fs.remove(dirpath);
+ }
+ };
+};
+
+/**
+ * Waits for `time` ms.
+ * @param {number} time - Time in ms
+ * @returns {Promise<void>}
+ */
+function sleep(time) {
+ return new Promise(resolve => {
+ setTimeout(resolve, time);
+ });
+}
+
+module.exports = {
+ DEFAULT_FIXTURE,
+ SPLIT_DOT_REPORTER_REGEXP,
+
+ createTempDir,
+ invokeMocha,
+ invokeMochaAsync,
+ invokeNode,
+ getSummary,
+ resolveFixturePath,
+ toJSONResult,
+ escapeRegExp,
+ runMocha,
+ runMochaJSON,
+ runMochaAsync,
+ runMochaJSONAsync,
+ runMochaWatchAsync,
+ runMochaWatchJSONAsync,
+ copyFixture,
+ touchFile,
+ replaceFileContents
+};
+
/**
* A summary of a `mocha` run
* @typedef {Object} Summary
@@ -421,3 +566,66 @@ function getSummary(res) {
* @property {number} pending - Number of pending tests
* @property {number} failing - Number of failing tests
*/
+
+/**
+ * An unprocessed result from a `mocha` run
+ * @typedef {Object} RawResult
+ * @property {string} output - Process output; _usually_ just stdout
+ * @property {number?} code - Exit code or `null` in some circumstances
+ * @property {string[]} args - Array of program arguments
+ * @property {string} command - Complete command executed
+ */
+
+/**
+ * The result of a `mocha` run using `json` reporter
+ * @typedef {Object} JSONResult
+ * @property {Object} stats - Statistics
+ * @property {Object[]} failures - Failure information
+ * @property {number?} code - Exit code or `null` in some circumstances
+ * @property {string} command - Complete command executed
+ */
+
+/**
+ * The result of a `mocha` run using `spec` reporter (parsed)
+ * @typedef {Summary} SummarizedResult
+ * @property {string} output - Process output; _usually_ just stdout
+ * @property {number?} code - Exit code or `null` in some circumstances
+ */
+
+/**
+ * Callback function run when `mocha` process execution complete
+ * @callback RawResultCallback
+ * @param {Error?} err - Error, if any
+ * @param {RawResult} result - Result of `mocha` run
+ * @returns {void}
+ */
+
+/**
+ * Callback function run when `mocha` process execution complete
+ * @callback JSONResultCallback
+ * @param {Error?} err - Error, if any
+ * @param {JSONResult} result - Result of `mocha` run
+ * @returns {void}
+ */
+
+/**
+ * Callback function run when `mocha` process execution complete
+ * @callback SummarizedResultCallback
+ * @param {Error?} err - Error, if any
+ * @param {SummarizedResult} result - Result of `mocha` run
+ * @returns {void}
+ */
+
+/**
+ * Return value when calling {@link createTempDir}
+ *
+ * @typedef {Object} CreateTempDirResult
+ * @property {string} dirname - Path of new temp dir
+ * @property {RemoveTempDirCallback} removeTempDir - "Cleanup" function to remove temp dir
+ */
+
+/**
+ * Cleanup function to remove temp dir
+ * @callback RemoveTempDirCallback
+ * @returns {void}
+ */
diff --git a/test/integration/hook-err.spec.js b/test/integration/hook-err.spec.js
index d5fe6e85..ad327dfc 100644
--- a/test/integration/hook-err.spec.js
+++ b/test/integration/hook-err.spec.js
@@ -3,7 +3,7 @@
var helpers = require('./helpers');
var runMocha = helpers.runMocha;
var runMochaJSON = require('./helpers').runMochaJSON;
-var splitRegExp = helpers.splitRegExp;
+var SPLIT_DOT_REPORTER_REGEXP = helpers.SPLIT_DOT_REPORTER_REGEXP;
var bang = require('../../lib/reporters/base').symbols.bang;
describe('hook error handling', function() {
@@ -263,7 +263,7 @@ describe('hook error handling', function() {
expect(err, 'to be falsy');
lines = res.output
- .split(splitRegExp)
+ .split(SPLIT_DOT_REPORTER_REGEXP)
.map(function(line) {
return line.trim();
})
diff --git a/test/integration/hooks.spec.js b/test/integration/hooks.spec.js
index 7c3e8bf2..727ce115 100644
--- a/test/integration/hooks.spec.js
+++ b/test/integration/hooks.spec.js
@@ -3,7 +3,7 @@
var assert = require('assert');
var runMocha = require('./helpers').runMocha;
var runMochaJSON = require('./helpers').runMochaJSON;
-var splitRegExp = require('./helpers').splitRegExp;
+var SPLIT_DOT_REPORTER_REGEXP = require('./helpers').SPLIT_DOT_REPORTER_REGEXP;
var args = ['--reporter', 'dot'];
describe('hooks', function() {
@@ -17,7 +17,7 @@ describe('hooks', function() {
}
lines = res.output
- .split(splitRegExp)
+ .split(SPLIT_DOT_REPORTER_REGEXP)
.map(function(line) {
return line.trim();
})
diff --git a/test/integration/multiple-runs.spec.js b/test/integration/multiple-runs.spec.js
index 61d672d4..25528143 100644
--- a/test/integration/multiple-runs.spec.js
+++ b/test/integration/multiple-runs.spec.js
@@ -1,14 +1,17 @@
'use strict';
-var invokeNode = require('./helpers').invokeNode;
+const {invokeNode} = require('./helpers');
-describe('multiple runs', function(done) {
+describe('multiple runs', function() {
it('should be allowed to run multiple times if cleanReferences is turned off', function(done) {
var path = require.resolve(
'./fixtures/multiple-runs/run-thrice.fixture.js'
);
invokeNode([path], function(err, res) {
- expect(err, 'to be null');
+ if (err) {
+ done(err);
+ return;
+ }
expect(res.code, 'to be', 0);
var results = JSON.parse(res.output);
expect(results, 'to have length', 3);
@@ -32,9 +35,15 @@ describe('multiple runs', function(done) {
invokeNode(
[path],
function(err, res) {
- expect(err, 'to be null');
- expect(res.code, 'not to be', 0);
- expect(res.output, 'to contain', 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED');
+ if (err) {
+ done(err);
+ return;
+ }
+ expect(res, 'to have failed').and(
+ 'to contain output',
+ /ERR_MOCHA_INSTANCE_ALREADY_DISPOSED/
+ );
+
done();
},
{stdio: ['ignore', 'pipe', 'pipe']}
@@ -46,7 +55,10 @@ describe('multiple runs', function(done) {
invokeNode(
[path, '--directly-dispose'],
function(err, res) {
- expect(err, 'to be null');
+ if (err) {
+ done(err);
+ return;
+ }
expect(res.code, 'not to be', 0);
expect(res.output, 'to contain', 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED');
done();
@@ -62,7 +74,10 @@ describe('multiple runs', function(done) {
invokeNode(
[path],
function(err, res) {
- expect(err, 'to be null');
+ if (err) {
+ done(err);
+ return;
+ }
expect(res.output, 'to contain', 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING');
done();
},
diff --git a/test/integration/options/extension.spec.js b/test/integration/options/extension.spec.js
index 760e3bcd..56e40f6b 100644
--- a/test/integration/options/extension.spec.js
+++ b/test/integration/options/extension.spec.js
@@ -2,7 +2,7 @@
var helpers = require('../helpers');
var invokeMocha = helpers.invokeMocha;
-var toJSONRunResult = helpers.toJSONRunResult;
+var toJSONResult = helpers.toJSONResult;
describe('--extension', function() {
it('should allow comma-separated variables', function(done) {
@@ -21,7 +21,7 @@ describe('--extension', function() {
if (err) {
return done(err);
}
- expect(toJSONRunResult(res), 'to have passed').and(
+ expect(toJSONResult(res), 'to have passed').and(
'to have passed test count',
2
);
diff --git a/test/integration/options/watch.spec.js b/test/integration/options/watch.spec.js
index 822b28b6..0211ca25 100644
--- a/test/integration/options/watch.spec.js
+++ b/test/integration/options/watch.spec.js
@@ -1,30 +1,44 @@
'use strict';
const fs = require('fs-extra');
-const os = require('os');
const path = require('path');
-const helpers = require('../helpers');
+const {
+ copyFixture,
+ runMochaWatchJSONAsync,
+ touchFile,
+ replaceFileContents,
+ createTempDir,
+ DEFAULT_FIXTURE
+} = require('../helpers');
describe('--watch', function() {
describe('when enabled', function() {
+ /**
+ * @type {string}
+ */
let tempDir;
+ /**
+ * @type {import('../helpers').RemoveTempDirCallback}
+ */
+ let cleanup;
+
this.slow(5000);
- beforeEach(function() {
- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mocha-'));
+ beforeEach(async function() {
+ const {dirpath, removeTempDir} = await createTempDir();
+ tempDir = dirpath;
+ cleanup = removeTempDir;
});
afterEach(function() {
- if (tempDir) {
- return fs.remove(tempDir);
- }
+ cleanup();
});
it('reruns test when watched test file is touched', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
- return runMochaWatch([testFile], tempDir, () => {
+ return runMochaWatchJSONAsync([testFile], tempDir, () => {
touchFile(testFile);
}).then(results => {
expect(results, 'to have length', 2);
@@ -34,9 +48,9 @@ describe('--watch', function() {
describe('when in parallel mode', function() {
it('reruns test when watched test file is touched', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
- return runMochaWatch(['--parallel', testFile], tempDir, () => {
+ return runMochaWatchJSONAsync(['--parallel', testFile], tempDir, () => {
touchFile(testFile);
}).then(results => {
expect(results, 'to have length', 2);
@@ -46,12 +60,12 @@ describe('--watch', function() {
it('reruns test when file matching --watch-files changes', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
const watchedFile = path.join(tempDir, 'dir/file.xyz');
touchFile(watchedFile);
- return runMochaWatch(
+ return runMochaWatchJSONAsync(
[testFile, '--watch-files', 'dir/*.xyz'],
tempDir,
() => {
@@ -64,10 +78,10 @@ describe('--watch', function() {
it('reruns test when file matching --watch-files is added', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
const watchedFile = path.join(tempDir, 'lib/file.xyz');
- return runMochaWatch(
+ return runMochaWatchJSONAsync(
[testFile, '--watch-files', '**/*.xyz'],
tempDir,
() => {
@@ -80,12 +94,12 @@ describe('--watch', function() {
it('reruns test when file matching --watch-files is removed', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
const watchedFile = path.join(tempDir, 'lib/file.xyz');
touchFile(watchedFile);
- return runMochaWatch(
+ return runMochaWatchJSONAsync(
[testFile, '--watch-files', 'lib/**/*.xyz'],
tempDir,
() => {
@@ -98,12 +112,12 @@ describe('--watch', function() {
it('does not rerun test when file not matching --watch-files is changed', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
const watchedFile = path.join(tempDir, 'dir/file.js');
touchFile(watchedFile);
- return runMochaWatch(
+ return runMochaWatchJSONAsync(
[testFile, '--watch-files', 'dir/*.xyz'],
tempDir,
() => {
@@ -116,9 +130,9 @@ describe('--watch', function() {
it('picks up new test files when they are added', function() {
const testFile = path.join(tempDir, 'test/a.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
- return runMochaWatch(
+ return runMochaWatchJSONAsync(
['test/**/*.js', '--watch-files', 'test/**/*.js'],
tempDir,
() => {
@@ -134,23 +148,27 @@ describe('--watch', function() {
it('reruns test when file matching --extension is changed', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
const watchedFile = path.join(tempDir, 'file.xyz');
touchFile(watchedFile);
- return runMochaWatch([testFile, '--extension', 'xyz,js'], tempDir, () => {
- touchFile(watchedFile);
- }).then(results => {
+ return runMochaWatchJSONAsync(
+ [testFile, '--extension', 'xyz,js'],
+ tempDir,
+ () => {
+ touchFile(watchedFile);
+ }
+ ).then(results => {
expect(results, 'to have length', 2);
});
});
it('reruns when "rs\\n" typed', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
- return runMochaWatch([testFile], tempDir, mochaProcess => {
+ return runMochaWatchJSONAsync([testFile], tempDir, mochaProcess => {
mochaProcess.stdin.write('rs\n');
}).then(results => {
expect(results, 'to have length', 2);
@@ -159,21 +177,25 @@ describe('--watch', function() {
it('reruns test when file starting with . and matching --extension is changed', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
const watchedFile = path.join(tempDir, '.file.xyz');
touchFile(watchedFile);
- return runMochaWatch([testFile, '--extension', 'xyz,js'], tempDir, () => {
- touchFile(watchedFile);
- }).then(results => {
+ return runMochaWatchJSONAsync(
+ [testFile, '--extension', 'xyz,js'],
+ tempDir,
+ () => {
+ touchFile(watchedFile);
+ }
+ ).then(results => {
expect(results, 'to have length', 2);
});
});
it('ignores files in "node_modules" and ".git" by default', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
const nodeModulesFile = path.join(tempDir, 'node_modules', 'file.xyz');
const gitFile = path.join(tempDir, '.git', 'file.xyz');
@@ -181,22 +203,26 @@ describe('--watch', function() {
touchFile(gitFile);
touchFile(nodeModulesFile);
- return runMochaWatch([testFile, '--extension', 'xyz,js'], tempDir, () => {
- touchFile(gitFile);
- touchFile(nodeModulesFile);
- }).then(results => {
+ return runMochaWatchJSONAsync(
+ [testFile, '--extension', 'xyz,js'],
+ tempDir,
+ () => {
+ touchFile(gitFile);
+ touchFile(nodeModulesFile);
+ }
+ ).then(results => {
expect(results, 'to have length', 1);
});
});
it('ignores files matching --watch-ignore', function() {
const testFile = path.join(tempDir, 'test.js');
- copyFixture('__default__', testFile);
+ copyFixture(DEFAULT_FIXTURE, testFile);
const watchedFile = path.join(tempDir, 'dir/file-to-ignore.xyz');
touchFile(watchedFile);
- return runMochaWatch(
+ return runMochaWatchJSONAsync(
[
testFile,
'--watch-files',
@@ -217,7 +243,7 @@ describe('--watch', function() {
const testFile = path.join(tempDir, 'test.js');
copyFixture('options/watch/test-file-change', testFile);
- return runMochaWatch(
+ return runMochaWatchJSONAsync(
[testFile, '--watch-files', '**/*.js'],
tempDir,
() => {
@@ -243,7 +269,7 @@ describe('--watch', function() {
const dependency = path.join(tempDir, 'lib', 'dependency.js');
copyFixture('options/watch/dependency', dependency);
- return runMochaWatch(
+ return runMochaWatchJSONAsync(
[testFile, '--watch-files', 'lib/**/*.js'],
tempDir,
() => {
@@ -263,17 +289,22 @@ describe('--watch', function() {
});
// Regression test for https://github.com/mochajs/mocha/issues/2027
- it('respects --fgrep on re-runs', function() {
+ it('respects --fgrep on re-runs', async function() {
const testFile = path.join(tempDir, 'test.js');
copyFixture('options/grep', testFile);
- return runMochaWatch([testFile, '--fgrep', 'match'], tempDir, () => {
- touchFile(testFile);
- }).then(results => {
- expect(results, 'to have length', 2);
- expect(results[0].tests, 'to have length', 2);
- expect(results[1].tests, 'to have length', 2);
- });
+ return expect(
+ runMochaWatchJSONAsync([testFile, '--fgrep', 'match'], tempDir, () => {
+ touchFile(testFile);
+ }),
+ 'when fulfilled',
+ 'to satisfy',
+ {
+ length: 2,
+ 0: {tests: expect.it('to have length', 2)},
+ 1: {tests: expect.it('to have length', 2)}
+ }
+ );
});
describe('with required hooks', function() {
@@ -293,7 +324,7 @@ describe('--watch', function() {
replaceFileContents(hookFile, '<hook>', hookName);
- return runMochaWatch(
+ return runMochaWatchJSONAsync(
[testFile, '--require', hookFile],
tempDir,
() => {
@@ -314,70 +345,3 @@ describe('--watch', function() {
});
});
});
-
-/**
- * Runs the mocha binary in watch mode calls `change` and returns the
- * JSON reporter output.
- *
- * The function starts mocha with the given arguments and `--watch` and
- * waits until the first test run has completed. Then it calls `change`
- * and waits until the second test run has been completed. Mocha is
- * killed and the list of JSON outputs is returned.
- */
-function runMochaWatch(args, cwd, change) {
- const [mochaProcess, resultPromise] = helpers.invokeMochaAsync(
- [...args, '--watch', '--reporter', 'json'],
- {cwd, stdio: ['pipe', 'pipe', 'inherit']}
- );
-
- return sleep(2000)
- .then(() => change(mochaProcess))
- .then(() => sleep(2000))
- .then(() => {
- mochaProcess.kill('SIGINT');
- return resultPromise;
- })
- .then(data => {
- const testResults = data.output
- // eslint-disable-next-line no-control-regex
- .replace(/\u001b\[\?25./g, '')
- .split('\u001b[2K')
- .map(x => JSON.parse(x));
- return testResults;
- });
-}
-
-/**
- * Synchronously touch a file by appending a space to the end. Creates
- * the file and all its parent directories if necessary.
- */
-function touchFile(file) {
- fs.ensureDirSync(path.dirname(file));
- fs.appendFileSync(file, ' ');
-}
-
-/**
- * Synchronously replace all substrings matched by `pattern` with
- * `replacement` in the file’s content.
- */
-function replaceFileContents(file, pattern, replacement) {
- const contents = fs.readFileSync(file, 'utf-8');
- const newContents = contents.replace(pattern, replacement);
- fs.writeFileSync(file, newContents, 'utf-8');
-}
-
-/**
- * Synchronously copy a fixture to the given destination file path.
- * Creates parent directories of the destination path if necessary.
- */
-function copyFixture(fixtureName, dest) {
- const fixtureSource = helpers.resolveFixturePath(fixtureName);
- fs.ensureDirSync(path.dirname(dest));
- fs.copySync(fixtureSource, dest);
-}
-
-function sleep(time) {
- return new Promise(resolve => {
- setTimeout(resolve, time);
- });
-}
diff --git a/test/integration/pending.spec.js b/test/integration/pending.spec.js
index 51a7bc9b..5fe75f7c 100644
--- a/test/integration/pending.spec.js
+++ b/test/integration/pending.spec.js
@@ -4,7 +4,7 @@ var assert = require('assert');
var helpers = require('./helpers');
var run = helpers.runMochaJSON;
var invokeNode = helpers.invokeNode;
-var toJSONRunResult = helpers.toJSONRunResult;
+var toJSONResult = helpers.toJSONResult;
var args = [];
describe('pending', function() {
@@ -305,7 +305,7 @@ describe('pending', function() {
if (err) {
return done(err);
}
- var result = toJSONRunResult(res);
+ var result = toJSONResult(res);
expect(result, 'to have passed')
.and('to have passed test count', 0)
.and('to have pending test count', 1)
diff --git a/test/integration/plugins/global-fixtures.spec.js b/test/integration/plugins/global-fixtures.spec.js
new file mode 100644
index 00000000..5e3acb1a
--- /dev/null
+++ b/test/integration/plugins/global-fixtures.spec.js
@@ -0,0 +1,293 @@
+'use strict';
+
+const path = require('path');
+const {
+ touchFile,
+ runMochaAsync,
+ runMochaWatchAsync,
+ copyFixture,
+ DEFAULT_FIXTURE,
+ resolveFixturePath,
+ createTempDir
+} = require('../helpers');
+
+describe('global setup/teardown', function() {
+ describe('when mocha run in serial mode', function() {
+ it('should execute global setup and teardown', async function() {
+ return expect(
+ runMochaAsync(DEFAULT_FIXTURE, [
+ '--require',
+ resolveFixturePath('plugins/global-fixtures/global-setup-teardown')
+ ]),
+ 'when fulfilled',
+ 'to have passed'
+ );
+ });
+
+ describe('when only global teardown is supplied', function() {
+ it('should run global teardown', async function() {
+ return expect(
+ runMochaAsync(DEFAULT_FIXTURE, [
+ '--require',
+ resolveFixturePath('plugins/global-fixtures/global-teardown')
+ ]),
+ 'when fulfilled',
+ 'to contain once',
+ /teardown schmeardown/
+ );
+ });
+ });
+
+ describe('when only global setup is supplied', function() {
+ it('should run global setup', async function() {
+ return expect(
+ runMochaAsync(DEFAULT_FIXTURE, [
+ '--require',
+ resolveFixturePath('plugins/global-fixtures/global-setup')
+ ]),
+ 'when fulfilled',
+ 'to contain once',
+ /setup schmetup/
+ );
+ });
+ });
+
+ it('should share context', async function() {
+ return expect(
+ runMochaAsync(DEFAULT_FIXTURE, [
+ '--require',
+ resolveFixturePath('plugins/global-fixtures/global-setup-teardown')
+ ]),
+ 'when fulfilled',
+ 'to contain once',
+ /setup: this\.foo = bar[\s\S]+teardown: this\.foo = bar/
+ );
+ });
+
+ describe('when supplied multiple functions', function() {
+ it('should execute them sequentially', async function() {
+ return expect(
+ runMochaAsync(DEFAULT_FIXTURE, [
+ '--require',
+ resolveFixturePath(
+ 'plugins/global-fixtures/global-setup-teardown-multiple'
+ )
+ ]),
+ 'when fulfilled',
+ 'to contain once',
+ /teardown: this.foo = 3/
+ );
+ });
+ });
+
+ describe('when run in watch mode', function() {
+ let tempDir;
+ let testFile;
+ let removeTempDir;
+
+ beforeEach(async function() {
+ const tempInfo = await createTempDir();
+ tempDir = tempInfo.dirpath;
+ removeTempDir = tempInfo.removeTempDir;
+ testFile = path.join(tempDir, 'test.js');
+ copyFixture(DEFAULT_FIXTURE, testFile);
+ });
+
+ afterEach(async function() {
+ if (removeTempDir) {
+ return removeTempDir();
+ }
+ });
+
+ it('should execute global setup and teardown', async function() {
+ return expect(
+ runMochaWatchAsync(
+ [
+ '--require',
+ resolveFixturePath(
+ 'plugins/global-fixtures/global-setup-teardown'
+ ),
+ testFile
+ ],
+ tempDir,
+ () => {
+ touchFile(testFile);
+ }
+ ),
+ 'when fulfilled',
+ 'to have passed'
+ );
+ });
+
+ describe('when only global teardown is supplied', function() {
+ it('should run global teardown', async function() {
+ return expect(
+ runMochaWatchAsync(
+ [
+ '--require',
+ resolveFixturePath('plugins/global-fixtures/global-teardown'),
+ testFile
+ ],
+ tempDir,
+ () => {
+ touchFile(testFile);
+ }
+ ),
+ 'when fulfilled',
+ 'to contain once',
+ /teardown schmeardown/
+ );
+ });
+ });
+
+ describe('when only global setup is supplied', function() {
+ it('should run global setup', async function() {
+ return expect(
+ runMochaWatchAsync(
+ [
+ '--require',
+ resolveFixturePath('plugins/global-fixtures/global-setup'),
+ testFile
+ ],
+ tempDir,
+ () => {
+ touchFile(testFile);
+ }
+ ),
+ 'when fulfilled',
+ 'to contain once',
+ /setup schmetup/
+ );
+ });
+ });
+
+ it('should not re-execute the global fixtures', async function() {
+ return expect(
+ runMochaWatchAsync(
+ [
+ '--require',
+ resolveFixturePath(
+ 'plugins/global-fixtures/global-setup-teardown-multiple'
+ ),
+ testFile
+ ],
+ tempDir,
+ () => {
+ touchFile(testFile);
+ }
+ ),
+ 'when fulfilled',
+ 'to contain once',
+ /teardown: this.foo = 3/
+ );
+ });
+ });
+ });
+
+ describe('when mocha run in parallel mode', function() {
+ it('should execute global setup and teardown', async function() {
+ return expect(
+ runMochaAsync(DEFAULT_FIXTURE, [
+ '--parallel',
+ '--require',
+ resolveFixturePath('plugins/global-fixtures/global-setup-teardown')
+ ]),
+ 'when fulfilled',
+ 'to have passed'
+ );
+ });
+
+ it('should share context', async function() {
+ return expect(
+ runMochaAsync(DEFAULT_FIXTURE, [
+ '--parallel',
+ '--require',
+ resolveFixturePath('plugins/global-fixtures/global-setup-teardown')
+ ]),
+ 'when fulfilled',
+ 'to contain once',
+ /setup: this.foo = bar/
+ ).and('when fulfilled', 'to contain once', /teardown: this.foo = bar/);
+ });
+
+ describe('when supplied multiple functions', function() {
+ it('should execute them sequentially', async function() {
+ return expect(
+ runMochaAsync(DEFAULT_FIXTURE, [
+ '--parallel',
+ '--require',
+ resolveFixturePath(
+ 'plugins/global-fixtures/global-setup-teardown-multiple'
+ )
+ ]),
+ 'when fulfilled',
+ 'to contain once',
+ /teardown: this.foo = 3/
+ );
+ });
+ });
+
+ describe('when run in watch mode', function() {
+ let tempDir;
+ let testFile;
+ let removeTempDir;
+
+ beforeEach(async function() {
+ const tempInfo = await createTempDir();
+ tempDir = tempInfo.dirpath;
+ removeTempDir = tempInfo.removeTempDir;
+ testFile = path.join(tempDir, 'test.js');
+ copyFixture(DEFAULT_FIXTURE, testFile);
+ });
+
+ afterEach(async function() {
+ if (removeTempDir) {
+ return removeTempDir();
+ }
+ });
+
+ it('should execute global setup and teardown', async function() {
+ return expect(
+ runMochaWatchAsync(
+ [
+ '--parallel',
+ '--require',
+ resolveFixturePath(
+ 'plugins/global-fixtures/global-setup-teardown'
+ ),
+ testFile
+ ],
+ tempDir,
+ () => {
+ touchFile(testFile);
+ }
+ ),
+ 'when fulfilled',
+ 'to have passed'
+ );
+ });
+
+ it('should not re-execute the global fixtures', async function() {
+ return expect(
+ runMochaWatchAsync(
+ [
+ '--parallel',
+ '--require',
+ resolveFixturePath(
+ 'plugins/global-fixtures/global-setup-teardown-multiple'
+ ),
+ testFile
+ ],
+ tempDir,
+ () => {
+ touchFile(testFile);
+ }
+ ),
+ 'when fulfilled',
+ 'to contain once',
+ /teardown: this.foo = 3/
+ );
+ });
+ });
+ });
+});
diff --git a/test/integration/options/require.spec.js b/test/integration/plugins/root-hooks.spec.js
similarity index 81%
rename from test/integration/options/require.spec.js
rename to test/integration/plugins/root-hooks.spec.js
index 21da366b..53d18d58 100644
--- a/test/integration/options/require.spec.js
+++ b/test/integration/plugins/root-hooks.spec.js
@@ -30,21 +30,21 @@ function runMochaForHookOutput(args, opts) {
return invokeMochaAsync(args, opts)[1].then(extractHookOutputFromResult);
}
-describe('--require', function() {
+describe('root hooks', function() {
describe('when mocha run in serial mode', function() {
it('should run root hooks when provided via mochaHooks object export', function() {
return expect(
runMochaForHookOutput([
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-a.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js'
),
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-b.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js'
),
require.resolve(
- '../fixtures/options/require/root-hook-test.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
)
]),
'to be fulfilled with',
@@ -70,14 +70,14 @@ describe('--require', function() {
runMochaForHookOutput([
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-c.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-c.fixture.js'
),
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-d.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-d.fixture.js'
),
require.resolve(
- '../fixtures/options/require/root-hook-test.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
)
]),
'to be fulfilled with',
@@ -110,20 +110,20 @@ describe('--require', function() {
'--require=' +
require.resolve(
// as object
- '../fixtures/options/require/root-hook-defs-esm.fixture.mjs'
+ '../fixtures/plugins/root-hooks/root-hook-defs-esm.fixture.mjs'
),
'--require=' +
require.resolve(
// as function
- '../fixtures/options/require/esm/root-hook-defs-esm.fixture.js'
+ '../fixtures/plugins/root-hooks/esm/root-hook-defs-esm.fixture.js'
),
'--require=' +
require.resolve(
// mixed with commonjs
- '../fixtures/options/require/root-hook-defs-a.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js'
),
require.resolve(
- '../fixtures/options/require/root-hook-test.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
)
].concat(
+process.versions.node.split('.')[0] >= 13
@@ -158,7 +158,7 @@ describe('--require', function() {
'--require=' +
require.resolve(
// as object
- '../fixtures/options/require/root-hook-defs-esm-broken.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-esm-broken.fixture.js'
)
].concat(
+process.versions.node.split('.')[0] >= 13
@@ -181,15 +181,15 @@ describe('--require', function() {
runMochaForHookOutput([
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-a.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js'
),
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-b.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js'
),
'--parallel',
require.resolve(
- '../fixtures/options/require/root-hook-test.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
)
]),
'to be fulfilled with',
@@ -215,15 +215,15 @@ describe('--require', function() {
runMochaForHookOutput([
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-c.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-c.fixture.js'
),
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-d.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-d.fixture.js'
),
'--parallel',
require.resolve(
- '../fixtures/options/require/root-hook-test.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
)
]),
'to be fulfilled with',
@@ -250,18 +250,18 @@ describe('--require', function() {
runMochaForHookOutput([
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-a.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js'
),
'--require=' +
require.resolve(
- '../fixtures/options/require/root-hook-defs-b.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js'
),
'--parallel',
require.resolve(
- '../fixtures/options/require/root-hook-test.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
),
require.resolve(
- '../fixtures/options/require/root-hook-test-2.fixture.js'
+ '../fixtures/plugins/root-hooks/root-hook-test-2.fixture.js'
)
]),
'to be fulfilled with',
diff --git a/test/integration/retries.spec.js b/test/integration/retries.spec.js
index e076595d..bb5ae518 100644
--- a/test/integration/retries.spec.js
+++ b/test/integration/retries.spec.js
@@ -20,7 +20,7 @@ describe('retries', function() {
}
lines = res.output
- .split(helpers.splitRegExp)
+ .split(helpers.SPLIT_DOT_REPORTER_REGEXP)
.map(function(line) {
return line.trim();
})
@@ -102,7 +102,7 @@ describe('retries', function() {
}
lines = res.output
- .split(helpers.splitRegExp)
+ .split(helpers.SPLIT_DOT_REPORTER_REGEXP)
.map(function(line) {
return line.trim();
})
diff --git a/test/node-unit/cli/run-helpers.spec.js b/test/node-unit/cli/run-helpers.spec.js
index 3169bbd0..e12b97b8 100644
--- a/test/node-unit/cli/run-helpers.spec.js
+++ b/test/node-unit/cli/run-helpers.spec.js
@@ -1,76 +1,13 @@
'use strict';
-const {
- validatePlugin,
- list,
- loadRootHooks
-} = require('../../../lib/cli/run-helpers');
+const {validateLegacyPlugin, list} = require('../../../lib/cli/run-helpers');
describe('helpers', function() {
- describe('loadRootHooks()', function() {
- describe('when passed nothing', function() {
- it('should reject', async function() {
- return expect(loadRootHooks(), 'to be rejected');
- });
- });
-
- describe('when passed empty array of hooks', function() {
- it('should return an empty MochaRootHooks object', async function() {
- return expect(loadRootHooks([]), 'to be fulfilled with', {
- beforeAll: [],
- beforeEach: [],
- afterAll: [],
- afterEach: []
- });
- });
- });
-
- describe('when passed an array containing hook objects and sync functions and async functions', function() {
- it('should flatten them into a single object', async function() {
- function a() {}
- function b() {}
- function d() {}
- function g() {}
- async function f() {}
- function c() {
- return {
- beforeAll: d,
- beforeEach: g
- };
- }
- async function e() {
- return {
- afterEach: f
- };
- }
- return expect(
- loadRootHooks([
- {
- beforeEach: a
- },
- {
- afterAll: b
- },
- c,
- e
- ]),
- 'to be fulfilled with',
- {
- beforeAll: [d],
- beforeEach: [a, g],
- afterAll: [b],
- afterEach: [f]
- }
- );
- });
- });
- });
-
- describe('validatePlugin()', function() {
+ describe('validateLegacyPlugin()', function() {
describe('when used with "reporter" key', function() {
it('should disallow an array of names', function() {
expect(
- () => validatePlugin({reporter: ['bar']}, 'reporter'),
+ () => validateLegacyPlugin({reporter: ['bar']}, 'reporter'),
'to throw',
{
code: 'ERR_MOCHA_INVALID_REPORTER',
@@ -81,7 +18,7 @@ describe('helpers', function() {
it('should fail to recognize an unknown reporter', function() {
expect(
- () => validatePlugin({reporter: 'bar'}, 'reporter'),
+ () => validateLegacyPlugin({reporter: 'bar'}, 'reporter'),
'to throw',
{code: 'ERR_MOCHA_INVALID_REPORTER', message: /cannot find module/i}
);
@@ -91,7 +28,7 @@ describe('helpers', function() {
describe('when used with an "interfaces" key', function() {
it('should disallow an array of names', function() {
expect(
- () => validatePlugin({interface: ['bar']}, 'interface'),
+ () => validateLegacyPlugin({interface: ['bar']}, 'interface'),
'to throw',
{
code: 'ERR_MOCHA_INVALID_INTERFACE',
@@ -102,7 +39,7 @@ describe('helpers', function() {
it('should fail to recognize an unknown interface', function() {
expect(
- () => validatePlugin({interface: 'bar'}, 'interface'),
+ () => validateLegacyPlugin({interface: 'bar'}, 'interface'),
'to throw',
{code: 'ERR_MOCHA_INVALID_INTERFACE', message: /cannot find module/i}
);
@@ -112,7 +49,7 @@ describe('helpers', function() {
describe('when used with an unknown plugin type', function() {
it('should fail', function() {
expect(
- () => validatePlugin({frog: 'bar'}, 'frog'),
+ () => validateLegacyPlugin({frog: 'bar'}, 'frog'),
'to throw',
/unknown plugin/i
);
@@ -123,7 +60,7 @@ describe('helpers', function() {
it('should fail and report the original error', function() {
expect(
() =>
- validatePlugin(
+ validateLegacyPlugin(
{
reporter: require.resolve('./fixtures/bad-module.fixture.js')
},
diff --git a/test/node-unit/mocha.spec.js b/test/node-unit/mocha.spec.js
index b5fc04d2..49ae9037 100644
--- a/test/node-unit/mocha.spec.js
+++ b/test/node-unit/mocha.spec.js
@@ -5,7 +5,6 @@ const rewiremock = require('rewiremock/node');
const sinon = require('sinon');
const {EventEmitter} = require('events');
-const MODULE_PATH = require.resolve('../../lib/mocha.js');
const DUMB_FIXTURE_PATH = require.resolve('./fixtures/dumb-module.fixture.js');
const DUMBER_FIXTURE_PATH = require.resolve(
'./fixtures/dumber-module.fixture.js'
@@ -20,9 +19,20 @@ describe('Mocha', function() {
opts = {reporter: sinon.stub()};
stubs = {};
+ stubs.errors = {
+ warn: sinon.stub(),
+ createMochaInstanceAlreadyDisposedError: sinon
+ .stub()
+ .throws({code: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED'}),
+ createInvalidReporterError: sinon
+ .stub()
+ .throws({code: 'ERR_MOCHA_INVALID_REPORTER'}),
+ createUnsupportedError: sinon
+ .stub()
+ .throws({code: 'ERR_MOCHA_UNSUPPORTED'})
+ };
stubs.utils = {
supportsEsModules: sinon.stub().returns(false),
- warn: sinon.stub(),
isString: sinon.stub(),
noop: sinon.stub(),
cwd: sinon.stub().returns(process.cwd()),
@@ -37,12 +47,9 @@ describe('Mocha', function() {
});
stubs.Suite = sinon.stub().returns(stubs.suite);
stubs.Suite.constants = {};
- stubs.BufferedRunner = sinon.stub().returns({});
+ stubs.ParallelBufferedRunner = sinon.stub().returns({});
const runner = Object.assign(sinon.createStubInstance(EventEmitter), {
- run: sinon
- .stub()
- .callsArgAsync(0)
- .returnsThis(),
+ runAsync: sinon.stub().resolves(0),
globals: sinon.stub(),
grep: sinon.stub(),
dispose: sinon.stub()
@@ -52,12 +59,17 @@ describe('Mocha', function() {
// we don't need the constants themselves, but the object cannot be undefined
stubs.Runner.constants = {};
- Mocha = rewiremock.proxy(MODULE_PATH, r => ({
- '../../lib/utils.js': r.with(stubs.utils).callThrough(),
- '../../lib/suite.js': stubs.Suite,
- '../../lib/nodejs/parallel-buffered-runner.js': stubs.BufferedRunner,
- '../../lib/runner.js': stubs.Runner
- }));
+ Mocha = rewiremock.proxy(
+ () => require('../../lib/mocha'),
+ r => ({
+ '../../lib/utils.js': r.with(stubs.utils).callThrough(),
+ '../../lib/suite.js': stubs.Suite,
+ '../../lib/nodejs/parallel-buffered-runner.js':
+ stubs.ParallelBufferedRunner,
+ '../../lib/runner.js': stubs.Runner,
+ '../../lib/errors.js': stubs.errors
+ })
+ );
delete require.cache[DUMB_FIXTURE_PATH];
delete require.cache[DUMBER_FIXTURE_PATH];
});
@@ -84,14 +96,14 @@ describe('Mocha', function() {
describe('when parallel mode is already enabled', function() {
beforeEach(function() {
mocha.options.parallel = true;
- mocha._runnerClass = stubs.BufferedRunner;
+ mocha._runnerClass = stubs.ParallelBufferedRunner;
mocha._lazyLoadFiles = true;
});
it('should not swap the Runner, nor change lazy loading setting', function() {
expect(mocha.parallelMode(true), 'to satisfy', {
options: {parallel: true},
- _runnerClass: stubs.BufferedRunner,
+ _runnerClass: stubs.ParallelBufferedRunner,
_lazyLoadFiles: true
});
});
@@ -122,13 +134,14 @@ describe('Mocha', function() {
describe('when `Mocha` instance is in `INIT` state', function() {
beforeEach(function() {
mocha._state = 'init';
- // this is broken
- this.skip();
});
it('should enable parallel mode', function() {
+ // FIXME: the dynamic require() call breaks the mock of
+ // `ParallelBufferedRunner` and returns the real class.
+ // don't know how to make this work or if it's even possible
expect(mocha.parallelMode(true), 'to satisfy', {
- _runnerClass: stubs.BufferedRunner,
+ _runnerClass: expect.it('not to be', Mocha.Runner),
options: {
parallel: true
},
@@ -144,7 +157,7 @@ describe('Mocha', function() {
it('should throw', function() {
expect(
- function() {
+ () => {
mocha.parallelMode(true);
},
'to throw',
@@ -259,7 +272,7 @@ describe('Mocha', function() {
);
} catch (ignored) {
} finally {
- expect(stubs.utils.warn, 'to have a call satisfying', [
+ expect(stubs.errors.warn, 'to have a call satisfying', [
expect.it('to match', /reporter blew up/)
]);
}
@@ -296,7 +309,7 @@ describe('Mocha', function() {
);
} catch (ignored) {
} finally {
- expect(stubs.utils.warn, 'to have a call satisfying', [
+ expect(stubs.errors.warn, 'to have a call satisfying', [
expect.it('to match', /reporter blew up/)
]);
}
@@ -320,7 +333,7 @@ describe('Mocha', function() {
mocha.unloadFiles();
},
'to throw',
- 'Mocha instance is already disposed, it cannot be used again.'
+ {code: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED'}
);
});
});
diff --git a/test/node-unit/worker.spec.js b/test/node-unit/worker.spec.js
index 8d46ef49..48a62cd8 100644
--- a/test/node-unit/worker.spec.js
+++ b/test/node-unit/worker.spec.js
@@ -54,16 +54,20 @@ describe('worker', function() {
};
stubs.runHelpers = {
- handleRequires: sinon.stub(),
- validatePlugin: sinon.stub(),
- loadRootHooks: sinon.stub().resolves()
+ handleRequires: sinon.stub().resolves({}),
+ validateLegacyPlugin: sinon.stub()
+ };
+
+ stubs.plugin = {
+ aggregateRootHooks: sinon.stub().resolves()
};
worker = rewiremock.proxy(WORKER_PATH, {
workerpool: stubs.workerpool,
'../../lib/mocha': stubs.Mocha,
'../../lib/nodejs/serializer': stubs.serializer,
- '../../lib/cli/run-helpers': stubs.runHelpers
+ '../../lib/cli/run-helpers': stubs.runHelpers,
+ '../../lib/plugin-loader': stubs.plugin
});
});
@@ -146,7 +150,10 @@ describe('worker', function() {
expect(
stubs.runHelpers.handleRequires,
'to have a call satisfying',
- ['foo']
+ [
+ 'foo',
+ {ignoredPlugins: ['mochaGlobalSetup', 'mochaGlobalTeardown']}
+ ]
).and('was called once');
});
@@ -155,7 +162,7 @@ describe('worker', function() {
await worker.run('some-file.js', serializeJavascript(argv));
expect(
- stubs.runHelpers.validatePlugin,
+ stubs.runHelpers.validateLegacyPlugin,
'to have a call satisfying',
[argv, 'ui', stubs.Mocha.interfaces]
).and('was called once');
@@ -173,6 +180,13 @@ describe('worker', function() {
]);
});
+ it('should remove all unhandledRejection listeners', async function() {
+ await worker.run('some-file.js');
+ expect(process.removeAllListeners, 'to have a call satisfying', [
+ 'unhandledRejection'
+ ]);
+ });
+
describe('when serialization succeeds', function() {
beforeEach(function() {
stubs.serializer.serialize.returnsArg(0);
@@ -204,7 +218,7 @@ describe('worker', function() {
expect(stubs.runHelpers, 'to satisfy', {
handleRequires: expect.it('was called once'),
- validatePlugin: expect.it('was called once')
+ validateLegacyPlugin: expect.it('was called once')
});
});
});
diff --git a/test/reporters/xunit.spec.js b/test/reporters/xunit.spec.js
index f3dfe21e..1d3bad9c 100644
--- a/test/reporters/xunit.spec.js
+++ b/test/reporters/xunit.spec.js
@@ -2,15 +2,15 @@
var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
-var os = require('os');
var path = require('path');
-var rimraf = require('rimraf');
var sinon = require('sinon');
var createStatsCollector = require('../../lib/stats-collector');
var events = require('../../').Runner.constants;
var reporters = require('../../').reporters;
var states = require('../../').Runnable.constants;
+const {createTempDir, touchFile} = require('../integration/helpers');
+
var Base = reporters.Base;
var XUnit = reporters.XUnit;
@@ -81,15 +81,21 @@ describe('XUnit reporter', function() {
describe('when fileStream cannot be created', function() {
describe('when given an invalid pathname', function() {
- var tmpdir;
+ /**
+ * @type {string}
+ */
+ let tmpdir;
+
+ /**
+ * @type {import('../integration/helpers').RemoveTempDirCallback}
+ */
+ let cleanup;
var invalidPath;
- beforeEach(function createInvalidPath() {
- tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), 'mocha-test-'));
-
- function touch(filename) {
- fs.closeSync(fs.openSync(filename, 'w'));
- }
+ beforeEach(async function() {
+ const {dirpath, removeTempDir} = await createTempDir();
+ tmpdir = dirpath;
+ cleanup = removeTempDir;
// Create path where file 'some-file' used as directory
invalidPath = path.join(
@@ -97,7 +103,7 @@ describe('XUnit reporter', function() {
'some-file',
path.basename(expectedOutput)
);
- touch(path.dirname(invalidPath));
+ touchFile(path.dirname(invalidPath));
});
it('should throw system error', function() {
@@ -119,7 +125,7 @@ describe('XUnit reporter', function() {
});
afterEach(function() {
- rimraf.sync(tmpdir);
+ cleanup();
});
});
diff --git a/test/setup.js b/test/setup.js
index 58bda9cb..a979858a 100644
--- a/test/setup.js
+++ b/test/setup.js
@@ -6,4 +6,6 @@ global.expect = unexpected
.clone()
.use(require('unexpected-sinon'))
.use(require('unexpected-eventemitter'))
+ .use(require('unexpected-map'))
+ .use(require('unexpected-set'))
.use(require('./assertions'));
diff --git a/test/unit/errors.spec.js b/test/unit/errors.spec.js
index 3c1adee5..4d28a042 100644
--- a/test/unit/errors.spec.js
+++ b/test/unit/errors.spec.js
@@ -1,8 +1,13 @@
'use strict';
var errors = require('../../lib/errors');
+const sinon = require('sinon');
describe('Errors', function() {
+ afterEach(function() {
+ sinon.restore();
+ });
+
var message = 'some message';
describe('createInvalidReporterError()', function() {
@@ -62,4 +67,80 @@ describe('Errors', function() {
});
});
});
+
+ describe('deprecate()', function() {
+ var emitWarning;
+
+ beforeEach(function() {
+ if (process.emitWarning) {
+ emitWarning = process.emitWarning;
+ sinon.stub(process, 'emitWarning');
+ } else {
+ process.emitWarning = sinon.spy();
+ }
+ errors.deprecate.cache = {};
+ });
+
+ afterEach(function() {
+ // if this is not set, then we created it, so we should remove it.
+ if (!emitWarning) {
+ delete process.emitWarning;
+ }
+ });
+
+ it('should coerce its parameter to a string', function() {
+ errors.deprecate(1);
+ expect(process.emitWarning, 'to have a call satisfying', [
+ '1',
+ 'DeprecationWarning'
+ ]);
+ });
+
+ it('should cache the message', function() {
+ errors.deprecate('foo');
+ errors.deprecate('foo');
+ expect(process.emitWarning, 'was called times', 1);
+ });
+
+ it('should ignore falsy messages', function() {
+ errors.deprecate('');
+ expect(process.emitWarning, 'was not called');
+ });
+ });
+
+ describe('warn()', function() {
+ var emitWarning;
+
+ beforeEach(function() {
+ if (process.emitWarning) {
+ emitWarning = process.emitWarning;
+ sinon.stub(process, 'emitWarning');
+ } else {
+ process.emitWarning = sinon.spy();
+ }
+ });
+
+ afterEach(function() {
+ // if this is not set, then we created it, so we should remove it.
+ if (!emitWarning) {
+ delete process.emitWarning;
+ }
+ });
+
+ it('should call process.emitWarning', function() {
+ errors.warn('foo');
+ expect(process.emitWarning, 'was called times', 1);
+ });
+
+ it('should not cache messages', function() {
+ errors.warn('foo');
+ errors.warn('foo');
+ expect(process.emitWarning, 'was called times', 2);
+ });
+
+ it('should ignore falsy messages', function() {
+ errors.warn('');
+ expect(process.emitWarning, 'was not called');
+ });
+ });
});
diff --git a/test/unit/mocha.spec.js b/test/unit/mocha.spec.js
index d4f3ee8b..3834f0ad 100644
--- a/test/unit/mocha.spec.js
+++ b/test/unit/mocha.spec.js
@@ -4,6 +4,7 @@ var sinon = require('sinon');
var EventEmitter = require('events').EventEmitter;
var Mocha = require('../../lib/mocha');
var utils = require('../../lib/utils');
+const errors = require('../../lib/errors');
describe('Mocha', function() {
/**
@@ -51,11 +52,8 @@ describe('Mocha', function() {
sinon.stub(Mocha.reporters, 'base').returns({});
sinon.stub(Mocha.reporters, 'spec').returns({});
- runner = utils.assign(sinon.createStubInstance(EventEmitter), {
- run: sinon
- .stub()
- .callsArgAsync(0)
- .returnsThis(),
+ runner = Object.assign(sinon.createStubInstance(EventEmitter), {
+ runAsync: sinon.stub().resolves(0),
globals: sinon.stub(),
grep: sinon.stub(),
dispose: sinon.stub()
@@ -64,18 +62,22 @@ describe('Mocha', function() {
// the Runner constructor is the main export, and constants is a static prop.
// we don't need the constants themselves, but the object cannot be undefined
Runner.constants = {};
- suite = utils.assign(sinon.createStubInstance(EventEmitter), {
+ suite = Object.assign(sinon.createStubInstance(EventEmitter), {
slow: sinon.stub(),
timeout: sinon.stub(),
bail: sinon.stub(),
dispose: sinon.stub(),
- reset: sinon.stub()
+ reset: sinon.stub(),
+ beforeAll: sinon.stub(),
+ beforeEach: sinon.stub(),
+ afterAll: sinon.stub(),
+ afterEach: sinon.stub()
});
Suite = sinon.stub(Mocha, 'Suite').returns(suite);
Suite.constants = {};
sinon.stub(utils, 'supportsEsModules').returns(false);
- sinon.stub(utils, 'warn');
+ sinon.stub(errors, 'warn');
sinon.stub(utils, 'isString');
sinon.stub(utils, 'noop');
});
@@ -96,6 +98,10 @@ describe('Mocha', function() {
sinon.stub(Mocha.prototype, 'retries').returnsThis();
sinon.stub(Mocha.prototype, 'rootHooks').returnsThis();
sinon.stub(Mocha.prototype, 'parallelMode').returnsThis();
+ sinon.stub(Mocha.prototype, 'globalSetup').returnsThis();
+ sinon.stub(Mocha.prototype, 'globalTeardown').returnsThis();
+ sinon.stub(Mocha.prototype, 'enableGlobalSetup').returnsThis();
+ sinon.stub(Mocha.prototype, 'enableGlobalTeardown').returnsThis();
});
it('should set _cleanReferencesAfterRun to true', function() {
@@ -176,6 +182,44 @@ describe('Mocha', function() {
expect(Mocha.prototype.parallelMode, 'was not called');
});
});
+
+ describe('when `globalSetup` option is present', function() {
+ it('should configure global setup fixtures', function() {
+ const globalSetup = [() => {}];
+ const mocha = new Mocha({globalSetup});
+ expect(mocha.globalSetup, 'to have a call satisfying', [
+ globalSetup
+ ]).and('was called once');
+ });
+ });
+
+ describe('when `globalTeardown` option is present', function() {
+ it('should configure global teardown fixtures', function() {
+ const globalTeardown = [() => {}];
+ const mocha = new Mocha({globalTeardown});
+ expect(mocha.globalTeardown, 'to have a call satisfying', [
+ globalTeardown
+ ]).and('was called once');
+ });
+ });
+
+ describe('when `enableGlobalSetup` option is present', function() {
+ it('should toggle global setup fixtures', function() {
+ const mocha = new Mocha({enableGlobalSetup: 1});
+ expect(mocha.enableGlobalSetup, 'to have a call satisfying', [1]).and(
+ 'was called once'
+ );
+ });
+ });
+
+ describe('when `enableGlobalTeardown` option is present', function() {
+ it('should configure global teardown fixtures', function() {
+ const mocha = new Mocha({enableGlobalTeardown: 1});
+ expect(mocha.enableGlobalTeardown, 'to have a call satisfying', [
+ 1
+ ]).and('was called once');
+ });
+ });
});
});
@@ -544,6 +588,14 @@ describe('Mocha', function() {
});
describe('run()', function() {
+ let globalFixtureContext;
+
+ beforeEach(function() {
+ globalFixtureContext = {};
+ sinon.stub(mocha, 'runGlobalSetup').returns(globalFixtureContext);
+ sinon.stub(mocha, 'runGlobalTeardown').returns(globalFixtureContext);
+ });
+
describe('when files have been added to the Mocha instance', function() {
beforeEach(function() {
sinon.stub(mocha, 'loadFiles');
@@ -716,13 +768,14 @@ describe('Mocha', function() {
);
});
- it('should not call `Runner#run`', function(done) {
+ it('should not call `Runner#runAsync`', function(done) {
mocha.run(done); // this is async!
try {
mocha.run();
} catch (ignored) {
} finally {
- expect(runner.run, 'was called once');
+ // it'll be 0 or 1, depending on timing.
+ expect(runner.runAsync.callCount, 'to be less than', 2);
}
});
});
@@ -746,12 +799,12 @@ describe('Mocha', function() {
);
});
- it('should not call `Runner#run`', function() {
+ it('should not call `Runner#runAsync`', function() {
try {
mocha.run();
} catch (ignored) {
} finally {
- expect(runner.run, 'was not called');
+ expect(runner.runAsync, 'was not called');
}
});
});
@@ -759,7 +812,7 @@ describe('Mocha', function() {
describe('when a run has finished and is called again', function() {
beforeEach(function(done) {
mocha.run(function() {
- runner.run.reset();
+ runner.runAsync.reset();
done();
});
});
@@ -777,12 +830,12 @@ describe('Mocha', function() {
);
});
- it('should not call `Runner#run()`', function() {
+ it('should not call `Runner#runAsync()`', function() {
try {
mocha.run();
} catch (ignored) {
} finally {
- expect(runner.run, 'was not called');
+ expect(runner.runAsync, 'was not called');
}
});
});
@@ -798,10 +851,10 @@ describe('Mocha', function() {
});
});
- it('should call `Runner#run` for each call', function(done) {
+ it('should call `Runner#runAsync` for each call', function(done) {
mocha.run(function() {
mocha.run(function() {
- expect(runner.run, 'was called twice');
+ expect(runner.runAsync, 'was called twice');
done();
});
});
@@ -825,6 +878,153 @@ describe('Mocha', function() {
});
});
});
+
+ describe('when global setup fixtures enabled', function() {
+ beforeEach(function() {
+ mocha.options.enableGlobalSetup = true;
+ });
+ describe('when global setup fixtures not present', function() {
+ beforeEach(function() {
+ sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(false);
+ });
+
+ it('should not run global setup fixtures', function(done) {
+ mocha.run(() => {
+ expect(mocha.runGlobalSetup, 'was not called');
+ done();
+ });
+ });
+ });
+
+ describe('when global setup fixtures are present', function() {
+ beforeEach(function() {
+ sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(true);
+ });
+
+ it('should run global setup fixtures', function(done) {
+ mocha.run(() => {
+ expect(mocha.runGlobalSetup, 'to have a call satisfying', {
+ args: [expect.it('to be', runner)]
+ }).and('was called once');
+ done();
+ });
+ });
+ });
+ });
+
+ describe('when global setup fixtures disabled', function() {
+ beforeEach(function() {
+ mocha.options.enableGlobalSetup = false;
+ });
+ describe('when global setup fixtures not present', function() {
+ beforeEach(function() {
+ sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(false);
+ });
+
+ it('should not run global setup fixtures', function(done) {
+ mocha.run(() => {
+ expect(mocha.runGlobalSetup, 'was not called');
+ done();
+ });
+ });
+ });
+
+ describe('when global setup fixtures are present', function() {
+ beforeEach(function() {
+ sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(true);
+ });
+
+ it('should not run global setup fixtures', function(done) {
+ mocha.run(() => {
+ expect(mocha.runGlobalSetup, 'was not called');
+ done();
+ });
+ });
+ });
+ });
+
+ describe('when global teardown fixtures enabled', function() {
+ beforeEach(function() {
+ mocha.options.enableGlobalTeardown = true;
+ });
+ describe('when global teardown fixtures not present', function() {
+ beforeEach(function() {
+ sinon.stub(mocha, 'hasGlobalTeardownFixtures').returns(false);
+ });
+
+ it('should not run global teardown fixtures', function(done) {
+ mocha.run(() => {
+ expect(mocha.runGlobalTeardown, 'was not called');
+ done();
+ });
+ });
+ });
+
+ describe('when global teardown fixtures are present', function() {
+ beforeEach(function() {
+ sinon.stub(mocha, 'hasGlobalTeardownFixtures').returns(true);
+ });
+
+ it('should run global teardown fixtures', function(done) {
+ mocha.run(() => {
+ expect(mocha.runGlobalTeardown, 'to have a call satisfying', {
+ args: [expect.it('to be', runner), {context: {}}]
+ }).and('was called once');
+ done();
+ });
+ });
+
+ describe('when global setup fixtures are present and enabled', function() {
+ beforeEach(function() {
+ sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(true);
+ mocha.options.enableGlobalSetup = true;
+ });
+
+ it('should use the same context as returned by `runGlobalSetup`', function(done) {
+ mocha.run(() => {
+ expect(mocha.runGlobalTeardown, 'to have a call satisfying', {
+ args: [
+ expect.it('to be', runner),
+ {context: globalFixtureContext}
+ ]
+ }).and('was called once');
+ done();
+ });
+ });
+ });
+ });
+ });
+
+ describe('when global teardown fixtures disabled', function() {
+ beforeEach(function() {
+ mocha.options.enableGlobalTeardown = false;
+ });
+ describe('when global teardown fixtures not present', function() {
+ beforeEach(function() {
+ sinon.stub(mocha, 'hasGlobalTeardownFixtures').returns(false);
+ });
+
+ it('should not run global teardown fixtures', function(done) {
+ mocha.run(() => {
+ expect(mocha.runGlobalTeardown, 'was not called');
+ done();
+ });
+ });
+ });
+
+ describe('when global teardown fixtures are present', function() {
+ beforeEach(function() {
+ sinon.stub(mocha, 'hasGlobalTeardownFixtures').returns(true);
+ });
+
+ it('should not run global teardown fixtures', function(done) {
+ mocha.run(() => {
+ expect(mocha.runGlobalTeardown, 'was not called');
+ done();
+ });
+ });
+ });
+ });
});
describe('parallelMode()', function() {
@@ -845,7 +1045,7 @@ describe('Mocha', function() {
});
});
- describe('unloadFile', function() {
+ describe('unloadFile()', function() {
describe('when run in a browser', function() {
beforeEach(function() {
sinon.stub(utils, 'isBrowser').returns(true);
@@ -858,5 +1058,208 @@ describe('Mocha', function() {
});
});
});
+
+ describe('_runGlobalFixtures()', function() {
+ it('should execute multiple fixtures in order', async function() {
+ const fixtures = [
+ sinon.stub().resolves('foo'),
+ sinon.stub().returns('bar')
+ ];
+ const context = await mocha._runGlobalFixtures(fixtures);
+
+ return expect(fixtures, 'to satisfy', [
+ expect.it('to have a call satisfying', {
+ thisValue: context,
+ returnValue: expect.it('to be fulfilled with', 'foo')
+ }),
+ expect.it('to have a call satisfying', {
+ thisValue: context,
+ returnValue: 'bar'
+ })
+ ]);
+ });
+ });
+
+ describe('runGlobalSetup()', function() {
+ let context;
+
+ beforeEach(function() {
+ sinon.stub(mocha, '_runGlobalFixtures').resolvesArg(1);
+ context = {};
+ });
+
+ describe('when fixture(s) are present', function() {
+ beforeEach(function() {
+ mocha.options.globalSetup = [sinon.spy()];
+ });
+
+ it('should attempt run the fixtures', async function() {
+ await mocha.runGlobalSetup(context);
+ expect(mocha._runGlobalFixtures, 'to have a call satisfying', [
+ mocha.options.globalSetup,
+ context
+ ]);
+ });
+ });
+
+ describe('when a fixture is not present', function() {
+ it('should not attempt to run fixtures', async function() {
+ await mocha.runGlobalSetup();
+ expect(mocha._runGlobalFixtures, 'was not called');
+ });
+ });
+ });
+
+ describe('runGlobalTeardown()', function() {
+ let context;
+
+ beforeEach(function() {
+ sinon.stub(mocha, '_runGlobalFixtures').resolvesArg(1);
+ context = {};
+ });
+
+ describe('when fixture(s) are present', function() {
+ beforeEach(function() {
+ mocha.options.globalTeardown = [sinon.spy()];
+ });
+
+ it('should attempt to run the fixtures', async function() {
+ await mocha.runGlobalTeardown();
+ expect(mocha._runGlobalFixtures, 'to have a call satisfying', [
+ mocha.options.globalTeardown,
+ context
+ ]);
+ });
+ });
+
+ describe('when a fixture is not present', function() {
+ it('not attempt to run the fixtures', async function() {
+ await mocha.runGlobalTeardown();
+ expect(mocha._runGlobalFixtures, 'was not called');
+ });
+ });
+ });
+
+ describe('hasGlobalSetupFixtures()', function() {
+ describe('when one or more global setup fixtures are present', function() {
+ it('should return `true`', function() {
+ mocha.options.globalSetup = [() => {}];
+ expect(mocha.hasGlobalSetupFixtures(), 'to be true');
+ });
+ });
+
+ describe('when no global setup fixtures are present', function() {
+ it('should return `false`', function() {
+ mocha.options.globalSetup = [];
+ expect(mocha.hasGlobalSetupFixtures(), 'to be false');
+ });
+ });
+ });
+
+ describe('hasGlobalTeardownFixtures()', function() {
+ describe('when one or more global teardown fixtures are present', function() {
+ it('should return `true`', function() {
+ mocha.options.globalTeardown = [() => {}];
+ expect(mocha.hasGlobalTeardownFixtures(), 'to be true');
+ });
+ });
+
+ describe('when no global teardown fixtures are present', function() {
+ it('should return `false`', function() {
+ mocha.options.globalTeardown = [];
+ expect(mocha.hasGlobalTeardownFixtures(), 'to be false');
+ });
+ });
+ });
+
+ describe('rootHooks()', function() {
+ it('should be chainable', function() {
+ expect(mocha.rootHooks(), 'to be', mocha);
+ });
+
+ describe('when provided a single "before all" hook', function() {
+ it('should attach it to the root suite', function() {
+ const beforeAll = () => {};
+ mocha.rootHooks({beforeAll});
+ expect(mocha.suite.beforeAll, 'to have a call satisfying', [
+ beforeAll
+ ]).and('was called once');
+ });
+ });
+
+ describe('when provided a single "before each" hook', function() {
+ it('should attach it to the root suite', function() {
+ const beforeEach = () => {};
+ mocha.rootHooks({beforeEach});
+ expect(mocha.suite.beforeEach, 'to have a call satisfying', [
+ beforeEach
+ ]).and('was called once');
+ });
+ });
+
+ describe('when provided a single "after all" hook', function() {
+ it('should attach it to the root suite', function() {
+ const afterAll = () => {};
+ mocha.rootHooks({afterAll});
+ expect(mocha.suite.afterAll, 'to have a call satisfying', [
+ afterAll
+ ]).and('was called once');
+ });
+ });
+
+ describe('when provided a single "after each" hook', function() {
+ it('should attach it to the root suite', function() {
+ const afterEach = () => {};
+ mocha.rootHooks({afterEach});
+ expect(mocha.suite.afterEach, 'to have a call satisfying', [
+ afterEach
+ ]).and('was called once');
+ });
+ });
+
+ describe('when provided multiple "before all" hooks', function() {
+ it('should attach each to the root suite', function() {
+ const beforeAll = [() => {}, () => {}];
+ mocha.rootHooks({beforeAll});
+ expect(mocha.suite.beforeAll, 'to have calls satisfying', [
+ [beforeAll[0]],
+ [beforeAll[1]]
+ ]).and('was called twice');
+ });
+ });
+
+ describe('when provided multiple "before each" hooks', function() {
+ it('should attach each to the root suite', function() {
+ const beforeEach = [() => {}, () => {}];
+ mocha.rootHooks({beforeEach});
+ expect(mocha.suite.beforeEach, 'to have calls satisfying', [
+ [beforeEach[0]],
+ [beforeEach[1]]
+ ]).and('was called twice');
+ });
+ });
+
+ describe('when provided multiple "after all" hooks', function() {
+ it('should attach each to the root suite', function() {
+ const afterAll = [() => {}, () => {}];
+ mocha.rootHooks({afterAll});
+ expect(mocha.suite.afterAll, 'to have calls satisfying', [
+ [afterAll[0]],
+ [afterAll[1]]
+ ]).and('was called twice');
+ });
+ });
+
+ describe('when provided multiple "after each" hooks', function() {
+ it('should attach each to the root suite', function() {
+ const afterEach = [() => {}, () => {}];
+ mocha.rootHooks({afterEach});
+ expect(mocha.suite.afterEach, 'to have calls satisfying', [
+ [afterEach[0]],
+ [afterEach[1]]
+ ]).and('was called twice');
+ });
+ });
+ });
});
});
diff --git a/test/unit/plugin-loader.spec.js b/test/unit/plugin-loader.spec.js
new file mode 100644
index 00000000..78d2debd
--- /dev/null
+++ b/test/unit/plugin-loader.spec.js
@@ -0,0 +1,514 @@
+'use strict';
+
+const PluginLoader = require('../../lib/plugin-loader');
+const sinon = require('sinon');
+const {
+ INVALID_PLUGIN_DEFINITION,
+ INVALID_PLUGIN_IMPLEMENTATION
+} = require('../../lib/errors').constants;
+
+describe('plugin module', function() {
+ describe('class PluginLoader', function() {
+ describe('constructor', function() {
+ describe('when passed no options', function() {
+ it('should populate a registry of built-in plugins', function() {
+ expect(new PluginLoader().registered.has('mochaHooks'), 'to be true');
+ });
+ });
+
+ describe('when passed custom plugins', function() {
+ it('should register the custom plugins', function() {
+ const plugin = {exportName: 'mochaBananaPhone'};
+ expect(
+ new PluginLoader({pluginDefs: [plugin]}).registered,
+ 'to satisfy',
+ new Map([['mochaBananaPhone', plugin]])
+ );
+ });
+ });
+
+ describe('when passed ignored plugins', function() {
+ it('should retain a list of ignored plugins', function() {
+ expect(
+ new PluginLoader({
+ ignore: ['elephantInRoom']
+ }).ignoredExportNames,
+ 'to contain',
+ 'elephantInRoom'
+ );
+ });
+ });
+ });
+
+ describe('static method', function() {
+ describe('create()', function() {
+ it('should return a PluginLoader instance', function() {
+ expect(PluginLoader.create(), 'to be a', PluginLoader);
+ });
+ });
+ });
+
+ describe('instance method', function() {
+ let pluginLoader;
+
+ beforeEach(function() {
+ pluginLoader = PluginLoader.create({
+ ignore: ['elephantInRoom']
+ });
+ });
+
+ describe('register()', function() {
+ describe('when the plugin export name is not in use', function() {
+ it('should not throw', function() {
+ expect(
+ () => pluginLoader.register({exportName: 'butts'}),
+ 'not to throw'
+ );
+ });
+ });
+
+ describe('when the plugin export name is already in use', function() {
+ it('should throw', function() {
+ const pluginDef = {exportName: 'butts'};
+ pluginLoader.register(pluginDef);
+ expect(() => pluginLoader.register(pluginDef), 'to throw', {
+ code: INVALID_PLUGIN_DEFINITION,
+ pluginDef
+ });
+ });
+ });
+
+ describe('when the plugin export name is ignored', function() {
+ let pluginDef;
+
+ beforeEach(function() {
+ pluginDef = {exportName: 'elephantInRoom'};
+ });
+
+ it('should not throw', function() {
+ expect(() => pluginLoader.register(pluginDef), 'not to throw');
+ });
+
+ it('should not register the plugin', function() {
+ pluginLoader.register(pluginDef);
+ expect(
+ pluginLoader.registered,
+ 'not to have key',
+ 'elephantInRoom'
+ );
+ });
+ });
+
+ describe('when passed a falsy parameter', function() {
+ it('should throw', function() {
+ expect(() => pluginLoader.register(), 'to throw', {
+ code: INVALID_PLUGIN_DEFINITION
+ });
+ });
+ });
+
+ describe('when passed a non-object parameter', function() {
+ it('should throw', function() {
+ expect(() => pluginLoader.register(1), 'to throw', {
+ code: INVALID_PLUGIN_DEFINITION,
+ pluginDef: 1
+ });
+ });
+ });
+
+ describe('when passed a definition w/o an exportName', function() {
+ it('should throw', function() {
+ const pluginDef = {foo: 'bar'};
+ expect(() => pluginLoader.register(pluginDef), 'to throw', {
+ code: INVALID_PLUGIN_DEFINITION,
+ pluginDef
+ });
+ });
+ });
+ });
+
+ describe('load()', function() {
+ let pluginLoader;
+
+ beforeEach(function() {
+ pluginLoader = PluginLoader.create();
+ });
+
+ describe('when called with a falsy value', function() {
+ it('should return false', function() {
+ expect(pluginLoader.load(), 'to be false');
+ });
+ });
+
+ describe('when called with an object containing no recognized plugin', function() {
+ it('should return false', function() {
+ // also it should not throw
+ expect(
+ pluginLoader.load({mochaBananaPhone: () => {}}),
+ 'to be false'
+ );
+ });
+ });
+
+ describe('when called with an object containing a recognized plugin', function() {
+ let plugin;
+ let pluginLoader;
+
+ beforeEach(function() {
+ plugin = {
+ exportName: 'mochaBananaPhone',
+ validate: sinon.spy()
+ };
+ pluginLoader = PluginLoader.create({pluginDefs: [plugin]});
+ });
+
+ it('should return true', function() {
+ const func = () => {};
+ expect(pluginLoader.load({mochaBananaPhone: func}), 'to be true');
+ });
+
+ it('should retain the value of any matching property in its mapping', function() {
+ const func = () => {};
+ pluginLoader.load({mochaBananaPhone: func});
+ expect(
+ pluginLoader.loaded,
+ 'to satisfy',
+ new Map([['mochaBananaPhone', [func]]])
+ );
+ });
+
+ it('should call the associated validator, if present', function() {
+ const func = () => {};
+ pluginLoader.load({mochaBananaPhone: func});
+ expect(plugin.validate, 'was called once');
+ });
+ });
+ });
+
+ describe('load()', function() {
+ let pluginLoader;
+ let fooPlugin;
+ let barPlugin;
+
+ beforeEach(function() {
+ fooPlugin = {
+ exportName: 'foo',
+ validate: sinon.stub()
+ };
+ fooPlugin.validate.withArgs('ERROR').throws();
+ barPlugin = {
+ exportName: 'bar',
+ validate: sinon.stub()
+ };
+ pluginLoader = PluginLoader.create({
+ pluginDefs: [fooPlugin, barPlugin]
+ });
+ });
+
+ describe('when passed a falsy or non-object value', function() {
+ it('should return false', function() {
+ expect(pluginLoader.load(), 'to be false');
+ });
+
+ it('should not call a validator', function() {
+ expect([fooPlugin, barPlugin], 'to have items satisfying', {
+ validate: expect.it('was not called')
+ });
+ });
+ });
+
+ describe('when passed an object value', function() {
+ describe('when no keys match any known named exports', function() {
+ let retval;
+
+ beforeEach(function() {
+ retval = pluginLoader.load({butts: () => {}});
+ });
+
+ it('should return false', function() {
+ expect(retval, 'to be false');
+ });
+ });
+
+ describe('when a key matches a known named export', function() {
+ let retval;
+ let impl;
+
+ beforeEach(function() {
+ impl = sinon.stub();
+ });
+
+ it('should call the associated validator', function() {
+ retval = pluginLoader.load({foo: impl});
+
+ expect(fooPlugin.validate, 'to have a call satisfying', [
+ impl
+ ]).and('was called once');
+ });
+
+ it('should not call validators whose keys were not found', function() {
+ retval = pluginLoader.load({foo: impl});
+ expect(barPlugin.validate, 'was not called');
+ });
+
+ describe('when the value passes the associated validator', function() {
+ beforeEach(function() {
+ retval = pluginLoader.load({foo: impl});
+ });
+
+ it('should return true', function() {
+ expect(retval, 'to be true');
+ });
+
+ it('should add the implementation to the internal mapping', function() {
+ expect(
+ pluginLoader.loaded,
+ 'to satisfy',
+ new Map([['foo', expect.it('to have length', 1)]])
+ );
+ });
+
+ it('should not add an implementation of plugins not present', function() {
+ expect(
+ pluginLoader.loaded,
+ 'to satisfy',
+ new Map([['bar', expect.it('to be empty')]])
+ );
+ });
+ });
+
+ describe('when the value does not pass the associated validator', function() {
+ it('should throw', function() {
+ expect(() => pluginLoader.load({foo: 'ERROR'}), 'to throw');
+ });
+ });
+ });
+ });
+ });
+
+ describe('finalize()', function() {
+ let pluginLoader;
+ let fooPlugin;
+ let barPlugin;
+ let bazPlugin;
+
+ beforeEach(function() {
+ fooPlugin = {
+ exportName: 'foo',
+ optionName: 'fooOption',
+ validate: sinon.stub(),
+ finalize: impls => impls.map(() => 'FOO')
+ };
+ fooPlugin.validate.withArgs('ERROR').throws();
+ barPlugin = {
+ exportName: 'bar',
+ validate: sinon.stub(),
+ finalize: impls => impls.map(() => 'BAR')
+ };
+ bazPlugin = {
+ exportName: 'baz'
+ };
+ pluginLoader = PluginLoader.create({
+ pluginDefs: [fooPlugin, barPlugin, bazPlugin]
+ });
+ });
+
+ describe('when no plugins have been loaded', function() {
+ it('should return an empty map', async function() {
+ return expect(pluginLoader.finalize(), 'to be fulfilled with', {});
+ });
+ });
+
+ describe('when a plugin has one or more implementations', function() {
+ beforeEach(function() {
+ pluginLoader.load({foo: sinon.stub()});
+ pluginLoader.load({foo: sinon.stub()});
+ });
+
+ it('should return an object map using `optionName` key for each registered plugin', async function() {
+ return expect(pluginLoader.finalize(), 'to be fulfilled with', {
+ fooOption: ['FOO', 'FOO']
+ });
+ });
+
+ it('should omit unused plugins', async function() {
+ pluginLoader.load({bar: sinon.stub()});
+ return expect(pluginLoader.finalize(), 'to be fulfilled with', {
+ fooOption: ['FOO', 'FOO'],
+ bar: ['BAR']
+ });
+ });
+ });
+
+ describe('when a plugin has no "finalize" function', function() {
+ it('should return an array of raw implementations', function() {
+ pluginLoader.load({baz: 'polar bears'});
+ return expect(pluginLoader.finalize(), 'to be fulfilled with', {
+ baz: ['polar bears']
+ });
+ });
+ });
+ });
+ });
+ });
+
+ describe('root hooks plugin 🎣', function() {
+ let pluginLoader;
+
+ beforeEach(function() {
+ pluginLoader = PluginLoader.create();
+ });
+
+ describe('when impl is an array', function() {
+ it('should fail validation', function() {
+ expect(() => pluginLoader.load({mochaHooks: []}), 'to throw', {
+ code: INVALID_PLUGIN_IMPLEMENTATION
+ });
+ });
+ });
+
+ describe('when impl is a primitive', function() {
+ it('should fail validation', function() {
+ expect(() => pluginLoader.load({mochaHooks: 'nuts'}), 'to throw', {
+ code: INVALID_PLUGIN_IMPLEMENTATION
+ });
+ });
+ });
+
+ describe('when impl is a function', function() {
+ it('should pass validation', function() {
+ expect(pluginLoader.load({mochaHooks: sinon.stub()}), 'to be true');
+ });
+ });
+
+ describe('when impl is an object of functions', function() {
+ // todo: hook name validation?
+ it('should pass validation');
+ });
+
+ describe('when a loaded impl is finalized', function() {
+ it('should flatten the implementations', async function() {
+ function a() {}
+ function b() {}
+ function d() {}
+ function g() {}
+ async function f() {}
+ function c() {
+ return {
+ beforeAll: d,
+ beforeEach: g
+ };
+ }
+ async function e() {
+ return {
+ afterEach: f
+ };
+ }
+
+ [
+ {
+ beforeEach: a
+ },
+ {
+ afterAll: b
+ },
+ c,
+ e
+ ].forEach(impl => {
+ pluginLoader.load({mochaHooks: impl});
+ });
+
+ return expect(pluginLoader.finalize(), 'to be fulfilled with', {
+ rootHooks: {
+ beforeAll: [d],
+ beforeEach: [a, g],
+ afterAll: [b],
+ afterEach: [f]
+ }
+ });
+ });
+ });
+ });
+
+ describe('global fixtures plugin', function() {
+ let pluginLoader;
+
+ beforeEach(function() {
+ pluginLoader = PluginLoader.create();
+ });
+
+ describe('global setup', function() {
+ describe('when an implementation is a primitive', function() {
+ it('should fail validation', function() {
+ expect(
+ () => pluginLoader.load({mochaGlobalSetup: 'nuts'}),
+ 'to throw'
+ );
+ });
+ });
+ describe('when an implementation is an array of primitives', function() {
+ it('should fail validation', function() {
+ expect(
+ () => pluginLoader.load({mochaGlobalSetup: ['nuts']}),
+ 'to throw'
+ );
+ });
+ });
+
+ describe('when an implementation is a function', function() {
+ it('should pass validation', function() {
+ expect(
+ pluginLoader.load({mochaGlobalSetup: sinon.stub()}),
+ 'to be true'
+ );
+ });
+ });
+
+ describe('when an implementation is an array of functions', function() {
+ it('should pass validation', function() {
+ expect(
+ pluginLoader.load({mochaGlobalSetup: [sinon.stub()]}),
+ 'to be true'
+ );
+ });
+ });
+ });
+
+ describe('global teardown', function() {
+ describe('when an implementation is a primitive', function() {
+ it('should fail validation', function() {
+ expect(
+ () => pluginLoader.load({mochaGlobalTeardown: 'nuts'}),
+ 'to throw'
+ );
+ });
+ });
+ describe('when an implementation is an array of primitives', function() {
+ it('should fail validation', function() {
+ expect(
+ () => pluginLoader.load({mochaGlobalTeardown: ['nuts']}),
+ 'to throw'
+ );
+ });
+ });
+
+ describe('when an implementation is a function', function() {
+ it('should pass validation', function() {
+ expect(
+ pluginLoader.load({mochaGlobalTeardown: sinon.stub()}),
+ 'to be true'
+ );
+ });
+ });
+
+ describe('when an implementation is an array of functions', function() {
+ it('should pass validation', function() {
+ expect(
+ pluginLoader.load({mochaGlobalTeardown: [sinon.stub()]}),
+ 'to be true'
+ );
+ });
+ });
+ });
+ });
+});
diff --git a/test/unit/runner.spec.js b/test/unit/runner.spec.js
index 730c4000..abc5eef8 100644
--- a/test/unit/runner.spec.js
+++ b/test/unit/runner.spec.js
@@ -25,919 +25,903 @@ var STATE_RUNNING = Runner.constants.STATE_RUNNING;
var STATE_STOPPED = Runner.constants.STATE_STOPPED;
describe('Runner', function() {
- var suite;
- var runner;
-
- beforeEach(function() {
- suite = new Suite('Suite', 'root');
- runner = new Runner(suite, {cleanReferencesAfterRun: true});
- runner.checkLeaks = true;
- });
-
afterEach(function() {
sinon.restore();
});
- 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));
- var newRunner = new Runner(suite);
- newRunner.grep(/lions/);
- expect(newRunner.total, 'to be', 2);
+ describe('instance method', function() {
+ let suite;
+ let runner;
+ beforeEach(function() {
+ suite = new Suite('Suite', 'root');
+ runner = new Runner(suite, {cleanReferencesAfterRun: true});
+ runner.checkLeaks = true;
});
- 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));
- var newRunner = new Runner(suite);
- newRunner.grep(/lions/, true);
- expect(newRunner.total, 'to be', 1);
- });
- });
+ 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));
+ var newRunner = new Runner(suite);
+ newRunner.grep(/lions/);
+ expect(newRunner.total, 'to be', 2);
+ });
- 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));
- runner.grep(/lions/);
- expect(runner.grepTotal(suite), 'to be', 2);
+ 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));
+ var newRunner = new Runner(suite);
+ newRunner.grep(/lions/, true);
+ expect(newRunner.total, 'to be', 1);
+ });
});
- 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));
- runner.grep(/lions/, true);
- expect(runner.grepTotal(suite), 'to be', 1);
- });
- });
+ 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));
+ runner.grep(/lions/);
+ expect(runner.grepTotal(suite), 'to be', 2);
+ });
- describe('.globalProps()', function() {
- it('should include common non enumerable globals', function() {
- var props = runner.globalProps();
- expect(
- props,
- 'to contain',
- 'setTimeout',
- 'clearTimeout',
- 'setInterval',
- 'clearInterval',
- 'Date',
- 'XMLHttpRequest'
- );
+ 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));
+ runner.grep(/lions/, true);
+ expect(runner.grepTotal(suite), 'to be', 1);
+ });
});
- });
-
- describe('.globals()', function() {
- it('should default to the known globals', function() {
- expect(runner.globals().length, 'to be greater than', 16);
+ describe('globalProps()', function() {
+ it('should include common non enumerable globals', function() {
+ var props = runner.globalProps();
+ expect(
+ props,
+ 'to contain',
+ 'setTimeout',
+ 'clearTimeout',
+ 'setInterval',
+ 'clearInterval',
+ 'Date',
+ 'XMLHttpRequest'
+ );
+ });
});
- it('should white-list globals', function() {
- runner.globals(['foo', 'bar']);
- expect(runner.globals(), 'to contain', 'foo', 'bar');
- });
- });
+ describe('globals()', function() {
+ it('should default to the known globals', function() {
+ expect(runner.globals().length, 'to be greater than', 16);
+ });
- describe('.checkGlobals(test)', function() {
- before(function() {
- if (!Object.create) {
- this.skip();
- }
+ it('should white-list globals', function() {
+ runner.globals(['foo', 'bar']);
+ expect(runner.globals(), 'to contain', 'foo', 'bar');
+ });
});
- it('should allow variables that match a wildcard', function(done) {
- runner.globals(['foo*', 'giz*']);
- global.foo = 'baz';
- global.gizmo = 'quux';
- runner.checkGlobals();
- delete global.foo;
- delete global.gizmo;
- done();
- });
+ describe('checkGlobals(test)', function() {
+ before(function() {
+ if (!Object.create) {
+ this.skip();
+ }
+ });
- 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(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_test, 'to be', test);
- expect(_err, 'to have message', "global leak(s) detected: 'foo'");
+ it('should allow variables that match a wildcard', function(done) {
+ runner.globals(['foo*', 'giz*']);
+ global.foo = 'baz';
+ global.gizmo = 'quux';
+ runner.checkGlobals();
delete global.foo;
+ delete global.gizmo;
done();
});
- runner.checkGlobals(test);
- });
- 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(EVENT_TEST_FAIL, function() {
- delete global.bad;
- done();
- doneCalled = true;
+ 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(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_test, 'to be', test);
+ expect(_err, 'to have message', "global leak(s) detected: 'foo'");
+ delete global.foo;
+ done();
+ });
+ runner.checkGlobals(test);
});
- runner.checkGlobals(new Test('yet another test', noop));
- if (!doneCalled) {
- done(Error('Expected test failure did not occur.'));
- }
- });
- it('should not fail when a new common global is introduced', function() {
- if (process.browser) {
- this.skip();
- return;
- }
- // verify that the prop isn't enumerable
- expect(
- Object.prototype.propertyIsEnumerable.call(global, 'XMLHttpRequest'),
- 'to be',
- false
- );
-
- // create a new runner and keep a reference to the test.
- var test = new Test('im a test about bears', noop);
- suite.addTest(test);
- var newRunner = new Runner(suite);
-
- // make the prop enumerable again.
- global.XMLHttpRequest = noop;
- expect(
- Object.prototype.propertyIsEnumerable.call(global, 'XMLHttpRequest'),
- 'to be',
- true
- );
-
- // verify the test hasn't failed.
- newRunner.checkGlobals(test);
- expect(test, 'not to have key', 'state');
-
- // clean up our global space.
- delete global.XMLHttpRequest;
- });
-
- 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(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_test, 'to be', test);
- expect(_err.message, 'to be', "global leak(s) detected: 'foo', 'bar'");
- delete global.foo;
- delete global.bar;
- 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(EVENT_TEST_FAIL, function() {
+ delete global.bad;
+ done();
+ doneCalled = true;
+ });
+ runner.checkGlobals(new Test('yet another test', noop));
+ if (!doneCalled) {
+ done(Error('Expected test failure did not occur.'));
+ }
});
- runner.checkGlobals(test);
- });
- it('should respect per test whitelisted globals', function() {
- var test = new Test('im a test about lions', noop);
- test.globals(['foo']);
+ it('should not fail when a new common global is introduced', function() {
+ if (process.browser) {
+ this.skip();
+ return;
+ }
+ // verify that the prop isn't enumerable
+ expect(
+ Object.prototype.propertyIsEnumerable.call(global, 'XMLHttpRequest'),
+ 'to be',
+ false
+ );
+
+ // create a new runner and keep a reference to the test.
+ var test = new Test('im a test about bears', noop);
+ suite.addTest(test);
+ var newRunner = new Runner(suite);
- suite.addTest(test);
- var runner = new Runner(suite);
+ // make the prop enumerable again.
+ global.XMLHttpRequest = noop;
+ expect(
+ Object.prototype.propertyIsEnumerable.call(global, 'XMLHttpRequest'),
+ 'to be',
+ true
+ );
- global.foo = 'bar';
+ // verify the test hasn't failed.
+ newRunner.checkGlobals(test);
+ expect(test, 'not to have key', 'state');
- // verify the test hasn't failed.
- runner.checkGlobals(test);
- expect(test, 'not to have key', 'state');
+ // clean up our global space.
+ delete global.XMLHttpRequest;
+ });
- delete global.foo;
- });
+ 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(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_test, 'to be', test);
+ expect(
+ _err.message,
+ 'to be',
+ "global leak(s) detected: 'foo', 'bar'"
+ );
+ delete global.foo;
+ delete global.bar;
+ done();
+ });
+ runner.checkGlobals(test);
+ });
+
+ it('should respect per test whitelisted globals', function() {
+ var test = new Test('im a test about lions', noop);
+ test.globals(['foo']);
- 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']);
+ suite.addTest(test);
+ var runner = new Runner(suite);
- suite.addTest(test);
+ global.foo = 'bar';
+
+ // verify the test hasn't failed.
+ runner.checkGlobals(test);
+ expect(test, 'not to have key', 'state');
- global.foo = 'whitelisted';
- global.bar = 'detect-me';
- runner.on(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_test.title, 'to be', 'im a test about lions');
- expect(_err, 'to have message', "global leak(s) detected: 'bar'");
delete global.foo;
- delete global.bar;
- done();
});
- runner.checkGlobals(test);
- });
- it('should emit "fail" when a global beginning with "d" is introduced', function(done) {
- global.derp = 'bar';
- runner.on(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_test.title, 'to be', 'herp');
- expect(_err, 'to have message', "global leak(s) detected: 'derp'");
- delete global.derp;
- 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']);
+
+ suite.addTest(test);
+
+ global.foo = 'whitelisted';
+ global.bar = 'detect-me';
+ runner.on(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_test.title, 'to be', 'im a test about lions');
+ expect(_err, 'to have message', "global leak(s) detected: 'bar'");
+ delete global.foo;
+ delete global.bar;
+ done();
+ });
+ runner.checkGlobals(test);
});
- runner.checkGlobals(new Test('herp', noop));
- });
- });
- 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), new Error());
- suite.bail(true);
- suite.afterEach(function() {
- suite.afterAll(function() {
+ it('should emit "fail" when a global beginning with "d" is introduced', function(done) {
+ global.derp = 'bar';
+ runner.on(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_test.title, 'to be', 'herp');
+ expect(_err, 'to have message', "global leak(s) detected: 'derp'");
+ delete global.derp;
done();
});
+ runner.checkGlobals(new Test('herp', noop));
});
- runner.hook('afterEach', noop);
- runner.hook('afterAll', noop);
});
+ describe('hook()', function() {
+ it('should execute hooks after failed test if suite bail is true', function(done) {
+ runner.fail(new Test('failed test', noop), new Error());
+ suite.bail(true);
+ suite.afterEach(function() {
+ suite.afterAll(function() {
+ done();
+ });
+ });
+ runner.hook('afterEach', noop);
+ runner.hook('afterAll', noop);
+ });
- it('should augment hook title with current test title', function(done) {
- var expectedHookTitle;
- function assertHookTitle() {
- expect(hook.title, 'to be', expectedHookTitle);
- }
- var failHook = false;
- var hookError = new Error('failed hook');
- suite.beforeEach(function() {
- assertHookTitle();
- if (failHook) {
- throw hookError;
+ it('should augment hook title with current test title', function(done) {
+ var expectedHookTitle;
+ function assertHookTitle() {
+ expect(hook.title, 'to be', expectedHookTitle);
}
- });
- runner.on(EVENT_HOOK_BEGIN, assertHookTitle);
- runner.on(EVENT_HOOK_END, assertHookTitle);
- runner.on(EVENT_TEST_FAIL, assertHookTitle);
- runner.on(EVENT_TEST_PASS, assertHookTitle);
- var hook = suite._beforeEach[0];
-
- suite.addTest(new Test('should behave', noop));
- suite.addTest(new Test('should obey', noop));
- runner.suite = suite;
-
- runner.test = suite.tests[0];
- expectedHookTitle = '"before each" hook for "should behave"';
- runner.hook('beforeEach', function(err) {
- if (err && err !== hookError) return done(err);
-
- runner.test = suite.tests[1];
- failHook = true;
- expectedHookTitle = '"before each" hook for "should obey"';
+ var failHook = false;
+ var hookError = new Error('failed hook');
+ suite.beforeEach(function() {
+ assertHookTitle();
+ if (failHook) {
+ throw hookError;
+ }
+ });
+ runner.on(EVENT_HOOK_BEGIN, assertHookTitle);
+ runner.on(EVENT_HOOK_END, assertHookTitle);
+ runner.on(EVENT_TEST_FAIL, assertHookTitle);
+ runner.on(EVENT_TEST_PASS, assertHookTitle);
+ var hook = suite._beforeEach[0];
+
+ suite.addTest(new Test('should behave', noop));
+ suite.addTest(new Test('should obey', noop));
+ runner.suite = suite;
+
+ runner.test = suite.tests[0];
+ expectedHookTitle = '"before each" hook for "should behave"';
runner.hook('beforeEach', function(err) {
if (err && err !== hookError) return done(err);
- return done();
+
+ runner.test = suite.tests[1];
+ failHook = true;
+ expectedHookTitle = '"before each" hook for "should obey"';
+ runner.hook('beforeEach', function(err) {
+ if (err && err !== hookError) return done(err);
+ return done();
+ });
});
});
});
- });
-
- describe('fail()', function() {
- it('should increment `Runner#failures`', function() {
- expect(runner.failures, 'to be', 0);
- runner.fail(new Test('one', noop), {});
- expect(runner.failures, 'to be', 1);
- runner.fail(new Test('two', noop), new Error());
- expect(runner.failures, 'to be', 2);
- });
- it('should set `Test#state` to "failed"', function() {
- var test = new Test('some test', noop);
- runner.fail(test, 'some error');
- expect(test.state, 'to be', STATE_FAILED);
- });
-
- it('should emit "fail"', function(done) {
- var test = new Test('some other test', noop);
- var err = {};
- runner.on(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_test, 'to be', test);
- expect(_err, 'to be an', Error);
- expect(_err, 'not to be', {});
- done();
+ describe('fail()', function() {
+ it('should increment `Runner#failures`', function() {
+ expect(runner.failures, 'to be', 0);
+ runner.fail(new Test('one', noop), {});
+ expect(runner.failures, 'to be', 1);
+ runner.fail(new Test('two', noop), new Error());
+ expect(runner.failures, 'to be', 2);
});
- runner.fail(test, err);
- });
- 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(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_err, 'to be an', Error);
- expect(
- _err,
- 'to have message',
- 'the string "string" was thrown, throw an Error :)'
- );
- done();
+ it('should set `Test#state` to "failed"', function() {
+ var test = new Test('some test', noop);
+ runner.fail(test, 'some error');
+ expect(test.state, 'to be', STATE_FAILED);
});
- runner.fail(test, err);
- });
- 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(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_err, 'to be an', Error);
- expect(_err, 'to have message', 'an error message');
- done();
+ it('should emit "fail"', function(done) {
+ var test = new Test('some other test', noop);
+ var err = {};
+ runner.on(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_test, 'to be', test);
+ expect(_err, 'to be an', Error);
+ expect(_err, 'not to be', {});
+ done();
+ });
+ runner.fail(test, err);
});
- runner.fail(test, err);
- });
- 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(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_err, 'not to be an', Error);
- expect(_err.message, 'to be', 'an error message');
- 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(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_err, 'to be an', Error);
+ expect(
+ _err,
+ 'to have message',
+ 'the string "string" was thrown, throw an Error :)'
+ );
+ done();
+ });
+ runner.fail(test, err);
});
- runner.fail(test, err);
- });
- 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(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_err, 'to be an', Error);
- expect(
- _err,
- 'to have message',
- 'the object {\n "x": 1\n} was thrown, throw an Error :)'
- );
- 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(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_err, 'to be an', Error);
+ expect(_err, 'to have message', 'an error message');
+ done();
+ });
+ runner.fail(test, err);
});
- runner.fail(test, err);
- });
- 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(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_err, 'to be an', Error);
- expect(
- _err,
- 'to have message',
- 'the array [\n 1\n 2\n] was thrown, throw an Error :)'
- );
- 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(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_err, 'not to be an', Error);
+ expect(_err.message, 'to be', 'an error message');
+ done();
+ });
+ runner.fail(test, err);
});
- runner.fail(test, err);
- });
-
- it('should recover if the error stack is not writable', function(done) {
- if (!Object.create) {
- this.skip();
- return;
- }
- var err = new Error('not evil');
- Object.defineProperty(err, 'stack', {
- value: err.stack
+ 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(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_err, 'to be an', Error);
+ expect(
+ _err,
+ 'to have message',
+ 'the object {\n "x": 1\n} was thrown, throw an Error :)'
+ );
+ done();
+ });
+ runner.fail(test, err);
});
- var test = new Test('a test', noop);
- runner.on(EVENT_TEST_FAIL, function(_test, _err) {
- expect(_err, 'to have message', 'not evil');
- 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(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_err, 'to be an', Error);
+ expect(
+ _err,
+ 'to have message',
+ 'the array [\n 1\n 2\n] was thrown, throw an Error :)'
+ );
+ done();
+ });
+ runner.fail(test, err);
});
- runner.fail(test, err);
- });
+ it('should recover if the error stack is not writable', function(done) {
+ if (!Object.create) {
+ this.skip();
+ return;
+ }
- it('should return and not increment failures when test is pending', function() {
- var test = new Test('a test');
- suite.addTest(test);
- test.pending = true;
- runner.fail(test, new Error());
- expect(runner.failures, 'to be', 0);
- });
+ var err = new Error('not evil');
+ Object.defineProperty(err, 'stack', {
+ value: err.stack
+ });
+ var test = new Test('a test', noop);
- describe('when Runner has stopped', function() {
- beforeEach(function() {
- runner.state = STATE_STOPPED;
+ runner.on(EVENT_TEST_FAIL, function(_test, _err) {
+ expect(_err, 'to have message', 'not evil');
+ done();
+ });
+
+ runner.fail(test, err);
});
- describe('when test is not pending', function() {
- describe('when error is the "multiple done" variety', function() {
- it('should throw the "multiple done" error', function() {
- var test = new Test('test', function() {});
- suite.addTest(test);
- var err = new Error();
- err.code = errors.constants.MULTIPLE_DONE;
- expect(
- function() {
- runner.fail(test, err);
- },
- 'to throw',
- err
- );
- });
+ it('should return and not increment failures when test is pending', function() {
+ var test = new Test('a test');
+ suite.addTest(test);
+ test.pending = true;
+ runner.fail(test, new Error());
+ expect(runner.failures, 'to be', 0);
+ });
+
+ describe('when Runner has stopped', function() {
+ beforeEach(function() {
+ runner.state = STATE_STOPPED;
});
- describe('when error is not of the "multiple done" variety', function() {
- it('should throw a "fatal" error', function() {
- var test = new Test('test', function() {});
- suite.addTest(test);
- var err = new Error();
- expect(
- function() {
- runner.fail(test, err);
- },
- 'to throw',
- {
- code: errors.constants.FATAL
- }
- );
+ describe('when test is not pending', function() {
+ describe('when error is the "multiple done" variety', function() {
+ it('should throw the "multiple done" error', function() {
+ var test = new Test('test', function() {});
+ suite.addTest(test);
+ var err = new Error();
+ err.code = errors.constants.MULTIPLE_DONE;
+ expect(
+ function() {
+ runner.fail(test, err);
+ },
+ 'to throw',
+ err
+ );
+ });
+ });
+
+ describe('when error is not of the "multiple done" variety', function() {
+ it('should throw a "fatal" error', function() {
+ var test = new Test('test', function() {});
+ suite.addTest(test);
+ var err = new Error();
+ expect(
+ function() {
+ runner.fail(test, err);
+ },
+ 'to throw',
+ {
+ code: errors.constants.FATAL
+ }
+ );
+ });
});
});
});
- });
- });
+ it('should increment .failures', function() {
+ expect(runner.failures, 'to be', 0);
+ var test1 = new Test('fail hook 1', noop);
+ var test2 = new Test('fail hook 2', noop);
+ suite.addTest(test1);
+ suite.addTest(test2);
+ runner.fail(test1, new Error('error1'));
+ expect(runner.failures, 'to be', 1);
+ runner.fail(test2, new Error('error2'));
+ expect(runner.failures, 'to be', 2);
+ });
- describe('.fail(hook, err)', function() {
- it('should increment .failures', function() {
- expect(runner.failures, 'to be', 0);
- var test1 = new Test('fail hook 1', noop);
- var test2 = new Test('fail hook 2', noop);
- suite.addTest(test1);
- suite.addTest(test2);
- runner.fail(test1, new Error('error1'));
- expect(runner.failures, 'to be', 1);
- runner.fail(test2, new Error('error2'));
- expect(runner.failures, 'to be', 2);
- });
+ it('should emit "fail"', function(done) {
+ var hook = new Hook();
+ hook.parent = suite;
+ var err = new Error('error');
+ runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
+ expect(_hook, 'to be', hook);
+ expect(_err, 'to be', err);
+ done();
+ });
+ runner.fail(hook, err);
+ });
- it('should emit "fail"', function(done) {
- var hook = new Hook();
- hook.parent = suite;
- var err = new Error('error');
- runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
- expect(_hook, 'to be', hook);
- expect(_err, 'to be', err);
+ it('should not emit "end" if suite bail is not true', function(done) {
+ var hook = new Hook();
+ hook.parent = suite;
+ var err = new Error('error');
+ suite.bail(false);
+ expect(
+ function() {
+ runner.fail(hook, err);
+ },
+ 'not to emit from',
+ hook,
+ EVENT_RUN_END
+ );
done();
});
- runner.fail(hook, err);
});
- it('should not emit "end" if suite bail is not true', function(done) {
- var hook = new Hook();
- hook.parent = suite;
- var err = new Error('error');
- suite.bail(false);
- expect(
- function() {
- runner.fail(hook, err);
- },
- 'not to emit from',
- hook,
- EVENT_RUN_END
- );
- done();
- });
- });
+ describe('run()', function() {
+ it('should emit "retry" when a retryable test fails', function(done) {
+ var retries = 2;
+ var retryableFails = 0;
+ var err = new Error('bear error');
- describe('.run(fn)', function() {
- it('should emit "retry" when a retryable test fails', function(done) {
- var retries = 2;
- var retryableFails = 0;
- var err = new Error('bear error');
+ var test = new Test('im a test about bears', function() {
+ if (retryableFails < retries) {
+ throw err;
+ }
+ });
- var test = new Test('im a test about bears', function() {
- if (retryableFails < retries) {
- throw err;
- }
- });
+ suite.retries(retries);
+ suite.addTest(test);
- suite.retries(retries);
- suite.addTest(test);
+ runner.on(EVENT_TEST_RETRY, function(testClone, testErr) {
+ retryableFails += 1;
+ expect(testClone.title, 'to be', test.title);
+ expect(testErr, 'to be', err);
+ });
- runner.on(EVENT_TEST_RETRY, function(testClone, testErr) {
- retryableFails += 1;
- expect(testClone.title, 'to be', test.title);
- expect(testErr, 'to be', err);
- });
+ runner.run(function(failures) {
+ expect(failures, 'to be', 0);
+ expect(retryableFails, 'to be', retries);
- runner.run(function(failures) {
- expect(failures, 'to be', 0);
- expect(retryableFails, 'to be', retries);
+ done();
+ });
+ });
- done();
+ // karma-mocha is inexplicably doing this with a Hook
+ it('should not throw an exception if something emits EVENT_TEST_END with a non-Test object', function() {
+ expect(function() {
+ runner.emit(EVENT_TEST_END, {});
+ }, 'not to throw');
});
- });
- // karma-mocha is inexplicably doing this with a Hook
- it('should not throw an exception if something emits EVENT_TEST_END with a non-Test object', function() {
- expect(function() {
- runner.emit(EVENT_TEST_END, {});
- }, 'not to throw');
- });
- it('should clean references after a run', function() {
- runner = new Runner(suite, {delay: false, cleanReferencesAfterRun: true});
- var cleanReferencesStub = sinon.stub(suite, 'cleanReferences');
- runner.run();
- runner.emit(EVENT_SUITE_END, suite);
- expect(cleanReferencesStub, 'was called once');
- });
+ it('should clean references after a run', function() {
+ runner = new Runner(suite, {
+ delay: false,
+ cleanReferencesAfterRun: true
+ });
+ var cleanReferencesStub = sinon.stub(suite, 'cleanReferences');
+ runner.run();
+ runner.emit(EVENT_SUITE_END, suite);
+ expect(cleanReferencesStub, 'was called once');
+ });
- it('should not clean references after a run when `cleanReferencesAfterRun` is `false`', function() {
- runner = new Runner(suite, {
- delay: false,
- cleanReferencesAfterRun: false
+ it('should not clean references after a run when `cleanReferencesAfterRun` is `false`', function() {
+ runner = new Runner(suite, {
+ delay: false,
+ cleanReferencesAfterRun: false
+ });
+ var cleanReferencesStub = sinon.stub(suite, 'cleanReferences');
+ runner.run();
+ runner.emit(EVENT_SUITE_END, suite);
+ expect(cleanReferencesStub, 'was not called');
});
- var cleanReferencesStub = sinon.stub(suite, 'cleanReferences');
- runner.run();
- runner.emit(EVENT_SUITE_END, suite);
- expect(cleanReferencesStub, 'was not called');
- });
- it('should not leak `Process.uncaughtException` listeners', function(done) {
- var normalUncaughtExceptionListenerCount = process.listenerCount(
- 'uncaughtException'
- );
-
- runner.run();
- runner.run();
- runner.run();
- expect(
- process.listenerCount('uncaughtException'),
- 'to be',
- normalUncaughtExceptionListenerCount + 1
- );
- done();
- });
+ it('should not leak `Process.uncaughtException` listeners', function(done) {
+ var normalUncaughtExceptionListenerCount = process.listenerCount(
+ 'uncaughtException'
+ );
- afterEach(function() {
- runner.dispose();
- });
- });
+ runner.run();
+ runner.run();
+ runner.run();
+ expect(
+ process.listenerCount('uncaughtException'),
+ 'to be',
+ normalUncaughtExceptionListenerCount + 1
+ );
+ done();
+ });
- describe('.dispose', function() {
- it('should remove all listeners from itself', function() {
- runner.on('disposeShouldRemoveThis', noop);
- runner.dispose();
- expect(runner.listenerCount('disposeShouldRemoveThis'), 'to be', 0);
- });
+ describe('stack traces', function() {
+ var stack = [
+ 'AssertionError: foo bar',
+ 'at EventEmitter.<anonymous> (/usr/local/dev/test.js:16:12)',
+ 'at Context.<anonymous> (/usr/local/dev/test.js:19:5)',
+ 'Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:244:7)',
+ 'Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:374:10)',
+ '/usr/local/lib/node_modules/mocha/lib/runner.js:452:12',
+ 'next (/usr/local/lib/node_modules/mocha/lib/runner.js:299:14)',
+ '/usr/local/lib/node_modules/mocha/lib/runner.js:309:7',
+ 'next (/usr/local/lib/node_modules/mocha/lib/runner.js:248:23)',
+ 'Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)',
+ 'at processImmediate [as _immediateCallback] (timers.js:321:17)'
+ ];
+
+ before(function() {
+ // Only for Node running on Windows
+ if (process.platform === 'win32') {
+ var addDrive = function(str) {
+ var drive = 'C:';
+ var pos = str.indexOf(path.posix.sep);
+ return pos !== -1
+ ? str.slice(0, pos) + drive + str.slice(pos)
+ : str;
+ };
+
+ var useWinPathSep = function(str) {
+ return str.split(path.posix.sep).join(path.win32.sep);
+ };
+
+ // Fake Windows pathnames in stacktrace
+ stack = stack.map(function(line) {
+ return useWinPathSep(addDrive(line));
+ });
+ }
+ });
- it('should remove "error" listeners from a test', function() {
- var fn = sinon.stub();
- runner.test = new Test('test for dispose', fn);
- runner.runTest(noop);
- // sanity check
- expect(runner.test.listenerCount('error'), 'to be', 1);
- runner.dispose();
- expect(runner.test.listenerCount('error'), 'to be', 0);
- });
+ describe('short', function() {
+ before(function() {
+ if (process.browser) {
+ this.skip();
+ }
+ });
- it('should remove "uncaughtException" listeners from the process', function() {
- var normalUncaughtExceptionListenerCount = process.listenerCount(
- 'uncaughtException'
- );
- runner.run(noop);
- // sanity check
- expect(
- process.listenerCount('uncaughtException'),
- 'to be',
- normalUncaughtExceptionListenerCount + 1
- );
- runner.dispose();
- expect(
- process.listenerCount('uncaughtException'),
- 'to be',
- normalUncaughtExceptionListenerCount
- );
- });
- });
+ it('should prettify the stack-trace', function(done) {
+ var hook = new Hook();
+ hook.parent = suite;
+ var err = new Error();
+ // Fake stack-trace
+ err.stack = stack.join('\n');
- describe('.runTest(fn)', function() {
- it('should return when no tests to run', function() {
- runner.test = undefined;
- expect(runner.runTest(noop), 'to be undefined');
- });
- });
+ runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
+ expect(_err.stack, 'to be', stack.slice(0, 3).join('\n'));
+ done();
+ });
+ runner.fail(hook, err);
+ });
+ });
- describe('allowUncaught', function() {
- it('should allow unhandled errors to propagate through', function() {
- var newRunner = new Runner(suite);
- newRunner.allowUncaught = true;
- newRunner.test = new Test('failing test', function() {
- throw new Error('allow unhandled errors');
- });
- function fail() {
- newRunner.runTest();
- }
- expect(fail, 'to throw', 'allow unhandled errors');
- });
+ describe('long', function() {
+ it('should display the full stack-trace', function(done) {
+ var hook = new Hook();
+ hook.parent = suite;
+ var err = new Error();
+ // Fake stack-trace
+ err.stack = stack.join('\n');
+ // Add --stack-trace option
+ runner.fullStackTrace = true;
+
+ runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
+ expect(_err.stack, 'to be', stack.join('\n'));
+ done();
+ });
+ runner.fail(hook, err);
+ });
+ });
- it('should not allow unhandled errors in sync hooks to propagate through', function(done) {
- suite.beforeEach(function() {
- throw new Error();
- });
- var runner = new Runner(suite);
- runner.allowUncaught = false;
-
- // We are monkey patching here with runner.once and a hook.run wrapper to effectively
- // capture thrown errors within the event loop phase where Runner.immediately executes
- runner.once(EVENT_HOOK_BEGIN, function(hook) {
- var _run = hook.run;
- hook.run = function(fn) {
- function throwError() {
- _run.call(hook, fn);
- }
- expect(throwError, 'not to throw');
- done();
- };
- });
+ describe('ginormous', function() {
+ before(function() {
+ if (process.browser) {
+ this.skip();
+ }
+ });
- runner.hook('beforeEach', noop);
- });
+ // Generate 64k string
+ function genOverlongSingleLineMessage() {
+ var n = 8200;
+ var data = [];
+ data.length = n;
+ for (var i = 0; i < n; i++) {
+ data[i] = {a: 1};
+ }
+ return JSON.stringify(data);
+ }
- it('should allow unhandled errors in sync hooks to propagate through', function(done) {
- suite.beforeEach(function() {
- throw new Error('allow unhandled errors in sync hooks');
- });
- var runner = new Runner(suite);
- runner.allowUncaught = true;
-
- runner.once(EVENT_HOOK_BEGIN, function(hook) {
- var _run = hook.run;
- hook.run = function(fn) {
- function throwError() {
- _run.call(hook, fn);
+ // Generate 64k string
+ function genOverlongMultiLineMessage() {
+ var n = 1150;
+ var data = [];
+ data.length = n;
+ var str =
+ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
+ for (var i = 0; i < n; i++) {
+ data[i] = str;
+ }
+ return data.join('\n');
}
- var expected = 'allow unhandled errors in sync hooks';
- expect(throwError, 'to throw', expected);
- done();
- };
- });
- runner.hook('beforeEach', noop);
- });
+ it('should not hang if overlong error message is single line', function(done) {
+ var hook = new Hook();
+ hook.parent = suite;
+ var message = genOverlongSingleLineMessage();
+ var err = new Error();
+ // Fake stack-trace
+ err.stack = [message].concat(stack).join('\n');
- it('async - should allow unhandled errors in hooks to propagate through', function(done) {
- // the `done` argument, although unused, it triggers the async path
- // see this.async in the Runnable constructor
- suite.beforeEach(function(done) {
- throw new Error('allow unhandled errors in async hooks');
- });
- var runner = new Runner(suite);
- runner.allowUncaught = true;
-
- runner.once(EVENT_HOOK_BEGIN, function(hook) {
- var _run = hook.run;
- hook.run = function(fn) {
- function throwError() {
- _run.call(hook, fn);
- }
- var expected = 'allow unhandled errors in async hooks';
- expect(throwError, 'to throw', expected);
- done();
- };
- });
+ runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
+ var filteredErrStack = _err.stack.split('\n').slice(1);
+ expect(
+ filteredErrStack.join('\n'),
+ 'to be',
+ stack.slice(0, 3).join('\n')
+ );
+ done();
+ });
+ runner.fail(hook, err);
+ });
- runner.hook('beforeEach', noop);
- });
- });
+ it('should not hang if overlong error message is multiple lines', function(done) {
+ var hook = new Hook();
+ hook.parent = suite;
+ var message = genOverlongMultiLineMessage();
+ var err = new Error();
+ // Fake stack-trace
+ err.stack = [message].concat(stack).join('\n');
- describe('stackTrace', function() {
- var stack = [
- 'AssertionError: foo bar',
- 'at EventEmitter.<anonymous> (/usr/local/dev/test.js:16:12)',
- 'at Context.<anonymous> (/usr/local/dev/test.js:19:5)',
- 'Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:244:7)',
- 'Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:374:10)',
- '/usr/local/lib/node_modules/mocha/lib/runner.js:452:12',
- 'next (/usr/local/lib/node_modules/mocha/lib/runner.js:299:14)',
- '/usr/local/lib/node_modules/mocha/lib/runner.js:309:7',
- 'next (/usr/local/lib/node_modules/mocha/lib/runner.js:248:23)',
- 'Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)',
- 'at processImmediate [as _immediateCallback] (timers.js:321:17)'
- ];
-
- before(function() {
- // Only for Node running on Windows
- if (process.platform === 'win32') {
- var addDrive = function(str) {
- var drive = 'C:';
- var pos = str.indexOf(path.posix.sep);
- return pos !== -1 ? str.slice(0, pos) + drive + str.slice(pos) : str;
- };
-
- var useWinPathSep = function(str) {
- return str.split(path.posix.sep).join(path.win32.sep);
- };
-
- // Fake Windows pathnames in stacktrace
- stack = stack.map(function(line) {
- return useWinPathSep(addDrive(line));
+ runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
+ var filteredErrStack = _err.stack.split('\n').slice(-3);
+ expect(
+ filteredErrStack.join('\n'),
+ 'to be',
+ stack.slice(0, 3).join('\n')
+ );
+ done();
+ });
+ runner.fail(hook, err);
+ });
});
- }
+ });
});
- describe('shortStackTrace', function() {
- before(function() {
- if (process.browser) {
- this.skip();
- }
+ describe('runAsync()', function() {
+ beforeEach(function() {
+ sinon
+ .stub(runner, 'run')
+ .callsArgWithAsync(0, 42)
+ .returnsThis();
});
- it('should prettify the stack-trace', function(done) {
- var hook = new Hook();
- hook.parent = suite;
- var err = new Error();
- // Fake stack-trace
- err.stack = stack.join('\n');
+ it('should return a Promise with a failure count', async function() {
+ return expect(runner.runAsync(), 'to be fulfilled with', 42);
+ });
- runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
- expect(_err.stack, 'to be', stack.slice(0, 3).join('\n'));
- done();
- });
- runner.fail(hook, err);
+ it('should pass through options to Runner#run', async function() {
+ await runner.runAsync({foo: 'bar'});
+ expect(runner.run, 'to have a call satisfying', [
+ expect.it('to be a function'),
+ {foo: 'bar'}
+ ]).and('was called once');
});
});
- describe('longStackTrace', function() {
- it('should display the full stack-trace', function(done) {
- var hook = new Hook();
- hook.parent = suite;
- var err = new Error();
- // Fake stack-trace
- err.stack = stack.join('\n');
- // Add --stack-trace option
- runner.fullStackTrace = true;
+ describe('dispose()', function() {
+ it('should remove all listeners from itself', function() {
+ runner.on('disposeShouldRemoveThis', noop);
+ runner.dispose();
+ expect(runner.listenerCount('disposeShouldRemoveThis'), 'to be', 0);
+ });
- runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
- expect(_err.stack, 'to be', stack.join('\n'));
- done();
- });
- runner.fail(hook, err);
+ it('should remove "error" listeners from a test', function() {
+ var fn = sinon.stub();
+ runner.test = new Test('test for dispose', fn);
+ runner.runTest(noop);
+ // sanity check
+ expect(runner.test.listenerCount('error'), 'to be', 1);
+ runner.dispose();
+ expect(runner.test.listenerCount('error'), 'to be', 0);
+ });
+
+ it('should remove "uncaughtException" listeners from the process', function() {
+ var normalUncaughtExceptionListenerCount = process.listenerCount(
+ 'uncaughtException'
+ );
+ runner.run(noop);
+ // sanity check
+ expect(
+ process.listenerCount('uncaughtException'),
+ 'to be',
+ normalUncaughtExceptionListenerCount + 1
+ );
+ runner.dispose();
+ expect(
+ process.listenerCount('uncaughtException'),
+ 'to be',
+ normalUncaughtExceptionListenerCount
+ );
});
});
- describe('hugeStackTrace', function() {
- before(function() {
- if (process.browser) {
- this.skip();
- }
+ describe('runTest()', function() {
+ it('should return when no tests to run', function() {
+ runner.test = undefined;
+ expect(runner.runTest(noop), 'to be undefined');
});
+ });
- // Generate 64k string
- function genOverlongSingleLineMessage() {
- var n = 8200;
- var data = [];
- data.length = n;
- for (var i = 0; i < n; i++) {
- data[i] = {a: 1};
- }
- return JSON.stringify(data);
- }
-
- // Generate 64k string
- function genOverlongMultiLineMessage() {
- var n = 1150;
- var data = [];
- data.length = n;
- var str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
- for (var i = 0; i < n; i++) {
- data[i] = str;
+ describe('allowUncaught()', function() {
+ it('should allow unhandled errors to propagate through', function() {
+ var newRunner = new Runner(suite);
+ newRunner.allowUncaught = true;
+ newRunner.test = new Test('failing test', function() {
+ throw new Error('allow unhandled errors');
+ });
+ function fail() {
+ newRunner.runTest();
}
- return data.join('\n');
- }
-
- it('should not hang if overlong error message is single line', function(done) {
- var hook = new Hook();
- hook.parent = suite;
- var message = genOverlongSingleLineMessage();
- var err = new Error();
- // Fake stack-trace
- err.stack = [message].concat(stack).join('\n');
+ expect(fail, 'to throw', 'allow unhandled errors');
+ });
- runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
- var filteredErrStack = _err.stack.split('\n').slice(1);
- expect(
- filteredErrStack.join('\n'),
- 'to be',
- stack.slice(0, 3).join('\n')
- );
- done();
+ it('should not allow unhandled errors in sync hooks to propagate through', function(done) {
+ suite.beforeEach(function() {
+ throw new Error();
});
- runner.fail(hook, err);
+ var runner = new Runner(suite);
+ runner.allowUncaught = false;
+
+ // We are monkey patching here with runner.once and a hook.run wrapper to effectively
+ // capture thrown errors within the event loop phase where Runner.immediately executes
+ runner.once(EVENT_HOOK_BEGIN, function(hook) {
+ var _run = hook.run;
+ hook.run = function(fn) {
+ function throwError() {
+ _run.call(hook, fn);
+ }
+ expect(throwError, 'not to throw');
+ done();
+ };
+ });
+
+ runner.hook('beforeEach', noop);
});
- it('should not hang if overlong error message is multiple lines', function(done) {
- var hook = new Hook();
- hook.parent = suite;
- var message = genOverlongMultiLineMessage();
- var err = new Error();
- // Fake stack-trace
- err.stack = [message].concat(stack).join('\n');
+ it('should allow unhandled errors in sync hooks to propagate through', function(done) {
+ suite.beforeEach(function() {
+ throw new Error('allow unhandled errors in sync hooks');
+ });
+ var runner = new Runner(suite);
+ runner.allowUncaught = true;
- runner.on(EVENT_TEST_FAIL, function(_hook, _err) {
- var filteredErrStack = _err.stack.split('\n').slice(-3);
- expect(
- filteredErrStack.join('\n'),
- 'to be',
- stack.slice(0, 3).join('\n')
- );
- done();
+ runner.once(EVENT_HOOK_BEGIN, function(hook) {
+ var _run = hook.run;
+ hook.run = function(fn) {
+ function throwError() {
+ _run.call(hook, fn);
+ }
+ var expected = 'allow unhandled errors in sync hooks';
+ expect(throwError, 'to throw', expected);
+ done();
+ };
});
- runner.fail(hook, err);
- });
- });
- });
- describe('abort', function() {
- it('should set _abort property to true', function() {
- runner.abort();
- expect(runner._abort, 'to be true');
- });
+ runner.hook('beforeEach', noop);
+ });
- it('should return the Runner', function() {
- expect(runner.abort(), 'to be', runner);
- });
- });
+ it('async - should allow unhandled errors in hooks to propagate through', function(done) {
+ // the `done` argument, although unused, it triggers the async path
+ // see this.async in the Runnable constructor
+ suite.beforeEach(function(done) {
+ throw new Error('allow unhandled errors in async hooks');
+ });
+ var runner = new Runner(suite);
+ runner.allowUncaught = true;
- describe('_uncaught()', function() {
- describe('when called with a non-Runner context', function() {
- it('should throw', function() {
- expect(runner._uncaught.bind({}), 'to throw', {
- code: errors.constants.FATAL
+ runner.once(EVENT_HOOK_BEGIN, function(hook) {
+ var _run = hook.run;
+ hook.run = function(fn) {
+ function throwError() {
+ _run.call(hook, fn);
+ }
+ var expected = 'allow unhandled errors in async hooks';
+ expect(throwError, 'to throw', expected);
+ done();
+ };
});
- });
- });
- });
- describe('uncaught()', function() {
- beforeEach(function() {
- sinon.stub(runner, 'fail');
+ runner.hook('beforeEach', noop);
+ });
});
- describe('when allow-uncaught is set to true', function() {
- it('should propagate error and throw', function() {
- if (process.browser) this.skip();
+ describe('abort()', function() {
+ it('should set _abort property to true', function() {
+ runner.abort();
+ expect(runner._abort, 'to be true');
+ });
- var err = new Error('should rethrow err');
- runner.allowUncaught = true;
- expect(
- function() {
- runner.uncaught(err);
- },
- 'to throw',
- 'should rethrow err'
- );
+ it('should return the Runner', function() {
+ expect(runner.abort(), 'to be', runner);
});
});
- describe('when provided an object argument', function() {
- describe('when argument is not an Error', function() {
- var err;
- beforeEach(function() {
- err = {whatever: 'yolo'};
- });
-
- it('should fail with a transient Runnable and a new Error coerced from the object', function() {
- runner.uncaught(err);
-
- expect(runner.fail, 'to have all calls satisfying', [
- expect.it('to be a', Runnable).and('to satisfy', {
- parent: runner.suite,
- title: /uncaught error outside test suite/i
- }),
- expect.it('to be an', Error).and('to satisfy', {
- message: /throw an error/i,
- uncaught: true
- })
- ]).and('was called once');
+ describe('_uncaught()', function() {
+ describe('when called with a non-Runner context', function() {
+ it('should throw', function() {
+ expect(runner._uncaught.bind({}), 'to throw', {
+ code: errors.constants.FATAL
+ });
});
});
+ });
- describe('when argument is a Pending', function() {
- it('should ignore argument and return', function() {
- var err = new Pending();
- expect(runner.uncaught(err), 'to be undefined');
- });
+ describe('uncaught()', function() {
+ beforeEach(function() {
+ sinon.stub(runner, 'fail');
});
- describe('when argument is an Error', function() {
- var err;
- beforeEach(function() {
- err = new Error('sorry dave');
- });
+ describe('when allow-uncaught is set to true', function() {
+ it('should propagate error and throw', function() {
+ if (process.browser) this.skip();
- it('should add the "uncaught" property to the Error', function() {
- runner.uncaught(err);
- expect(err, 'to have property', 'uncaught', true);
+ var err = new Error('should rethrow err');
+ runner.allowUncaught = true;
+ expect(
+ function() {
+ runner.uncaught(err);
+ },
+ 'to throw',
+ 'should rethrow err'
+ );
});
+ });
- describe('when no Runnables are running', function() {
+ describe('when provided an object argument', function() {
+ describe('when argument is not an Error', function() {
+ var err;
beforeEach(function() {
- delete runner.currentRunnable;
+ err = {whatever: 'yolo'};
});
- it('should fail with a transient Runnable and the error', function() {
+ it('should fail with a transient Runnable and a new Error coerced from the object', function() {
runner.uncaught(err);
expect(runner.fail, 'to have all calls satisfying', [
@@ -945,212 +929,252 @@ describe('Runner', function() {
parent: runner.suite,
title: /uncaught error outside test suite/i
}),
- err
+ expect.it('to be an', Error).and('to satisfy', {
+ message: /throw an error/i,
+ uncaught: true
+ })
]).and('was called once');
});
+ });
- describe('when Runner is RUNNING', function() {
- beforeEach(function() {
- runner.state = STATE_RUNNING;
- });
-
- it('should not emit start/end events', function() {
- expect(
- function() {
- runner.uncaught(err);
- },
- 'not to emit from',
- runner,
- 'start'
- ).and('not to emit from', runner, 'end');
- });
- });
-
- describe('when Runner is IDLE', function() {
- beforeEach(function() {
- runner.state = STATE_IDLE;
- });
-
- it('should emit start/end events for the benefit of reporters', function() {
- expect(
- function() {
- runner.uncaught(err);
- },
- 'to emit from',
- runner,
- 'start'
- ).and('to emit from', runner, 'end');
- });
- });
-
- describe('when Runner is STOPPED', function() {
- beforeEach(function() {
- runner.state = STATE_STOPPED;
- });
-
- it('should not emit start/end events, since this presumably would have already happened', function() {
- expect(
- function() {
- try {
- runner.uncaught(err);
- } catch (ignored) {}
- },
- 'not to emit from',
- runner,
- 'start'
- ).and('not to emit from', runner, 'end');
- });
-
- it('should throw', function() {
- expect(function() {
- runner.uncaught(err);
- }, 'to throw');
- });
+ describe('when argument is a Pending', function() {
+ it('should ignore argument and return', function() {
+ var err = new Pending();
+ expect(runner.uncaught(err), 'to be undefined');
});
});
- describe('when a Runnable is running or has run', function() {
- var runnable;
+ describe('when argument is an Error', function() {
+ var err;
beforeEach(function() {
- runnable = new Runnable();
- runnable.parent = runner.suite;
- sinon.stub(runnable, 'clearTimeout');
- runner.currentRunnable = runnable;
+ err = new Error('sorry dave');
});
- it('should clear any pending timeouts', function() {
- runnable.callback = sinon.fake();
+ it('should add the "uncaught" property to the Error', function() {
runner.uncaught(err);
- expect(runnable.clearTimeout, 'was called times', 1);
+ expect(err, 'to have property', 'uncaught', true);
});
- describe('when current Runnable has already failed', function() {
+ describe('when no Runnables are running', function() {
beforeEach(function() {
- sinon.stub(runnable, 'isFailed').returns(true);
+ delete runner.currentRunnable;
});
- it('should not attempt to fail again', function() {
- runner.uncaught(err);
- expect(runner.fail, 'was not called');
- });
- });
-
- describe('when current Runnable has been marked pending', function() {
- beforeEach(function() {
- sinon.stub(runnable, 'isPending').returns(true);
- });
-
- it('should attempt to fail', function() {
- runner.uncaught(err);
- expect(runner.fail, 'was called once');
- });
- });
-
- describe('when the current Runnable has already passed', function() {
- beforeEach(function() {
- sinon.stub(runnable, 'isPassed').returns(true);
- });
-
- it('should fail with the current Runnable and the error', function() {
+ it('should fail with a transient Runnable and the error', function() {
runner.uncaught(err);
expect(runner.fail, 'to have all calls satisfying', [
- expect.it('to be', runnable),
+ expect.it('to be a', Runnable).and('to satisfy', {
+ parent: runner.suite,
+ title: /uncaught error outside test suite/i
+ }),
err
]).and('was called once');
});
- it('should abort the runner without emitting end event', function() {
- expect(
- function() {
- runner.uncaught(err);
- },
- 'not to emit from',
- runner,
- 'end'
- );
- expect(runner._abort, 'to be', true);
- });
- });
-
- describe('when the current Runnable is still running', function() {
- describe('when the current Runnable is a Test', function() {
+ describe('when Runner is RUNNING', function() {
beforeEach(function() {
- runnable = new Test('goomba', noop);
- runnable.parent = runner.suite;
- runner.currentRunnable = runnable;
- runnable.callback = sinon.fake();
+ runner.state = STATE_RUNNING;
});
- it('should run callback(err) to handle failing and hooks', function() {
- runner.uncaught(err);
+ it('should not emit start/end events', function() {
+ expect(
+ function() {
+ runner.uncaught(err);
+ },
+ 'not to emit from',
+ runner,
+ 'start'
+ ).and('not to emit from', runner, 'end');
+ });
+ });
- expect(runner.fail, 'was not called');
- expect(runnable.callback, 'to have all calls satisfying', [
- err
- ]).and('was called once');
+ describe('when Runner is IDLE', function() {
+ beforeEach(function() {
+ runner.state = STATE_IDLE;
});
- it('should not notify test has ended', function() {
+ it('should emit start/end events for the benefit of reporters', function() {
expect(
function() {
runner.uncaught(err);
},
- 'not to emit from',
+ 'to emit from',
runner,
- EVENT_TEST_END
- );
+ 'start'
+ ).and('to emit from', runner, 'end');
+ });
+ });
+
+ describe('when Runner is STOPPED', function() {
+ beforeEach(function() {
+ runner.state = STATE_STOPPED;
});
- it('should not notify run has ended', function() {
+ it('should not emit start/end events, since this presumably would have already happened', function() {
expect(
function() {
- runner.uncaught(err);
+ try {
+ runner.uncaught(err);
+ } catch (ignored) {}
},
'not to emit from',
runner,
- EVENT_RUN_END
- );
+ 'start'
+ ).and('not to emit from', runner, 'end');
+ });
+
+ it('should throw', function() {
+ expect(function() {
+ runner.uncaught(err);
+ }, 'to throw');
});
});
+ });
+
+ describe('when a Runnable is running or has run', function() {
+ var runnable;
+ beforeEach(function() {
+ runnable = new Runnable();
+ runnable.parent = runner.suite;
+ sinon.stub(runnable, 'clearTimeout');
+ runner.currentRunnable = runnable;
+ });
+
+ it('should clear any pending timeouts', function() {
+ runnable.callback = sinon.fake();
+ runner.uncaught(err);
+ expect(runnable.clearTimeout, 'was called times', 1);
+ });
- describe('when the current Runnable is a Hook', function() {
+ describe('when current Runnable has already failed', function() {
beforeEach(function() {
- runnable = new Hook();
- runnable.parent = runner.suite;
- runner.currentRunnable = runnable;
- runnable.callback = sinon.fake();
+ sinon.stub(runnable, 'isFailed').returns(true);
});
- it('should run callback(err) to handle failing hook pattern', function() {
+ it('should not attempt to fail again', function() {
runner.uncaught(err);
-
expect(runner.fail, 'was not called');
- expect(runnable.callback, 'to have all calls satisfying', [
+ });
+ });
+
+ describe('when current Runnable has been marked pending', function() {
+ beforeEach(function() {
+ sinon.stub(runnable, 'isPending').returns(true);
+ });
+
+ it('should attempt to fail', function() {
+ runner.uncaught(err);
+ expect(runner.fail, 'was called once');
+ });
+ });
+
+ describe('when the current Runnable has already passed', function() {
+ beforeEach(function() {
+ sinon.stub(runnable, 'isPassed').returns(true);
+ });
+
+ it('should fail with the current Runnable and the error', function() {
+ runner.uncaught(err);
+
+ expect(runner.fail, 'to have all calls satisfying', [
+ expect.it('to be', runnable),
err
]).and('was called once');
});
- it('should not notify test has ended', function() {
+ it('should abort the runner without emitting end event', function() {
expect(
function() {
runner.uncaught(err);
},
'not to emit from',
runner,
- EVENT_TEST_END
+ 'end'
);
+ expect(runner._abort, 'to be', true);
});
+ });
- it('should not notify run has ended', function() {
- expect(
- function() {
- runner.uncaught(err);
- },
- 'not to emit from',
- runner,
- EVENT_RUN_END
- );
+ describe('when the current Runnable is still running', function() {
+ describe('when the current Runnable is a Test', function() {
+ beforeEach(function() {
+ runnable = new Test('goomba', noop);
+ runnable.parent = runner.suite;
+ runner.currentRunnable = runnable;
+ runnable.callback = sinon.fake();
+ });
+
+ it('should run callback(err) to handle failing and hooks', function() {
+ runner.uncaught(err);
+
+ expect(runner.fail, 'was not called');
+ expect(runnable.callback, 'to have all calls satisfying', [
+ err
+ ]).and('was called once');
+ });
+
+ it('should not notify test has ended', function() {
+ expect(
+ function() {
+ runner.uncaught(err);
+ },
+ 'not to emit from',
+ runner,
+ EVENT_TEST_END
+ );
+ });
+
+ it('should not notify run has ended', function() {
+ expect(
+ function() {
+ runner.uncaught(err);
+ },
+ 'not to emit from',
+ runner,
+ EVENT_RUN_END
+ );
+ });
+ });
+
+ describe('when the current Runnable is a Hook', function() {
+ beforeEach(function() {
+ runnable = new Hook();
+ runnable.parent = runner.suite;
+ runner.currentRunnable = runnable;
+ runnable.callback = sinon.fake();
+ });
+
+ it('should run callback(err) to handle failing hook pattern', function() {
+ runner.uncaught(err);
+
+ expect(runner.fail, 'was not called');
+ expect(runnable.callback, 'to have all calls satisfying', [
+ err
+ ]).and('was called once');
+ });
+
+ it('should not notify test has ended', function() {
+ expect(
+ function() {
+ runner.uncaught(err);
+ },
+ 'not to emit from',
+ runner,
+ EVENT_TEST_END
+ );
+ });
+
+ it('should not notify run has ended', function() {
+ expect(
+ function() {
+ runner.uncaught(err);
+ },
+ 'not to emit from',
+ runner,
+ EVENT_RUN_END
+ );
+ });
});
});
});
diff --git a/test/unit/suite.spec.js b/test/unit/suite.spec.js
index 06752dab..05cb75f5 100644
--- a/test/unit/suite.spec.js
+++ b/test/unit/suite.spec.js
@@ -4,7 +4,7 @@ var Mocha = require('../../lib/mocha');
var Suite = Mocha.Suite;
var Test = Mocha.Test;
var sinon = require('sinon');
-var utils = Mocha.utils;
+const errors = require('../../lib/errors');
function supportsFunctionNames() {
// eslint-disable-next-line no-extra-parens
@@ -551,7 +551,7 @@ describe('Suite', function() {
describe('constructor', function() {
beforeEach(function() {
- sinon.stub(utils, 'deprecate');
+ sinon.stub(errors, 'deprecate');
});
/* eslint no-new: off */
@@ -573,7 +573,7 @@ describe('Suite', function() {
it('should report listened-for deprecated events as deprecated', function() {
new Suite('foo').on(Suite.constants.EVENT_SUITE_ADD_TEST, function() {});
- expect(utils.deprecate, 'to have all calls satisfying', [
+ expect(errors.deprecate, 'to have a call satisfying', [
/Event "[^"]+" is deprecated/i
]);
});
diff --git a/test/unit/utils.spec.js b/test/unit/utils.spec.js
index 3fa408d0..5acd79dc 100644
--- a/test/unit/utils.spec.js
+++ b/test/unit/utils.spec.js
@@ -1,6 +1,7 @@
'use strict';
var utils = require('../../lib/utils');
+const errors = require('../../lib/errors');
var sinon = require('sinon');
describe('lib/utils', function() {
@@ -607,82 +608,6 @@ describe('lib/utils', function() {
});
});
- describe('deprecate()', function() {
- var emitWarning;
-
- beforeEach(function() {
- if (process.emitWarning) {
- emitWarning = process.emitWarning;
- sinon.stub(process, 'emitWarning');
- } else {
- process.emitWarning = sinon.spy();
- }
- utils.deprecate.cache = {};
- });
-
- afterEach(function() {
- // if this is not set, then we created it, so we should remove it.
- if (!emitWarning) {
- delete process.emitWarning;
- }
- });
-
- it('should coerce its parameter to a string', function() {
- utils.deprecate(1);
- expect(process.emitWarning, 'to have a call satisfying', [
- '1',
- 'DeprecationWarning'
- ]);
- });
-
- it('should cache the message', function() {
- utils.deprecate('foo');
- utils.deprecate('foo');
- expect(process.emitWarning, 'was called times', 1);
- });
-
- it('should ignore falsy messages', function() {
- utils.deprecate('');
- expect(process.emitWarning, 'was not called');
- });
- });
-
- describe('warn()', function() {
- var emitWarning;
-
- beforeEach(function() {
- if (process.emitWarning) {
- emitWarning = process.emitWarning;
- sinon.stub(process, 'emitWarning');
- } else {
- process.emitWarning = sinon.spy();
- }
- });
-
- afterEach(function() {
- // if this is not set, then we created it, so we should remove it.
- if (!emitWarning) {
- delete process.emitWarning;
- }
- });
-
- it('should call process.emitWarning', function() {
- utils.warn('foo');
- expect(process.emitWarning, 'was called times', 1);
- });
-
- it('should not cache messages', function() {
- utils.warn('foo');
- utils.warn('foo');
- expect(process.emitWarning, 'was called times', 2);
- });
-
- it('should ignore falsy messages', function() {
- utils.warn('');
- expect(process.emitWarning, 'was not called');
- });
- });
-
describe('sQuote()', function() {
var str = 'xxx';
@@ -743,9 +668,58 @@ describe('lib/utils', function() {
});
});
+ describe('castArray()', function() {
+ describe('when provided an array value', function() {
+ it('should return a copy of the array', function() {
+ const v = ['foo', 'bar', 'baz'];
+ expect(utils.castArray(v), 'to equal', ['foo', 'bar', 'baz']).and(
+ 'not to be',
+ v
+ );
+ });
+ });
+
+ describe('when provided an "arguments" value', function() {
+ it('should return an array containing the arguments', function() {
+ (function() {
+ expect(utils.castArray(arguments), 'to equal', [
+ 'foo',
+ 'bar',
+ 'baz'
+ ]).and('not to be', arguments);
+ })('foo', 'bar', 'baz');
+ });
+ });
+
+ describe('when provided an object', function() {
+ it('should return an array containing the object only', function() {
+ const v = {foo: 'bar'};
+ expect(utils.castArray(v), 'to equal', [v]);
+ });
+ });
+
+ describe('when provided no parameters', function() {
+ it('should return an empty array', function() {
+ expect(utils.castArray(), 'to equal', []);
+ });
+ });
+
+ describe('when provided a primitive value', function() {
+ it('should return an array containing the primitive value only', function() {
+ expect(utils.castArray('butts'), 'to equal', ['butts']);
+ });
+ });
+
+ describe('when provided null', function() {
+ it('should return an array containing a null value only', function() {
+ expect(utils.castArray(null), 'to equal', [null]);
+ });
+ });
+ });
+
describe('lookupFiles()', function() {
beforeEach(function() {
- sinon.stub(utils, 'deprecate');
+ sinon.stub(errors, 'deprecate');
});
describe('when run in Node.js', function() {
@@ -762,7 +736,7 @@ describe('lib/utils', function() {
it('should print a deprecation message', function() {
utils.lookupFiles();
- expect(utils.deprecate, 'was called once');
+ expect(errors.deprecate, 'was called once');
});
it('should delegate to new location of lookupFiles()', function() {