Arun
Arun

Reputation: 1296

How to call actual callback function in Jest unit test

I have the following piece of code.

window.requestAnimationFrame(() => {
  process("postProcess");
  window.clearTimeout();
});

When I write unit test to this, I can assert requestAnimationFrame getting called but not on the process function and clearTimeout since requestAnimationFrame is jest.fn(). How to call the actual callback function while unitTesting?

Upvotes: 1

Views: 3446

Answers (1)

Marcus
Marcus

Reputation: 2321

You've commented that you are able to mock requestAnimationFrame already and can assert that it is called. This actually gets you a long way to an answer.

Extend your jest mock from the jest.fn() to an implementation that immediately calls the callback that is passed to it as an argument.

requestAnimationFrame.mockImplementation((callback) => callback())

Thus when your tests run process and window.clearTimeout will be immediately invoked; so long as you are also mocking or spying on those functions you can assert that those are called too.

Upvotes: 3

Related Questions