简体   繁体   English

测试是否使用 Jest 调用了实际的 function

[英]Test if an actual function was called with Jest

I am simply trying to test if a function was called using jest 26.6.3.我只是想测试是否使用 jest 26.6.3 调用了 function。 I do not want to mock the implementation of the function. I want to test if my actual function was called.不想模拟 function 的实现。我想测试我的实际 function 是否被调用。

const add = (a,b) => a + b;

test("add() was called", () => {
    add(1,2);
    expect(add).toHaveBeenCalled();
})

在此处输入图像描述

If I create a mock function, I don't understand how that would be testing to see if my REAL function has been invoked.如果我创建一个模拟 function,我不明白如何测试我的 REAL function 是否已被调用。 Obviously, the mock function will be executed if I create it using jest.fn() and then invoke it.显然,如果我使用jest.fn()创建它然后调用它,那么模拟 function 将被执行。 Would I have to spy on my add function?我必须监视我的地址 function 吗? Still missing the fundamental understanding to do this simple task.仍然缺少完成这项简单任务的基本理解。

You will need to spy the function add to get some infos about her like when its called... Then you are to be able to do the expect.您将需要监视 function 添加以获取有关她的一些信息,例如在其被调用时......然后您将能够实现预期。

You can do this with jest.spyOn.你可以用 jest.spyOn 做到这一点。

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

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