Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: check how many times a mocked module function was called

Tags:

jestjs

I am using the module waait in my code to allow me to do things like:

import * as wait from 'waait';
await wait(500);

I have created a manual mock:

module.exports = (() => {
  return Promise.resolve();
});

I then want to have assertions like this in my test:

import * as wait from 'waait';
expect(wait).toHaveBeenCalledTimes(1);
expect(wait).toHaveBeenLastCalledWith(1000);

When I run that, I get:

expect(jest.fn())[.not].toHaveBeenCalledTimes()

jest.fn() value must be a mock function or spy.
Received: undefined
like image 503
jeznag Avatar asked Jan 02 '23 17:01

jeznag


1 Answers

The manual mock you have created is not a mock at all but a fake (i.e. an alternative implementation).

You don't even need it. You can remove the manual mock and write your test like this:

import * as wait from 'waait';

jest.mock('waait');
wait.mockResolvedValue(undefined);

it('does something', () => {
    // run the tested code here
    // ...

    // check the results against the expectations
    expect(wait).toHaveBeenCalledTimes(1);
    expect(wait).toHaveBeenLastCalledWith(1000);
});
like image 170
axiac Avatar answered Mar 14 '23 23:03

axiac