我如何在JavaScript中实现断言? [英] How do I implement assertions in JavaScript?
本文介绍了我如何在JavaScript中实现断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用断言来检查我的私有方法中的无效参数(以及其他只应在内部调用的参数)。我更喜欢:
- 失败的断言终止程序,或者至少停止我的自动化测试。
console.assert()
似乎没有这样做。 - 生产部署过程中可以剥离断言Grunt)。
- 一个非常小的解决方案(不需要库来做到这一点)。
编辑:
我不想在这里测试任何东西。如果我的动机不明确,请查看CC2或Clean Code或Wiki页面: https: //en.wikipedia.org/wiki/Assertion_(software_development)
解决方案
类似于?
const assert = env ===production
? ()=> {}
:(test,msg)=> {
if(!test)抛出新的错误(`assertion failed:$ {msg}`);
};
...
函数foo(param){
assert(typeof param ===number,param is a Number);
}
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)
解决方案
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");
}
这篇关于我如何在JavaScript中实现断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文