65

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?

Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111
  • possible duplicate of [How to use Jasmine to test if an instance is created?](http://stackoverflow.com/questions/23062034/how-to-use-jasmine-to-test-if-an-instance-is-created) – Chic Apr 13 '15 at 13:06

3 Answers3

129

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));
});
sluijs
  • 4,146
  • 4
  • 30
  • 36
35

I do prefer the more readable/intuitive (in my opinion) use with the instanceof operator.

class Parent {}
class Child extends Parent {}

let c = new Child();

expect(c instanceof Child).toBeTruthy();
expect(c instanceof Parent).toBeTruthy();

For the sake of completeness you can also use the prototype constructor property in some cases.

expect(my_var_1.constructor).toBe(Array);
expect(my_var_2.constructor).toBe(Object);
expect(my_var_3.constructor).toBe(Error);

// ...

BEWARE that this won't work if you need to check whether an object inherited from another or not.

class Parent {}
class Child extends Parent {}

let c = new Child();

console.log(c.constructor === Child); // prints "true"
console.log(c.constructor === Parent); // prints "false"

If you need inheritance support definitely use the instanceof operator or the jasmine.any() function like Roger suggested.

Object.prototype.constructor reference.

Francesco Casula
  • 26,184
  • 15
  • 132
  • 131
  • What if you want explicitly check if c is of type Child? That is, it should fail if it's of its parent type. Is there a way to test this other than doing something like constructor.name? – Ε Г И І И О Oct 18 '20 at 16:33
  • I think I reported examples already in my answer for that, both with the `instanceof` operator and with `c.constructor === Child`. – Francesco Casula Oct 19 '20 at 12:45
3

Jasmine uses matchers to do its assertions, so you can write your own custom matcher to check anything you want, including an instanceof check. https://github.com/pivotal/jasmine/wiki/Matchers

In particular, check out the Writing New Matchers section.

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406