Read more

Jasmine: Testing complex types for equality

Henning Koch
July 29, 2015Software engineer at makandra GmbH

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

expect(first).toBe(second)
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2015-07-29 22:21)