【问题标题】:Testing for instanceof using Jasmine使用 Jasmine 测试 instanceof
【发布时间】:2014-08-11 13:04:45
【问题描述】:

我是 Jasmine 和一般测试的新手。我的一段代码检查我的库是否已使用 new 运算符实例化:

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

如何使用 Jasmine 进行测试?

【问题讨论】:

标签: javascript unit-testing testing jasmine


【解决方案1】:

茉莉花>=3.5.0

Jasmine 提供了toBeInstanceOf 匹配器。

it("matches any value", () => {
  expect(3).toBeInstanceOf(Number);
});

茉莉花>2.3.0

检查某事物是否为instanceof [Object] Jasmine 提供jasmine.any

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

【讨论】:

  • “ArrayLikeMatchers”类型上不存在属性“toBeInstanceOf”
【解决方案2】:

我更喜欢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 运算符或 Roger 建议的 jasmine.any() 函数。

Object.prototype.constructor 参考。

【讨论】:

  • 如果要明确检查 c 是否为 Child 类型怎么办?也就是说,如果它是其父类型,它应该会失败。除了做诸如constructor.name之类的事情之外,还有其他方法可以测试吗?
  • 我想我已经在我的答案中报告了示例,包括instanceof 运算符和c.constructor === Child
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-14
    • 2013-12-20
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多