【问题标题】:Expected one assertion to be called but received zero assertion calls期望调用一个断言,但接收到零个断言调用
【发布时间】:2018-02-25 04:43:43
【问题描述】:

我正在尝试使用 Jest 测试一个方法...该方法应该返回 Promise.reject() 。

这是我写的代码:

test('testing Invalid Response Type', () => {       
        const client = new DataClient();

        client.getSomeData().then(response => {
            console.log("We got data: "+ response);
        }).catch(e => {
            console.log("in catch");
            expect(e).toBeInstanceOf(IncorrectResponseTypeError);

        });
        expect.assertions(1);

  });

当我运行测试时,它会打印“in catch”但失败并出现以下异常: 预计会调用一个断言,但收到零个断言调用。

console.log src/data/dataclient.test.js:25
      in catch

  ● testing Invalid Response Type

    expect.assertions(1)

    Expected one assertion to be called but received zero assertion calls.

      at extractExpectedAssertionsErrors (node_modules/expect/build/extract_expected_assertions_errors.js:37:19)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

【问题讨论】:

  • 看起来您没有匹配的 errorType。 (您发现了一个错误,但它不是IncorrectResponseTypeError 类型)
  • 也许您可以尝试在控制台中记录 e 以查看它实际上是什么类型

标签: javascript unit-testing promise jestjs es6-promise


【解决方案1】:

我通过在块之前添加 return 语句来解决它。 使用 return 语句,该函数将等待 catch 块完成.. 因此期望将被执行..

test('testing Invalid Response Type', () => {       
    const client = new DataClient();
    return client.getSomeData().then(response => {
            console.log("We got data: "+ response);
        }).catch(e => {
            console.log("in catch");
            expect(e).toBeInstanceOf(IncorrectResponseTypeError);

        });
        expect.assertions(1);
   });

【讨论】:

  • 如果你使用 async/await 怎么办?
  • 您在expect.assertions(1); 运行之前返回。
  • @ckim16 看到我的回答,没有理由不去
【解决方案2】:

您需要等待 Promise 完成以检查断言的数量(以到达 .catch 块)。

请参阅jest's asynchronous tutorial,特别是 async/await 解决方案。实际上,他们的示例与您的问题几乎相同。

在你的例子中,你会这样做:

test('testing Invalid Response Type', async () => { // <-- making your test async!      
    const client = new DataClient();

    await client.getSomeData().then(response => { // <-- await for your function to finish
        console.log("We got data: "+ response);
    }).catch(e => {
        console.log("in catch");
        expect(e).toBeInstanceOf(IncorrectResponseTypeError);

    });
    expect.assertions(1);

});

顺便说一句,公认的解决方案也有效,但不适合异步代码的多次测试

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 2021-12-04
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多