2014-06-20 155 views
16

我是新來的茉莉花和一般測試。我的代碼塊將檢查我的庫是否已使用新運算符實例化:使用茉莉花測試instanceof

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

我該如何使用Jasmine測試?

+0

[如何使用Jasmine來測試實例是否被創建?](http://stackoverflow.com/questions/23062034/how-to-use-jasmine-to-test-if-an-instance -被建造) – Chic

回答

2

Jasmine使用匹配器來做它的斷言,所以你可以編寫自己的自定義匹配器來檢查你想要的任何東西,包括一個實例檢查。 https://github.com/pivotal/jasmine/wiki/Matchers

特別是,請查看Writing New Matchers部分。

31

要檢查,如果事情是instanceof [Object]茉莉花現在提供jasmine.any

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

我不喜歡用instanceof運營商更可讀/直觀的(在我看來)使用。

class Parent {} 
class Child extends Parent {} 

let c = new Child(); 

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

爲了完整起見,你也可以使用原型constructor財產在某些情況下。

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

// ... 

當心,如果你需要檢查對象是否從另一個或不繼承,這將無法正常工作。

class Parent {} 
class Child extends Parent {} 

let c = new Child(); 

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

如果你需要繼承支持絕對使用instanceof運營商或jasmine.any()功能類似羅傑建議。

Object.prototype.constructor參考。