Expected one assertion to be called but received zero assertion calls

Viewed 11790

I am trying to test a method using Jest... The method should return Promise.reject() .

Here is the code I wrote:

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

  });

When I run the test, it prints "in catch" but fails with this exception: Expected one assertion to be called but received zero assertion calls.

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 Answers

You need to wait for the promise to finish to check number of assertions (to reach the .catch block).

see jest's asynchronous tutorial, specially the async/await solution. Actually, their example is almost identical to your problem.

in your example, you would do:

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

});

Btw, the accepted solution also works, but not suitable to multiple tests of async code

Related