代码之家  ›  专栏  ›  技术社区  ›  Leff

Jest-抛出错误的测试函数无法工作

  •  0
  • Leff  · 技术社区  · 4 年前

    我有一个简单的函数,如果输入小于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
    

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

    0 回复  |  直到 4 年前
        1
  •  1
  •   Estus Flask    4 年前

    在JavaScript中,不可能处理像这样抛出的错误 expect(hoursMinutesSecondsFromSeconds(-2)) 不用包装 try..catch .

    toThrowError 应该与一个内部封装有以下代码的函数一起使用 尝试。。抓住 当它被召唤时。它应该是:

    expect(() => hoursMinutesSecondsFromSeconds(-2)).toThrowError('illegal inputSeconds < 0');
    
        2
  •  1
  •   Ben Stephens    4 年前

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

    比如:

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