Jasmine JavaScript测试 - toBe vs toEqual [英] Jasmine JavaScript Testing - toBe vs toEqual

查看:536
本文介绍了Jasmine JavaScript测试 - toBe vs toEqual的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下内容:

var myNumber = 5;
expect(myNumber).toBe(5);
expect(myNumber).toEqual(5);

上述两项测试都将通过。在评估数字时, toBe() toEqual()之间是否存在差异?如果是这样,当我应该使用一个而不是另一个?

Both of the above tests will pass. Is there a difference between toBe() and toEqual() when it comes to evaluating numbers? If so, when I should use one and not the other?

推荐答案

对于原始类型(例如数字,布尔值,字符串等) 。), toBe toEqual 之间没有区别;任何一个将适用于 5 true ,或蛋糕是谎言

For primitive types (e.g. numbers, booleans, strings, etc.), there is no difference between toBe and toEqual; either one will work for 5, true, or "the cake is a lie".

了解 toBe toEqual <之间的区别/ code>,让我们想象三个对象。

To understand the difference between toBe and toEqual, let's imagine three objects.

var a = { bar: 'baz' },
    b = { foo: a },
    c = { foo: a };

使用严格比较( === ),有些东西是相同的:

Using a strict comparison (===), some things are "the same":

> b.foo.bar === c.foo.bar
true

> b.foo.bar === a.bar
true

> c.foo === b.foo
true

但有些事情,即使他们是相等,不是相同,因为它们代表住在记忆中不同位置的对象。

But some things, even though they are "equal", are not "the same", since they represent objects that live in different locations in memory.

> b === c
false

Jasmine的 toBe matcher只不过是一个严格的相等比较的包装器

Jasmine's toBe matcher is nothing more than a wrapper for a strict equality comparison

expect(a.foo).toBe(b.foo)

expect(a.foo === b.foo).toBe(true)

不要只听我的话;请参阅 toBe的源代码

Don't just take my word for it; see the source code for toBe.

b c 表示功能相当的对象;它们看起来像

But b and c represent functionally equivalent objects; they both look like

{ foo: { bar: 'baz' } }

如果我们可以说 b ,那会不会很好c 即使它们不代表同一个对象也是相等的?

Wouldn't it be great if we could say that b and c are "equal" even if they don't represent the same object?

输入 toEqual ,它检查深度相等(即通过对象进行递归搜索以确定其键的值是否相等)。以下两项测试都将通过:

Enter toEqual, which checks "deep equality" (i.e. does a recursive search through the objects to determine whether the values for their keys are equivalent). Both of the following tests will pass:

expect(b).not.toBe(c);
expect(b).toEqual(c);

希望这有助于澄清一些事情。

Hope that helps clarify some things.

这篇关于Jasmine JavaScript测试 - toBe vs toEqual的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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