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.js comparing arrays
In Jasmine.js, arrays can be compared in two different ways depending on your testing needs:
Reference equality - checking if two variables refer to the same array object in memory
Content equality - checking if arrays contain the same elements, even if they are different objects
Using toBe() for Reference Equality
The toBe() matcher checks whether two arrays are the exact same object in memory. This is useful when you want to verify that two variables reference the same array instance.
describe("Array Reference Equality", () => {
it("should check for array reference equality", () => {
let arr = [1, 2, 3];
let arr2 = arr; // arr2 points to the same array object
// Passes - both variables reference the same object
expect(arr).toBe(arr2);
// Fails - different objects even with same content
expect(arr).toBe([1, 2, 3]);
});
});
Output
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() for Content Equality
The toEqual() matcher performs deep comparison of array contents. It checks if arrays have the same elements in the same order, regardless of whether they are the same object in memory.
describe("Array Content Equality", () => {
it("should check for array content equality", () => {
let arr = [1, 2, 3];
let arr2 = arr; // Same reference
let arr3 = [1, 2, 3]; // Different object, same content
// Passes - same reference
expect(arr).toEqual(arr2);
// Passes - same content even though different objects
expect(arr).toEqual(arr3);
expect(arr).toEqual([1, 2, 3]);
});
});
Output
Array Content Equality should check for array content equality 1 spec, 0 failures
Comparison
| Matcher | Comparison Type | Use Case |
|---|---|---|
toBe() |
Reference equality | Verify same object instance |
toEqual() |
Deep content equality | Verify same array contents |
Nested Arrays Example
toEqual() also works with nested arrays and complex data structures:
describe("Nested Array Equality", () => {
it("should handle nested arrays", () => {
let nestedArray = [[1, 2], [3, 4]];
// Passes - deep comparison of nested structure
expect(nestedArray).toEqual([[1, 2], [3, 4]]);
// Fails - would need same reference
expect(nestedArray).not.toBe([[1, 2], [3, 4]]);
});
});
Conclusion
Use toBe() when testing if variables reference the same array object, and toEqual() when comparing array contents. For most array testing scenarios, toEqual() is the preferred choice as it focuses on data rather than object identity.
