在Chai中,“断言",“期望"和“应该"有什么区别? [英] What is the difference between “assert”, “expect”, and “should” in Chai?
问题描述
断言
,期望
和应该
之间有什么区别?什么时候使用什么?
What is the difference between assert
, expect
, and should
? When to use what?
assert.equal(3, '3', '== coerces values to strings');
var foo = 'bar';
expect(foo).to.equal('bar');
foo.should.equal('bar');
推荐答案
差异在此处记录.
这三个接口表示执行断言的不同样式.最终,他们执行相同的任务.一些用户比另一种更喜欢一种样式.话虽如此,还有一些技术方面的注意事项值得强调:
The three interfaces present different styles of performing assertions. Ultimately, they perform the same task. Some users prefer one style over the other. This being said, there are also a couple technical considerations worth highlighting:
-
assert和Expect接口不会修改
Object.prototype
,而应该进行修改.因此,在您无法或不想更改Object.prototype
的环境中,它们是一个更好的选择.
The assert and expect interfaces do not modify
Object.prototype
, whereas should does. So they are a better choice in an environment where you cannot or do not want to changeObject.prototype
.
assert和Expect接口几乎在任何地方都支持自定义消息.例如:
The assert and expect interfaces support custom messages just about everywhere. For instance:
assert.isTrue(foo, "foo should be true");
expect(foo, "foo should be true").to.be.true;
如果断言失败,则将与失败的断言一起输出消息"foo应该为真".您没有机会通过should接口设置自定义消息.
The message "foo should be true" will be output together with the failed assertion if the assertion fails. You don't get the opportunity to set a custom message with the should interface.
(历史记录:很长一段时间以来,这个答案都表明要使用 expect
获得自定义消息,您必须使用一种变通方法.
(Historical note: for a long time this answer stated that to get a custom message with expect
, you'd have to use a workaround. Aurélien Ribon informed me that passing a message to expect
as a second parameter works. Consequently, there is no need for a workaround. I've not been able to find which version of Mocha started providing support for this message, nor have I been able to find which version of the documentation documented it for the first time.)
请注意, assert.isTrue(foo)
, expect(foo).to.be.true
和 foo.should.be.true
>如果不使用自定义消息,则全部输出以下内容,并且 foo === 1
:
Note that assert.isTrue(foo)
, expect(foo).to.be.true
and foo.should.be.true
all output the following if you do not use a custom message, and foo === 1
:
AssertionError: expected 1 to be true
因此,尽管Expect和should接口比 read 更好,但是当断言失败时,这不像一个接口比另一个接口更自然地提供信息.该消息对于所有三个接口都是相同的,它不会告诉您您到底在测试什么,只是告诉您得到的值是 1
,而您想要的是 true
.如果您想知道要测试的内容,则需要添加一条消息.
So while the expect and should interface are nicer to read, it is not like one interface is more naturally informative than the other when an assertion fails. This message, which is identical for all three interfaces, does not tell you what exactly you were testing, only that the value you got was 1
but you wanted true
. If you want to know what you were testing, you need to add a message.
这篇关于在Chai中,“断言",“期望"和“应该"有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!