简体   繁体   English

如何在JavaScript中实现断言?

[英]How do I implement assertions in JavaScript?

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. console.assert()似乎没有这样做。
  • Assertions can be stripped out during production deployment (I'm using Grunt). 可以在生产部署期间删除断言(我正在使用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) 如果我这样做的动机不清楚,请查看CC2或Clean Code或Wiki页面: https : //en.wikipedia.org/wiki/Assertion_(software_development)

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM