Javascript 使用茉莉花的实例测试
我对茉莉花和测试都是新手。我的一个代码块检查我的库是否已使用新运算符实例化:Javascript 使用茉莉花的实例测试,javascript,unit-testing,testing,jasmine,Javascript,Unit Testing,Testing,Jasmine,我对茉莉花和测试都是新手。我的一个代码块检查我的库是否已使用新运算符实例化: //if 'this' isn't an instance of mylib... if (!(this instanceof mylib)) { //return a new instance return new mylib(); } 如何使用Jasmine来测试它?Jasmine使用matcher来进行断言,因此您可以编写自己的自定义matcher来检查您想要的任何内容,包括检查
//if 'this' isn't an instance of mylib...
if (!(this instanceof mylib)) {
//return a new instance
return new mylib();
}
如何使用Jasmine来测试它?Jasmine使用matcher来进行断言,因此您可以编写自己的自定义matcher来检查您想要的任何内容,包括检查实例 特别是,请查看“编写新匹配器”部分。Jasmine>=3.5.0 茉莉花提供火柴 茉莉花>2.3.0 要检查某物是否是[Object]的实例,Jasmine提供了:
在我看来,我更喜欢与操作员一起使用更具可读性/直观性的方法
class Parent {}
class Child extends Parent {}
let c = new Child();
expect(c instanceof Child).toBeTruthy();
expect(c instanceof Parent).toBeTruthy();
为了完整起见,在某些情况下,您还可以使用prototype构造函数
属性
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
运算符或建议使用的Roger函数
参考。如果要显式检查c是否为Child类型,则可能重复What if?也就是说,如果它是其父类型,它应该失败。除了像constructor.name这样的操作之外,还有什么方法可以测试这一点吗?我想我在回答中已经给出了一些例子,包括
instanceof
操作符和c.constructor===Child
。属性“toBeInstanceOf”在类型“ArrayLikeMatchers”上不存在
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"