Skip to content

Instantly share code, notes, and snippets.

@heat
Created September 4, 2012 19:45
Show Gist options
  • Select an option

  • Save heat/3625555 to your computer and use it in GitHub Desktop.

Select an option

Save heat/3625555 to your computer and use it in GitHub Desktop.
Jasmine Matcher instanceof
beforeEach(function() {
this.addMatchers({
toBeInstanceOf: function(expectedInstance) {
var actual = this.actual;
var notText = this.isNot ? " not" : "";
this.message = function() {
return "Expected " + actual.constructor.name + notText + " is instance of " + expectedInstance.name;
};
return actual instanceof expectedInstance;
}
});
});
@FilipZawada

Copy link
Copy Markdown

Worth adding, that in Jasmine 2.0 you can use jasmine.any() matcher. E.g:

expect(12).toEqual(jasmine.any(Number));

as mentioned in this blogpost

@kalbasit

Copy link
Copy Markdown

Thank you @FilipZawada

@asyncanup

Copy link
Copy Markdown

Thank you! And note that jasmine.Any is different from jasmine.any

@grebett

grebett commented Oct 31, 2015

Copy link
Copy Markdown

or simply:

expect(myVariable instanceof Array).toBeTruthy();

@ezk84

ezk84 commented Nov 28, 2015

Copy link
Copy Markdown

@grebett: Problem with that approach is the error message which is completely unhelpful. With jasmine.any you'll get a dump of what was actually passed in to the matcher:

Expected '12' to equal <jasmine.any(Number)>.

Instead of the much less helpful:

Expected false to be true.

@luchillo17

Copy link
Copy Markdown

I tough you could set up the output to the expectation as the second arg to .toEqual(), .toBeTruthy() and most expectation comparison does accept some kind of configuration argument.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment