问题
I'd like to use assertions to check for invalid parameters in my private methods (and others that should only be called internally). I'd prefer:
- A failed assertion terminates the program, or at least stops my automated tests.
console.assert()
doesn't appear to do this. - Assertions can be stripped out during production deployment (I'm using Grunt).
- A very minimal solution (shouldn't need a library to do this).
EDIT: I'm not trying to test anything here. If my motivation for doing this is unclear, check out CC2 or Clean Code or the Wiki page: https://en.wikipedia.org/wiki/Assertion_(software_development)
回答1:
Something like?
const assert = env === "production"
? () => {}
: (test, msg) => {
if (!test) throw new Error(`assertion failed: ${msg}`);
};
// ...
function foo(param) {
assert(typeof param === "number", "param is a Number");
}
来源:https://stackoverflow.com/questions/32409339/how-do-i-implement-assertions-in-javascript