Posted over 3 years ago. Visible to the public.

Jasmine: Testing complex types for equality

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


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:


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:

beforeEach -> jasmine.addCustomEqualityTester (first, second) -> if first instanceof jQuery && second instanceof jQuery

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.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Henning Koch
Last edit:
almost 3 years ago
by Henning Koch
jasmine, objects
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more