使用Jasmine测试instanceof

Mik*_*gin 43 javascript testing unit-testing jasmine

我是Jasmine的新手并且总体上都在进行测试.我的一段代码检查我的库是否已使用new运算符进行实例化:

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

我如何使用Jasmine进行测试?

slu*_*ijs 87

要检查是否有toBeInstanceOf茉莉花现在提供instanceof [Object]:

it("matches any value", () => {
  expect(3).toBeInstanceOf(Number);
});
Run Code Online (Sandbox Code Playgroud)


Fra*_*ula 31

我更喜欢使用instanceof运算符更具可读性/直观性(在我看来).

class Parent {}
class Child extends Parent {}

let c = new Child();

expect(c instanceof Child).toBeTruthy();
expect(c instanceof Parent).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)

为了完整起见,您还可以constructor在某些情况下使用prototype 属性.

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

// ...
Run Code Online (Sandbox Code Playgroud)

注意,如果您需要检查对象是否继承自另一个对象,则此方法无效.

class Parent {}
class Child extends Parent {}

let c = new Child();

console.log(c.constructor === Child); // prints "true"
console.log(c.constructor === Parent); // prints "false"
Run Code Online (Sandbox Code Playgroud)

如果你需要继承支持,请使用instanceof运算符或者像Roger建议的jasmine.any()函数.

Object.prototype.constructor引用.


Jef*_*rey 3

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

特别是,请查看“编写新匹配器”部分。