Jasmine: Testing complex types for equality

Updated . Posted . Visible to the public.

Jasmine comes with two matchers that test for equality. The first is toBe:

expect(first).toBe(second)

toBe passes when first === second. Unfortunately this is useless for non-primitive values because JavaScript is a horrible language Show archive.org snapshot .

However, Jasmine comes with another matcher toEqual:

expect(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 Show archive.org snapshot . E.g. the following code will teach toEqual to test two jQuery collections for equality:

beforeEach ->
  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:

beforeEach ->
  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.

Henning Koch
Last edit
Felix Eschey
Keywords
jasmine, objects
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2015-07-29 20:21)