Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Jasmine JavaScript Testing - toBe vs toEqual
In Jasmine JavaScript testing, toBe and toEqual are two different matchers for comparing values. Understanding their difference is crucial for writing effective tests.
toBe vs toEqual Overview
Arrays and objects can be compared in two ways:
Reference equality: They refer to the same object in memory
Value equality: They may refer to different objects but their contents are identical
Using toBe (Reference Equality)
The toBe matcher checks if two variables reference the exact same object in memory. It uses JavaScript's === operator internally.
describe("Array Reference Equality", () => {
it("should check for array reference equality", () => {
let arr = [1, 2, 3];
let arr2 = arr; // arr2 points to same object as arr
// Passes - same reference
expect(arr).toBe(arr2);
// Fails - different objects, even with same content
expect(arr).toBe([1, 2, 3]);
});
});
Output for toBe
1) Array Reference Equality should check for array reference equality
Message:
Expected [ 1, 2, 3 ] to be [ 1, 2, 3 ].
Tip: To check for deep equality, use .toEqual() instead of .toBe().
Using toEqual (Value Equality)
The toEqual matcher performs deep comparison, checking if the contents of two objects are equal, regardless of whether they're the same object in memory.
describe("Array Value Equality", () => {
it("should check for array content equality", () => {
let arr = [1, 2, 3];
let arr2 = arr;
// Passes - same reference
expect(arr).toEqual(arr2);
// Passes - same content, different objects
expect(arr).toEqual([1, 2, 3]);
// Works with nested objects too
expect({a: 1, b: [2, 3]}).toEqual({a: 1, b: [2, 3]});
});
});
Output for toEqual
1 spec, 0 failures
Key Differences
| Matcher | Comparison Type | Use Case |
|---|---|---|
toBe |
Reference (===) | Same object in memory |
toEqual |
Deep value comparison | Same content, different objects OK |
Conclusion
Use toBe when you need to verify that two variables reference the exact same object. Use toEqual when you want to compare the actual content or values, which is more common in most testing scenarios.
