Raheel
Raheel

Reputation: 9024

Expect to have been called failing even after being called

I have a test case code in Jest.

let ticketsTransformer = new TicketTransformer();
    ticketsTransformer.transform = jest.fn(() => results);
expect(ticketsTransformer.transform).toHaveBeenCalled();

const synchronizer = new Synchronizer(
        client,
        ticketsTransformer,
        jest.mock(),
        persister,
        jest.mock()
    );
synchronizer.sync("1999-01-01");
    expect(ticketsTransformer.transform).toHaveBeenCalled();

In the sync method i tried to console.log(this.ticketTransformer.transform()) and it gives me the same results stored in results variable which means that the method is being called as expected. But I am not sure why still my test case is failing and complaining

   Expected number of calls: >= 1
   Received number of calls:    0

      72 |  );
      73 |  synchronizer.sync("1999-01-01");
    > 74 |  expect(ticketsTransformer.transform).toHaveBeenCalled();
         |                                       ^
      75 | });
      76 |

Upvotes: 0

Views: 137

Answers (1)

Beginner
Beginner

Reputation: 9095

So the problem was since it was not waiting for the function to execute before itself it was trying to do the expect.

So inorder to wait you can use async and await, also to check a promise call you can use assertions

sample snippet from the official docs

it('works with async/await', async () => {
  expect.assertions(1);
  const data = await user.getUserName(4);
  expect(data).toEqual('Mark');
});

Upvotes: 1

Related Questions