Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for instanceof using Jasmine

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?

like image 265
Mike Rifgin Avatar asked Jun 20 '14 17:06

Mike Rifgin


People also ask

What is Jasmine used for in testing?

Jasmine is a very popular JavaScript behavior-driven development (In BDD, you write tests before writing actual code) framework for unit testing JavaScript applications. It provides utilities that can be used to run automated tests for both synchronous and asynchronous code.

How do I write a test case for setTimeout in Jasmine?

Jasmine supports testing async code. We can test async code with: describe("Using callbacks", function () { beforeEach(function (done) { setTimeout(function () { value = 0; done(); }, 1); }); it("supports sequential execution of async code", function (done) { value++; expect(value). toBeGreaterThan(0); done(); }); });


2 Answers

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)); }); 
like image 171
sluijs Avatar answered Oct 18 '22 05:10

sluijs


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.

like image 27
Francesco Casula Avatar answered Oct 18 '22 05:10

Francesco Casula