Easy way to enable / disable assert statements in node.js

I am using the assert module in node.js https://www.npmjs.com/package/assert

In C / C ++, you can easily enable / disable assert statements using macros. Is it possible to do the same for node.js and javascript in general?

+4
source share
2 answers

Note that the package you use adds assertions as a module and therefore polyfills .

You can simply overwrite the -part- object to disable the polyfill.

Example:
Say you want to disable deepEqualassert, which currently looks like this:

assert.deepEqual = function deepEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected)) {
    fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  }
};

, - :

assert.deepEqual = function deepEqual(actual, expected, message) {
  // disable
};

FYI:
: http://wiki.ecmascript.org/doku.php?id=strawman:assert

+2

:

1.

const devMode = false; // or var, if you use older javascript version

devMode && assert(...);

, assert , :

devMode && assert(value++, 'Value should not have been 0');
devMode && assert(myfunc(), 'myfunc unexpectedly returned false');
devMode && assert.throws(function() {
    home = '/home';
    throw new Error("Wrong value");
}, Error);

assert , devMode. value , myfunc , home .

, :

2. mock assert

, assert, , :

:

var assert = function (value, message) {
    return true;
}
assert.ok = assert;
assert.fail = assert;
assert.equal = assert;
assert.notEqual = assert;
assert.deepEqual = assert;
assert.notDeepEqual = assert;
assert.strictEqual = assert;
assert.notStrictEqual = assert;
assert.ifError = assert;
// assert.throws should only be used to confirm that certain code will produce
// an error, but it should not change any state outside the function scope.
// This mock version will NOT execute any of the functions passed to it.
assert.throws = assert;
// For assert.doesNotThrow the same choice is made:
assert.doesNotThrow = assert;

, , , assert.throws assert.doesNotThrow. , -, , , , .

3.

- assert . assert assert , , , (. ), , grep, .

, ( ) assert. :

 assert(value++, 'Value should not have been 0')

:

 value++

, .

+2

Source: https://habr.com/ru/post/1617821/


All Articles