How do I implement assertions in JavaScript?

旧时模样 提交于 2019-12-11 08:59:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!