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 professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
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)