【问题标题】:What is the proper way to test types?测试类型的正确方法是什么?
【发布时间】:2019-01-12 07:04:31
【问题描述】:

我正在使用 Jest 进行单元测试,并且我想测试变量是否为对象。有更好的方法吗?

it('should throw an Error if options is not an Object', () => {
  const error = 'Options should be an Object.'

  expect(() => new Foo([])).toThrow(error)
  expect(() => new Foo(123)).toThrow(error)
  expect(() => new Foo('')).toThrow(error)
  expect(() => new Foo(true)).toThrow(error)
  expect(() => new Foo(NaN)).toThrow(error)
  expect(() => new Foo(null)).toThrow(error)
  expect(() => new Foo(() => {})).toThrow(error)
})

【问题讨论】:

  • 您不是在测试变量是否是对象,而是在测试构造函数是否可以接收除对象之外的任何内容。我不知道这样做的任何更短的方法,但我会添加一个测试并希望它不会在对象 is 通过时抛出
  • 你可以用 Jasmine 做到这一点。 expect(foo).to.be.a('object')assert.typeOf(foo, 'object')

标签: javascript unit-testing testing ecmascript-6 jestjs


【解决方案1】:

与往常一样,循环可能会有所帮助:

 for(const type of [[], 123, '', true, NaN, null])
   expect(() => new Foo(type)).toThrow(error);

【讨论】:

    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    相关资源
    最近更新 更多