使用Jasmine测试instanceof

时间:2014-06-20 17:46:15

标签: javascript unit-testing testing jasmine

我是Jasmine的新手,并且总的来说是测试。我的一段代码检查我的库是否已使用new运算符进行实例化:

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

如何使用Jasmine进行测试?

3 个答案:

答案 0 :(得分:72)

要检查某些内容是instanceof [Object] Jasmine现在提供jasmine.any

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

答案 1 :(得分:25)

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.

答案 2 :(得分:3)

Jasmine使用匹配器来执行其断言,因此您可以编写自己的自定义匹配器来检查您想要的任何内容,包括检查实例。 https://github.com/pivotal/jasmine/wiki/Matchers

请特别查看“写新匹配”部分。