Testing for instanceof using Jasmine

Mike Rifgin picture Mike Rifgin · Jun 20, 2014 · Viewed 30.6k times · Source

I'm new to Jasmine and testing in general. One block of my code checks whether my library has been instantiated using the new operator:

 //if 'this' isn't an instance of mylib...
 if (!(this instanceof mylib)) {
     //return a new instance
     return new mylib();   
 }

How can I test this using Jasmine?

Answer

sluijs picture sluijs · Oct 10, 2015

Jasmine >=3.5.0

Jasmine provides the toBeInstanceOf matcher.

it("matches any value", () => {
  expect(3).toBeInstanceOf(Number);
});

Jasmine >2.3.0

To check if something is an instanceof [Object] Jasmine provides jasmine.any:

it("matches any value", function() {
  expect({}).toEqual(jasmine.any(Object));
  expect(12).toEqual(jasmine.any(Number));
});