【问题标题】:Jest - Testing function that throws an error not working开玩笑 - 抛出错误的测试功能不起作用
【发布时间】:2020-11-14 05:34:16
【问题描述】:

我有一个简单的函数,如果输入低于 0 就会抛出错误:

export const hoursMinutesSecondsFromSeconds = (inputSeconds) => {
  if (inputSeconds < 0) {
    throw new Error('illegal inputSeconds < 0');
  }
  let rem = Math.abs(inputSeconds);
  let divisor = 3600;
  const result = [];
  while (divisor >= 1) {
    result.push(Math.floor(rem / divisor));
    rem = rem % divisor;
    divisor = divisor / 60;
  }
  return result;
};

我正在尝试使用低于 0 的输入来测试此函数,如下所示:

import { hoursMinutesSecondsFromSeconds } from './timetools';

describe('hoursMinutesSecondsFromSeconds', () => {
  it('throws error', () => {
    expect(hoursMinutesSecondsFromSeconds(-2)).toThrowError('illegal inputSeconds < 0');
  });
});

但是,当我运行这个测试时,测试失败并且我收到一条错误消息:

Error: illegal inputSeconds < 0

当它抛出一个完全像我期望它在我的测试中抛出的错误时,为什么它没有通过测试?

【问题讨论】:

    标签: javascript jestjs


    【解决方案1】:

    如果不使用 try..catch 进行包装,JavaScript 就无法处理像 expect(hoursMinutesSecondsFromSeconds(-2)) 这样抛出的错误。

    toThrowError 应该与调用时用try..catch 内部包装的函数一起使用。应该是:

    expect(() => hoursMinutesSecondsFromSeconds(-2)).toThrowError('illegal inputSeconds < 0');
    

    【讨论】:

      【解决方案2】:

      查看:https://jestjs.io/docs/en/expect#tothrowerror 我希望您需要将函数调用包装在一个函数中。

      喜欢:

      expect(() => {
          hoursMinutesSecondsFromSeconds(-2);
      }).toThrowError('illegal inputSeconds < 0');
      

      【讨论】:

        猜你喜欢
        • 2021-07-13
        • 2018-09-25
        • 2018-09-27
        • 2020-12-15
        • 1970-01-01
        • 2020-07-04
        • 1970-01-01
        • 2021-06-11
        • 1970-01-01
        相关资源
        最近更新 更多