【问题标题】:Testing Function to Throw an Error in Jest测试函数以在 Jest 中抛出错误
【发布时间】:2020-10-22 02:10:12
【问题描述】:

我有这样一个功能要测试:

export const checkTextEmpty = stringArg => {
  if (typeof stringArg !== 'string') {
    throw new Error('Provide a string argument to checkTextEmpty function')
  }

  return stringArg.length === 0 || stringArg.trim() === ''
}

我想测试它是否正确抛出错误:

it(
   'should throw an error if passed argument is not a string',
      () => {
        const notStrings = [null, 4, [], {}, undefined, -5]

        notStrings.forEach(elem => {
          expect(checkTextEmpty(elem)).toThrow(Error)
        })
      }
    )

这是我终端中的结果:

utils.js › checkTextEmpty util › should throw an error if passed argument is not a string

    Provide a string argument to checkTextEmpty function

      117 | export const checkTextEmpty = stringArg => {
      118 |   if (typeof stringArg !== 'string') {
    > 119 |     throw new Error('Provide a string argument to checkTextEmpty function')
          |           ^
      120 |   }
      121 |
      122 |   return stringArg.length === 0 || stringArg.trim() === ''

      at checkTextEmpty (src/scripts/utils/utils.js:119:11)
      at forEach (src/scripts/utils/utils.test.js:11:18)
          at Array.forEach (<anonymous>)
      at Object.it (src/scripts/utils/utils.test.js:10:20)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 2 passed, 3 total
Snapshots:   0 total
Time:        3.918 s

如何修复我的测试以使其正常工作?

【问题讨论】:

  • 尝试用闭包包裹checkTextEmpty调用:expect(() =&gt; { checkTextEmpty(elem) })...
  • @hindmost 它有效!您能否将其添加为答案?我会接受的!

标签: javascript unit-testing testing jestjs


【解决方案1】:

toThrow 期望将 函数 传递给 expect,而不是其调用的结果。

所以你必须用匿名函数来包装你的函数调用:

expect(() => {
  checkTextEmpty(elem)
}).toThrow(Error);

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2018-11-21
    相关资源
    最近更新 更多