为什么Node.js Assert没有notOk()方法?
我正在学习使用mocha
和assert
模块在Node.js中进行testing。 assert
有这些types的方法:
assert.equal(); assert.deepEqual(); assert.deepStrict(); assert.strict(); assert.ok(); // Is the value true?
然后有一些对立面:
assert.notEqual(); assert.notDeepEqual(); assert.notDeepStrict(); assert.notStrict();
但有一个缺less…为什么没有一个notOk()
方法来testing结果值是否为false
?
这让我想到,也许有一些基本的东西我缺less一般的unit testing,也许我只应该testing,如果价值观是真实的,从来没有错误…
就目前而言,我只是在做这个来testingfalsey
陈述:
assert.ok(!myValue);
那是你应该怎么做的? 再说一遍,为什么不存在一个notOk()
方法,因为所有其他的方法都有一个not
版本?
如果你看看文档,它会注意到.ok(value, message)
等价于assert.equal(!!value, true, message)
。 这似乎只是一个方便的function。
应该注意的是,虽然函数被称为ok()
,但这并不意味着它期望从您的代码true
价值。 它期待着你想要testing真实性的声明。 所以,当您的!myValue
的使用是有效的,我认为这将是更合适的写:
assert.ok(myValue === false);
上面的语义是有道理的,因为你仍然在testing你的expression的真实性,所以恰好你期望它是错误的。 包含notOk()
函数意味着一些含糊不清的含义。 不好意味着失败,所以一个notOk
函数的失败可能似乎有点复杂。
至于其他的方法,我认为这个语言还是有意义的。 notEqual
意味着你正在专门testing一个不平等,而不是没有意义。 就我个人而言,我只是把ok()
全部放在一起,就好了,反正它本身也很模糊。
如果你真的觉得有需要,你也可以简单的编写自己的便利function。
我觉得还值得一提的是这个来源:
// 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok;