☕️ Classic, reliable, trusted test framework for Node.js and the browser
Growl: Web notifications & Desktop prerequisite software check (#3542)
P. Roebuck81c60f92cdc7
diff --git a/assets/mocha-logo-96.png b/assets/mocha-logo-96.pngnew file mode 100644index 00000000..dba31bc9Binary files /dev/null and b/assets/mocha-logo-96.png differdiff --git a/docs/index.md b/docs/index.mdindex d8a76a8a..6a18e0bc 100644--- a/docs/index.md+++ b/docs/index.md@@ -26,7 +26,7 @@ Mocha is a feature-rich JavaScript test framework running on [Node.js](https://n- [async test timeout support](#delayed-root-suite)- [test retry support](#retry-tests)- [test-specific timeouts](#test-level)-- [growl notification support](#mochaopts)+- [Growl support](#desktop-notification-support)- [reports test durations](#test-duration)- [highlights slow tests](#dot-matrix)- [file watcher support](#min)@@ -70,6 +70,7 @@ Mocha is a feature-rich JavaScript test framework running on [Node.js](https://n- [Interfaces](#interfaces)- [Reporters](#reporters)- [Running Mocha in the Browser](#running-mocha-in-the-browser)+- [Desktop Notification Support](#desktop-notification-support)- [Configuring Mocha (Node.js)](#configuring-mocha-nodejs)- [`mocha.opts`](#mochaopts)- [The `test/` Directory](#the-test-directory)@@ -748,7 +749,7 @@ To tweak what's considered "slow", you can use the `slow()` method:```jsdescribe('something slow', function() {- this.slow(10000);+ this.slow(300000); // five minutesit('should take long enough for me to go make a sandwich', function() {// ...@@ -1487,20 +1488,22 @@ A typical setup might look something like the following, where we call `mocha.se<head><meta charset="utf-8"><title>Mocha Tests</title>- <link href="https://unpkg.com/[email protected]/mocha.css" rel="stylesheet" />+ <link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" /></head><body><div id="mocha"></div><script src="https://unpkg.com/chai/chai.js"></script>- <script src="https://unpkg.com/[email protected]/mocha.js"></script>+ <script src="https://unpkg.com/mocha/mocha.js"></script>- <script>mocha.setup('bdd')</script>+ <script class="mocha-init">+ mocha.setup('bdd');+ mocha.checkLeaks();+ </script><script src="test.array.js"></script><script src="test.object.js"></script><script src="test.xhr.js"></script>- <script>- mocha.checkLeaks();+ <script class="mocha-exec">mocha.run();</script></body>@@ -1547,6 +1550,69 @@ The "HTML" reporter is what you see when running Mocha in the browser. It looks[Mochawesome](https://www.npmjs.com/package/mochawesome) is a great alternative to the default HTML reporter.+## Desktop Notification Support++Desktop notifications allow asynchronous communication of events without+forcing you to react to a notification immediately. Their appearance+and specific functionality vary across platforms. They typically disappear+automatically after a short delay, but their content is often stored in some+manner that allows you to access past notifications.++[Growl][] was an early notification system implementation for OS X and Windows,+hence, the name of Mocha's `--growl` option.++Once enabled, when your root suite completes test execution, a desktop+notification should appear informing you whether your tests passed or failed.++### Node-based notifications++In order to use desktop notifications with the command-line interface (CLI),+you **must** first install some platform-specific prerequisite software.+Instructions for doing so can be found [here][Growl-install].++Enable Mocha's desktop notifications as follows:++```sh+$ mocha --growl+```++### Browser-based notifications++Web notification support is being made available for current versions of+modern browsers. Ensure your browser version supports both+[promises](https://caniuse.com/#feat=promises) and+[web notifications](https://caniuse.com/#feat=notifications). As the+Notification API evolved over time, **do not expect** the minimum possible+browser version to necessarily work.++Enable Mocha's web notifications with a slight modification to your+client-side mocha HTML. Add a call to `mocha.growl()` prior to running your+tests as shown below:++```html+<!DOCTYPE html>+<html>+ <head>+ <title>Mocha</title>+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />+ </head>+ <body>+ <div id="mocha"></div>+ <script src="https://unpkg.com/mocha/mocha.js"></script>+ <script class="mocha-init">+ mocha.setup('bdd');+ mocha.growl(); // <-- Enables web notifications+ </script>+ <script src="tests.js"></script>+ <script class="mocha-exec">+ mocha.run();+ </script>+ </body>+</html>+```+## Configuring Mocha (Node.js)> *New in v6.0.0*@@ -1631,11 +1697,11 @@ For example, suppose you have the following `mocha.opts` file:The settings above will default the reporter to `dot`, require the `should`library, and use `bdd` as the interface. With this, you may then invoke `mocha`-with additional arguments, here enabling [Growl](http://growl.info/) support,-and changing the reporter to `list`:+with additional arguments, here changing the reporter to `list` and setting the+slow threshold to half a second:```sh-$ mocha --reporter list --growl+$ mocha --reporter list --slow 500```To ignore your `mocha.opts`, use the `--no-opts` option.@@ -1727,7 +1793,20 @@ $ REPORTER=nyan npm test## More Information-In addition to chatting with us on [Gitter], for additional information such as using spies, mocking, and shared behaviours be sure to check out the [Mocha Wiki](https://github.com/mochajs/mocha/wiki) on GitHub. For discussions join the [Google Group](https://groups.google.com/group/mochajs). For a running example of Mocha, view [example/tests.html](example/tests.html). For the JavaScript API, view the [API documentation](api/) or the [source](https://github.com/mochajs/mocha/blob/master/lib/mocha.js#L51).+In addition to chatting with us on [Gitter][Gitter-mocha], for additional information such as using+spies, mocking, and shared behaviours be sure to check out the [Mocha Wiki][Mocha-wiki] on GitHub.+For discussions join the [Google Group][Google-mocha]. For a running example of Mocha, view+[example/tests.html](example/tests.html). For the JavaScript API, view the [API documentation](api/)+or the [source](https://github.com/mochajs/mocha/blob/master/lib/mocha.js).++[//]: # (Cross reference section)++[Gitter-mocha]: https://gitter.im/mochajs/mocha+[Google-mocha]: https://groups.google.com/group/mochajs+[Growl]: http://growl.info/+[Growl-install]: https://github.com/mochajs/mocha/wiki/Growl-Notifications+[Mocha-website]: https://mochajs.org/+[Mocha-wiki]: https://github.com/mochajs/mocha/wiki<!-- AUTO-GENERATED-CONTENT:START (manifest:template=[Gitter]: ${gitter}) -->[Gitter]: https://gitter.im/mochajs/mochadiff --git a/lib/browser/growl.js b/lib/browser/growl.jsindex 28c62efb..a6764897 100644--- a/lib/browser/growl.js+++ b/lib/browser/growl.js@@ -1,5 +1,167 @@'use strict';-// just stub out growl+/**+ * Web Notifications module.+ * @module Growl+ */-module.exports = require('../utils').noop;+/**+ * Save timer references to avoid Sinon interfering (see GH-237).+ */+var Date = global.Date;+var setTimeout = global.setTimeout;++/**+ * Checks if browser notification support exists.+ *+ * @public+ * @see {@link https://caniuse.com/#feat=notifications|Browser support (notifications)}+ * @see {@link https://caniuse.com/#feat=promises|Browser support (promises)}+ * @see {@link Mocha#growl}+ * @see {@link Mocha#isGrowlCapable}+ * @return {boolean} whether browser notification support exists+ */+exports.isCapable = function() {+ var hasNotificationSupport = 'Notification' in window;+ var hasPromiseSupport = typeof Promise === 'function';+ return process.browser && hasNotificationSupport && hasPromiseSupport;+};++/**+ * Implements browser notifications as a pseudo-reporter.+ *+ * @public+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/notification|Notification API}+ * @see {@link https://developers.google.com/web/fundamentals/push-notifications/display-a-notification|Displaying a Notification}+ * @see {@link Growl#isPermitted}+ * @see {@link Mocha#_growl}+ * @param {Runner} runner - Runner instance.+ */+exports.notify = function(runner) {+ var promise = isPermitted();++ /**+ * Attempt notification.+ */+ var sendNotification = function() {+ // If user hasn't responded yet... "No notification for you!" (Seinfeld)+ Promise.race([promise, Promise.resolve(undefined)])+ .then(canNotify)+ .then(function() {+ display(runner);+ })+ .catch(notPermitted);+ };++ runner.once('end', sendNotification);+};++/**+ * Checks if browser notification is permitted by user.+ *+ * @private+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Notification/permission|Notification.permission}+ * @see {@link Mocha#growl}+ * @see {@link Mocha#isGrowlPermitted}+ * @returns {Promise<boolean>} promise determining if browser notification+ * permissible when fulfilled.+ */+function isPermitted() {+ var permitted = {+ granted: function allow() {+ return Promise.resolve(true);+ },+ denied: function deny() {+ return Promise.resolve(false);+ },+ default: function ask() {+ return Notification.requestPermission().then(function(permission) {+ return permission === 'granted';+ });+ }+ };++ return permitted[Notification.permission]();+}++/**+ * @summary+ * Determines if notification should proceed.+ *+ * @description+ * Notification shall <strong>not</strong> proceed unless `value` is true.+ *+ * `value` will equal one of:+ * <ul>+ * <li><code>true</code> (from `isPermitted`)</li>+ * <li><code>false</code> (from `isPermitted`)</li>+ * <li><code>undefined</code> (from `Promise.race`)</li>+ * </ul>+ *+ * @private+ * @param {boolean|undefined} value - Determines if notification permissible.+ * @returns {Promise<undefined>} Notification can proceed+ */+function canNotify(value) {+ if (!value) {+ var why = value === false ? 'blocked' : 'unacknowledged';+ var reason = 'not permitted by user (' + why + ')';+ return Promise.reject(new Error(reason));+ }+ return Promise.resolve();+}++/**+ * Displays the notification.+ *+ * @private+ * @param {Runner} runner - Runner instance.+ */+function display(runner) {+ var stats = runner.stats;+ var symbol = {+ cross: '\u274C',+ tick: '\u2705'+ };+ var logo = require('../../package').notifyLogo;+ var _message;+ var message;+ var title;++ if (stats.failures) {+ _message = stats.failures + ' of ' + runner.total + ' tests failed';+ message = symbol.cross + ' ' + _message;+ title = 'Failed';+ } else {+ _message = stats.passes + ' tests passed in ' + stats.duration + 'ms';+ message = symbol.tick + ' ' + _message;+ title = 'Passed';+ }++ // Send notification+ var options = {+ badge: logo,+ body: message,+ dir: 'ltr',+ icon: logo,+ lang: 'en-US',+ name: 'mocha',+ requireInteraction: false,+ timestamp: Date.now()+ };+ var notification = new Notification(title, options);++ // Autoclose after brief delay (makes various browsers act same)+ var FORCE_DURATION = 4000;+ setTimeout(notification.close.bind(notification), FORCE_DURATION);+}++/**+ * As notifications are tangential to our purpose, just log the error.+ *+ * @private+ * @param {Error} err - Why notification didn't happen.+ */+function notPermitted(err) {+ console.error('notification error:', err.message);+}diff --git a/lib/growl.js b/lib/growl.jsnew file mode 100644index 00000000..ee3d2323--- /dev/null+++ b/lib/growl.js@@ -0,0 +1,161 @@+'use strict';++/**+ * Desktop Notifications module.+ * @module Growl+ */++var fs = require('fs');+var os = require('os');+var path = require('path');++/**+ * @summary+ * Checks if Growl notification support seems likely.+ *+ * @description+ * Glosses over the distinction between an unsupported platform+ * and one that lacks prerequisite software installations.+ *+ * @public+ * @see {@link https://github.com/tj/node-growl/blob/master/README.md|Prerequisite Installs}+ * @see {@link Mocha#growl}+ * @see {@link Mocha#isGrowlCapable}+ * @return {boolean} whether Growl notification support can be expected+ */+exports.isCapable = function() {+ return !process.browser && which(getSupportBinaries()) !== '';+};++/**+ * Implements desktop notifications as a pseudo-reporter.+ *+ * @public+ * @see {@link Mocha#_growl}+ * @param {Runner} runner - Runner instance.+ */+exports.notify = function(runner) {+ var sendNotification = function() {+ display(runner);+ };+ runner.once('end', sendNotification);+};++/**+ * Displays the notification.+ *+ * @private+ * @param {Runner} runner - Runner instance.+ */+function display(runner) {+ var growl = require('growl');+ var stats = runner.stats;+ var symbol = {+ cross: '\u274C',+ tick: '\u2705'+ };+ var _message;+ var message;+ var title;++ if (stats.failures) {+ _message = stats.failures + ' of ' + runner.total + ' tests failed';+ message = symbol.cross + ' ' + _message;+ title = 'Failed';+ } else {+ _message = stats.passes + ' tests passed in ' + stats.duration + 'ms';+ message = symbol.tick + ' ' + _message;+ title = 'Passed';+ }++ // Send notification+ var options = {+ image: logo(),+ name: 'mocha',+ title: title+ };+ growl(message, options, onCompletion);+}++/**+ * @summary+ * Callback for result of attempted Growl notification.+ *+ * @description+ * Despite its appearance, this is <strong>not</strong> an Error-first+ * callback -- all parameters are populated regardless of success.+ *+ * @private+ * @callback Growl~growlCB+ * @param {*} err - Error object, or <code>null</code> if successful.+ * @param {string} stdout - <code>stdout</code> from notification delivery+ * process.+ * @param {string} stderr - <code>stderr</code> from notification delivery+ * process. It will include timestamp and executed command with arguments.+ */+function onCompletion(err, stdout, stderr) {+ if (err) {+ // As notifications are tangential to our purpose, just log the error.+ var message =+ err.code === 'ENOENT' ? 'prerequisite software not found' : err.message;+ console.error('notification error:', message);+ }+}++/**+ * Returns Mocha logo image path.+ *+ * @private+ * @return {string} Pathname of Mocha logo+ */+function logo() {+ return path.join(__dirname, '..', 'assets', 'mocha-logo-96.png');+}++/**+ * @summary+ * Locates a binary in the user's `PATH` environment variable.+ *+ * @description+ * Takes a list of command names and searches the path for each executable+ * file that would be run had these commands actually been invoked.+ *+ * @private+ * @param {string[]} binaries - Names of binary files to search for.+ * @return {string} absolute path of first binary found, or empty string if none+ */+function which(binaries) {+ var paths = process.env.PATH.split(path.delimiter);++ for (var n = 0, blen = binaries.length; n < blen; n++) {+ var binary = binaries[n];+ for (var i = 0, plen = paths.length; i < plen; i++) {+ var loc = path.join(paths[i], binary);+ if (fs.existsSync(loc)) {+ return loc;+ }+ }+ }+ return '';+}++/**+ * @summary+ * Gets platform-specific Growl support binaries.+ *+ * @description+ * Somewhat brittle dependency on `growl` package implementation, but it+ * rarely changes.+ *+ * @private+ * @see {@link https://github.com/tj/node-growl/blob/master/lib/growl.js#L28-L126|setupCmd}+ * @return {string[]} names of Growl support binaries+ */+function getSupportBinaries() {+ var binaries = {+ Darwin: ['terminal-notifier', 'growlnotify'],+ Linux: ['notify-send', 'growl'],+ Windows_NT: ['growlnotify.exe']+ };+ return binaries[os.type()] || [];+}diff --git a/lib/mocha.js b/lib/mocha.jsindex cce2bb9b..d2ded3bf 100644--- a/lib/mocha.js+++ b/lib/mocha.js@@ -9,6 +9,7 @@var escapeRe = require('escape-string-regexp');var path = require('path');var builtinReporters = require('./reporters');+var growl = require('./growl');var utils = require('./utils');var mocharc = require('./mocharc.json');var assign = require('object.assign').getPolyfill();@@ -51,17 +52,6 @@ exports.Suite = require('./suite');exports.Hook = require('./hook');exports.Test = require('./test');-/**- * Returns Growl image `name` path.- *- * @private- * @param {string} name - Basename of associated Growl image.- * @return {string} Pathname to Growl image- */-function image(name) {- return path.join(__dirname, '..', 'assets', 'growl', name + '.png');-}-/*** Constructs a new Mocha instance with `options`.*@@ -324,32 +314,6 @@ Mocha.prototype.loadFiles = function(fn) {fn && fn();};-/**- * Implements desktop notifications using a pseudo-reporter.- *- * @private- * @see {@link Mocha#growl}- * @param {Object} runner - Runner instance.- * @param {Object} reporter - Reporter instance.- */-Mocha.prototype._growl = function(runner, reporter) {- var notify = require('growl');-- runner.on('end', function() {- var stats = reporter.stats;- if (stats.failures) {- var msg = stats.failures + ' of ' + runner.total + ' tests failed';- notify(msg, {name: 'mocha', title: 'Failed', image: image('error')});- } else {- notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {- name: 'mocha',- title: 'Passed',- image: image('ok')- });- }- });-};-/*** Sets `grep` filter after escaping RegExp special characters.*@@ -477,18 +441,49 @@ Mocha.prototype.fullTrace = function() {};/**- * Enables desktop notification support.+ * Enables desktop notification support if prerequisite software installed.** @public+ * @see {@link Mocha#isGrowlCapable}* @see {@link Mocha#_growl}* @return {Mocha} this* @chainable*/Mocha.prototype.growl = function() {- this.options.growl = true;+ this.options.growl = this.isGrowlCapable();+ if (!this.options.growl) {+ var detail = process.browser+ ? 'notification support not available in this browser...'+ : 'notification support prerequisites not installed...';+ console.error(detail + ' cannot enable!');+ }return this;};+/**+ * @summary+ * Determines if Growl support seems likely.+ *+ * @description+ * <strong>Not available when run in browser.</strong>+ *+ * @private+ * @see {@link Growl#isCapable}+ * @see {@link Mocha#growl}+ * @return {boolean} whether Growl support can be expected+ */+Mocha.prototype.isGrowlCapable = growl.isCapable;++/**+ * Implements desktop notifications using a pseudo-reporter.+ *+ * @private+ * @see {@link Mocha#growl}+ * @see {@link Growl#notify}+ * @param {Runner} runner - Runner instance.+ */+Mocha.prototype._growl = growl.notify;+/*** Specifies whitelist of variable names to be expected in global scope.*@@ -772,7 +767,7 @@ Mocha.prototype.run = function(fn) {runner.globals(options.globals);}if (options.growl) {- this._growl(runner, reporter);+ this._growl(runner);}if (options.useColors !== undefined) {exports.reporters.Base.useColors = options.useColors;diff --git a/package-scripts.js b/package-scripts.jsindex 71e2790a..c4081449 100644--- a/package-scripts.js+++ b/package-scripts.js@@ -23,7 +23,7 @@ function test(testName, mochaParams) {module.exports = {scripts: {build: {- script: `browserify ./browser-entry --plugin ./scripts/dedefine --ignore 'fs' --ignore 'glob' --ignore 'path' --ignore 'supports-color' > mocha.js`,+ script: `browserify -e browser-entry.js --plugin ./scripts/dedefine --ignore 'fs' --ignore 'glob' --ignore 'path' --ignore 'supports-color' -o mocha.js`,description: 'Build browser bundle'},lint: {diff --git a/package.json b/package.jsonindex 8756820e..049b754d 100644--- a/package.json+++ b/package.json@@ -451,6 +451,7 @@},"homepage": "https://mochajs.org/","logo": "https://cldup.com/S9uQ-cOLYz.svg",+ "notifyLogo": "https://ibin.co/4QuRuGjXvl36.png","bin": {"mocha": "./bin/mocha","_mocha": "./bin/_mocha"@@ -497,6 +498,7 @@"@mocha/docdash": "^1.0.1","assetgraph-builder": "^6.4.2","browserify": "^16.2.3",+ "browserify-package-json": "^1.0.1","chai": "^4.2.0","coffee-script": "^1.10.0","coveralls": "^3.0.2",@@ -525,7 +527,6 @@"markdownlint-cli": "^0.13.0","nps": "^5.9.3","nyc": "^13.1.0",- "package-json-versionify": "^1.0.4","prettier": "^1.15.3","rewiremock": "^3.12.3","rimraf": "^2.5.2",@@ -548,13 +549,13 @@],"browserify": {"transform": [- "package-json-versionify"+ "./scripts/package-json-cullify"]},"browser": {- "growl": "./lib/browser/growl.js",- "tty": "./lib/browser/tty.js","./index.js": "./browser-entry.js",+ "./lib/growl.js": "./lib/browser/growl.js",+ "tty": "./lib/browser/tty.js","fs": false,"glob": false,"path": false,diff --git a/scripts/package-json-cullify.js b/scripts/package-json-cullify.jsnew file mode 100644index 00000000..794b5efa--- /dev/null+++ b/scripts/package-json-cullify.js@@ -0,0 +1,17 @@+'use strict';++/**+ * This is a transform stream used to cull "package.json" results+ * when our source is transformed for our Browserify bundle.+ *+ * Based on Nolan Lawson's "package-json-versionify" package.+ */++const browserifyPackageJSON = require('browserify-package-json');++module.exports = function(filename, options) {+ const fieldsToKeep = ['name', 'version', 'homepage', 'notifyLogo'];+ const bpjOptions = Object.assign(options || {}, {only: fieldsToKeep});++ return browserifyPackageJSON(filename, bpjOptions);+};diff --git a/test/unit/mocha.spec.js b/test/unit/mocha.spec.jsindex 2511b120..82ba0e14 100644--- a/test/unit/mocha.spec.js+++ b/test/unit/mocha.spec.js@@ -129,12 +129,26 @@ describe('Mocha', function() {});describe('.growl()', function() {- it('should set the growl option to true', function() {- var mocha = new Mocha(opts);- mocha.growl();- expect(mocha.options, 'to have property', 'growl', true);+ describe('if capable of notifications', function() {+ it('should set the growl option to true', function() {+ var mocha = new Mocha(opts);+ mocha.isGrowlCapable = function forceEnable() {+ return true;+ };+ mocha.growl();+ expect(mocha.options, 'to have property', 'growl', true);+ });+ });+ describe('if not capable of notifications', function() {+ it('should set the growl option to false', function() {+ var mocha = new Mocha(opts);+ mocha.isGrowlCapable = function forceDisable() {+ return false;+ };+ mocha.growl();+ expect(mocha.options, 'to have property', 'growl', false);+ });});-it('should be chainable', function() {var mocha = new Mocha(opts);expect(mocha.growl(), 'to be', mocha);