简体   繁体   English

如何在 Jest 单元测试中调用实际回调 function

[英]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().当我为此编写单元测试时,我可以断言 requestAnimationFrame 被调用但不在进程 function 和 clearTimeout 上,因为 requestAnimationFrame 是 jest.fn()。 How to call the actual callback function while unitTesting? unitTesting时如何调用实际回调function?

You've commented that you are able to mock requestAnimationFrame already and can assert that it is called.您已经评论说您已经能够模拟 requestAnimationFrame 并且可以断言它已被调用。 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.将您的 jest 模拟从jest.fn()扩展到立即调用作为参数传递给它的回调的实现。

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

Thus when your tests run process and window.clearTimeout will be immediately invoked;因此,当您的测试运行processwindow.clearTimeout将立即被调用; so long as you are also mocking or spying on those functions you can assert that those are called too.只要您也是 mocking 或监视这些函数,您就可以断言这些函数也被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM