Fall back to assignment, update test

This commit is contained in:
Joe Portner
2023-03-12 12:10:19 -04:00
parent 58bc2eb556
commit 181a537556
3 changed files with 38 additions and 8 deletions

View File

@@ -100,13 +100,24 @@ exports.escapeXML = function (markup) {
.replace(_MATCH_HTML, encode_char);
};
// If the Object prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property
// cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict
// mode, attempting that will be silently ignored.
// However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object.
Object.defineProperty(exports.escapeXML, 'toString', function () {
function escapeXMLToString() {
return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
});
}
try {
if (typeof Object.defineProperty === 'function') {
// If the Function prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property
// cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict
// mode, attempting that will be silently ignored.
// However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object.
Object.defineProperty(exports.escapeXML, 'toString', { value: escapeXMLToString });
} else {
// If Object.defineProperty() doesn't exist, attempt to shadow this property using the assignment operator.
exports.escapeXML.toString = escapeXMLToString;
}
} catch (err) {
console.warn('Unable to set escapeXML.toString (is the Function prototype frozen?)');
}
/**
* Naive copy of properties from one object to another.

View File

@@ -37,6 +37,6 @@
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
"test": "mocha -u tdd"
}
}

View File

@@ -83,8 +83,27 @@ suite('unit testing exported functions of module \'utils.js\'', function () {
*/
suite('unit testing function \'escapeXML\' of module \'utils.js\'', function () {
test('it should be callable without parameters', function () {
const stringified =
`function (markup) {
return markup == undefined
? ''
: String(markup)
.replace(_MATCH_HTML, encode_char);
};
var _ENCODE_HTML_RULES = {
"&": "&"
, "<": "&lt;"
, ">": "&gt;"
, '"': "&#34;"
, "'": "&#39;"
}
, _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
return _ENCODE_HTML_RULES[c] || c;
};
`;
assert.doesNotThrow(() => { utils.escapeXML.toString(); });
assert.ok(typeof(utils.escapeXML.toString())==='string');
assert.ok(utils.escapeXML.toString()===stringified);
});
});