Jasmine JavaScript Testing - toBe vs toEqual
The toBe
matcher checks whether two items refer to the identical object (same reference), just like JavaScript's ===
. The toEqual
matcher instead checks whether two objects have the same value, making it ideal for inspecting object contents.
Quick Examples:
Exploring the fine-print of toBe
and toEqual
is vital for effective JavaScript testing.
Under the hood – toBe
vs toEqual
toBe
, toted as the «matcher of strict sameness», uses the rigid ===
comparison, making it the chief choice for primitives when an exact match is expected. Beware, though, for even two independent objects with identical contents will stumble over toBe
:
On the opposite end, toEqual
runs a deep comparison, checking each property and its children for equality:
toEqual
also plays nice with special JavaScript objects such as Date
, RegExp
, and wrapped types like Number
, focusing on the value, not the wrapper.
Special scenarios
Counting the beans, Numerical comparisons
When dealing with numeric comparisons, selecting the right matcher can avert subtle errors. Let's say you're a banker:
The «Doppelgänger Disorder», Comparing object references
Imagine you have a getSingleton
function which should always return the same signleton object:
The Mirror Maze, arrays and complex objects
When you're traversing arrays or juggling complex objects, toEqual
is your staunchest ally:
Time Trekkers and String Wranglers, special JavaScript objects
With value comparisons, toEqual
handles special JavaScript objects adeptly:
Pitfalls to avoid
Beware the Tiny Gap, floating point numbers
When dealing with floating point numbers, be wary of the classic trap of precision:
The Shapeshifter, object mutability
In mutable objects, toBe
can spring surprises:
Suit Up, value types with constructors
Don't forget, toBe
is not suitable for value types constructed using the new
keyword:
Deep dive into Jasmine's secret archives
To truly conquer the innards of Jasmine's matchers, venture into the source code. Decode the enigma of the toBe
matcher's strict comparison (===
) and toEqual
matcher's elaborate deep equality check. The source is available on GitHub, for those brave enough.
Key learnings for further honing
Peruse through the Jasmine docs, pore over online tutorials, or indulge in community discussions at the Jasmine GitHub Wiki for enlightening insights and nifty tricks.
Was this article helpful?