【问题标题】:Why does Jest say there are assertion calls when no exception is thrown?为什么 Jest 在没有抛出异常的情况下说有断言调用?
【发布时间】:2020-09-27 06:22:11
【问题描述】:

在将 expect.hasAssertions()expect.assertions(0) 添加到我现有的 Jest (js) 测试中时,我发现 Jest 意外地失败了 一些 测试,因为断言调用的预期和实际数量不匹配。

预期要调用零个断言,但收到一个断言调用。

我发现,即使我从头开始创建一个项目并添加非常简单的测试,Jest 也会由于预期/实际的断言调用而失败。

例如。 将 expect.assertions(0) 从 Jest 的网站添加到示例失败

test('two plus two is four', () => {
        // I'd think this would pass but it fails
        expect.assertions(0);
        expect(2 + 2).toBe(4);
});

expect.hasAssertions() 添加到 Jest 网站通行证的示例中

test('two plus two is four', () => {
        // I'd think this would fail but it passes
        expect.hasAssertions();
        expect(2 + 2).toBe(4);
});

为什么 Jest 在没有抛出异常的情况下说有断言调用?

开玩笑:26.4.2, 节点:13.11.0, NPM:6.13.7

注意:这和Expected one assertion to be called but received zero assertion calls不一样

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    expect.assertions 断言存在指定数量的断言,即expect(...)... 调用。 expect.assertions 断言存在断言。他们不断言有特定的失败的断言。他们也会考虑失败的断言,但由于第一次失败的断言测试失败,计算它们没有意义。

    由于有 1 个断言 (expect(2 + 2).toBe(4)),expect.assertions(0) 失败。

    因此,这些将通过:

    test('two plus two is four', () => {
        expect.assertions(1);
        expect(2 + 2).toBe(4);
    });
    
    test('two plus two is four', () => {
        expect.hasAssertions();
        expect(2 + 2).toBe(4);
    });
    

    这些会失败:

    test('two plus two is four', () => {
        expect.assertions(0);
        expect(2 + 2).toBe(4);
    });
    
    test('two plus two is four', () => {
        expect.hasAssertions();
    });
    

    【讨论】:

    • 出于某种原因,我将其专门视为引发的错误数量。现在一切都说得通了。感谢您对愚蠢时刻的礼貌回应。
    猜你喜欢
    • 2010-12-29
    • 2015-07-11
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多