我正在尝试使用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)

最佳答案

我通过在块之前添加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);
   });

关于javascript - 预期将调用一个断言,但收到零个断言调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46248905/

10-09 16:36