测试类型的正确方法是什么?

时间:2018-08-04 18:56:00

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

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

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)
})

1 个答案:

答案 0 :(得分:0)

一如既往,循环可能会有所帮助:

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