柴的断言,期待和应该有什么区别? [英] What is the difference between assert, expect and should in Chai?

查看:124
本文介绍了柴的断言,期待和应该有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

断言期望,以及何时使用什么?

What is the difference between assert, expect and should, and 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:


  1. 断言和期望接口不会修改 Object.prototype ,而应该这样做。因此,在您不能或不想更改 Object.prototype 的环境中,它们是更好的选择。

  1. 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 change Object.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应为true将与失败的断言一起输出。您没有机会使用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 的自定义消息,你必须使用一种解决方法。AurélienRibon告诉我,将消息传递给 expect 作为第二个参数有效。因此,没有需要一个解决方法。我无法找到哪个版本的Mocha开始提供对此消息的支持,也无法找到第一次记录哪个版本的文档。)

(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

所以虽然期望和应该接口更好,当断言失败时,它不像一个接口比另一个接口更自然。此消息对于所有三个接口都是相同的,并不告诉您您正在测试的,只是您获得的值是 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.

这篇关于柴的断言,期待和应该有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆