【问题标题】:Why jest expects an anonymous function to catch an error?为什么 jest 期望匿名函数捕获错误?
【发布时间】:2020-03-18 08:17:47
【问题描述】:

当我想测试错误消息的输出时,我还没有理解期望 curried 函数的背后原因。如果它是return 值,则直接调用该函数会导致在.toBe 中正确测试该值

function calculateMedian({numbers}) {
if (Array.isArray(numbers) && numbers.length === 0) {
        throw new Error('Cannot calcuate median without any numbers');
    }
}

但是,如果我在没有匿名函数的情况下测试以下片段,则测试将失败。背后的原因是什么?

通过测试

    it('should throw an error when given an empty array', () => {
        expect(() =>
            calculateMedian({
                numbers: [],
            }),
        ).toThrow('Cannot calcuate median without any numbers');
    });

未通过测试

    it('should throw an error when given an empty array', () => {
        expect(calculateMedian({numbers: []})
        ).toThrow('Cannot calcuate median without any numbers');
    });

【问题讨论】:

    标签: testing jestjs tdd


    【解决方案1】:

    expecttoThrow 只是函数调用。因此,为了使异常断言起作用,您作为expect 参数传递的东西需要允许由测试框架控制的执行。

    流程类似于:

    1. expect() 将 lambda 保存为变量
    2. toThrow()try/catch 块中执行保存的变量并测试捕获的异常。

    不使用toThrow 方法的方式类似于:

    try {
      calculateMedian({numbers: []};
      fail();
    } catch (err) {
      expect(err.message).toBe('Cannot calcuate median without any numbers')
    }
    

    如果您不传递 lambda/函数,而只是调用该函数,则会在程序控制到达 toThrow 方法之前引发错误。由于抛出的错误,测试将失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 2012-02-01
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多