Jasmine: Testing complex types for equality
Jasmine comes with two matchers that test for equality. The first is toBe
:
Copyexpect(first).toBe(second)
toBe
passes when first === second
. Unfortunately this is useless for non-primitive values because Javascript is a horrible language.
However, Jasmine comes with another matcher toEqual
:
Copyexpect(first).toEqual(second)
This matcher behaves as a human would expect for types like the following:
- Arrays
- Objects
- Nested array/object constructs
- Regular expressions
-
Date
objects NaN
- Exceptions
Custom equality matchers
You can also teach toEqual
additional notions of equality. E.g. the following code will teach toEqual
to test two jQuery collections for equality:
CopybeforeEach -> jasmine.addCustomEqualityTester (first, second) -> if first instanceof jQuery && second instanceof jQuery first.is(second)
Using Jasmine's equality logic in your own matchers
You can use Jasmine's built-in equality logic (plus the logic added by custom equality matchers) like this:
CopybeforeEach -> jasmine.addMatchers toEqual123Array: (util, customEqualityTesters) -> compare: (actual) pass: util.equals(actual, [1, 2, 3], customEqualityTesters)
Note how the compare
method is passed two arguments util
and customEqualityTesters
, which are both needed to access Jasmine's equality logic.
By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.