期望一个被调用的断言但是接受零断言调用

时间:2017-09-16 00:19:37

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

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

  });

当我运行测试时,它会打印"在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)

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

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

请参见jest's asynchronous tutorial,尤其是异步/等待解决方案。实际上,他们的例子几乎与您的问题相同。

在您的示例中,您可以这样做:

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);

});

顺便说一句,公认的解决方案也可以使用,但不适用于异步代码的多次测试

相关问题