Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected one assertion to be called but received zero assertion calls

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)
like image 693
ALBI Avatar asked Jan 30 '23 14:01

ALBI


2 Answers

I solved it by adding return statement before the block. With return statement the function will wait for catch block to finish.. and hence expect will be executed..

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);
   });
like image 128
ALBI Avatar answered Feb 03 '23 06:02

ALBI


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

like image 20
noam7700 Avatar answered Feb 03 '23 08:02

noam7700