Skip to content

armgit / mocha

Public Imported from GitHub
0

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

Add `utils.escape` tests and fix unicode escaping

Jan Krems9f403bf33119
diff --git a/lib/utils.js b/lib/utils.js
index d66eba3b..43e28bc4 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -18,6 +18,7 @@ var statSync = require('fs').statSync;
var watchFile = require('fs').watchFile;
var lstatSync = require('fs').lstatSync;
var toISOString = require('./to-iso-string');
+var he = require('he');
/**
* Ignored directories.
@@ -35,11 +36,7 @@ exports.inherits = require('util').inherits;
* @return {string}
*/
exports.escape = function (html) {
- return String(html)
- .replace(/&/g, '&')
- .replace(/"/g, '"')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;');
+ return he.encode(String(html), { useNamedReferences: true });
};
/**
diff --git a/package.json b/package.json
index e199cee1..6c7687da 100644
--- a/package.json
+++ b/package.json
@@ -314,6 +314,7 @@
"escape-string-regexp": "1.0.5",
"glob": "7.1.1",
"growl": "1.9.2",
+ "he": "1.1.1",
"json3": "3.3.2",
"lodash.create": "3.1.1",
"mkdirp": "0.5.1",
diff --git a/test/unit/utils.spec.js b/test/unit/utils.spec.js
index ad64fd84..078d05e5 100644
--- a/test/unit/utils.spec.js
+++ b/test/unit/utils.spec.js
@@ -624,4 +624,22 @@ describe('lib/utils', function () {
expect(utils.isPromise({})).to.be(false);
});
});
+
+ describe('escape', function () {
+ it('replaces the usual xml suspects', function () {
+ expect(utils.escape('<a<bc<d<')).to.be('&lt;a&lt;bc&lt;d&lt;');
+ expect(utils.escape('>a>bc>d>')).to.be('&gt;a&gt;bc&gt;d&gt;');
+ expect(utils.escape('"a"bc"d"')).to.be('&quot;a&quot;bc&quot;d&quot;');
+ expect(utils.escape('<>"&')).to.be('&lt;&gt;&quot;&amp;');
+
+ expect(utils.escape('&a&bc&d&')).to.be('&amp;a&amp;bc&amp;d&amp;');
+ expect(utils.escape('&amp;&lt;')).to.be('&amp;amp;&amp;lt;');
+ });
+
+ it('replaces invalid xml characters', function () {
+ expect(utils.escape('\x1B[32mfoo\x1B[0m')).to.be('&#x1B;[32mfoo&#x1B;[0m');
+ // Ensure we can handle non-trivial unicode characters as well
+ expect(utils.escape('💩')).to.be('&#x1F4A9;');
+ });
+ });
});