How do I implement assertions in JavaScript?

2019-08-04 23:02发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-08-04 23:55

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");
}
查看更多
登录 后发表回答