繁体   English   中英

如何通过“any”类型的 object 开玩笑地传递函数?

[英]How to pass object of type `any` with functions in jest?

我有一个代码,我从第三方组件接收 object,因此我将其类型标记为any 我在代码中使用的 object 有几种方法。

init(context: any) {
  context.doSomething('profile');
}

现在在测试这段代码时,我想模拟doSomething方法的功能,但我不知道该怎么做。 我在 jest.fn() 中尝试了一些东西,但似乎没有任何效果。 我尝试了类似的东西

type ContextType = { doSomething?: (arg0: { val: string; }) => any; }
let context: ContextType = {};
jest.spyOn(context, 'doSomething').mockReturnValue({});
obj.init(context);

但这似乎不起作用。 但是有人能告诉我如何在我的测试中使用它吗?

创建一个包含doSomething作为模拟 function 的context

let context = { doSomething: jest.fn() };
obj.init(context);

expect(context.doSomething).toHaveBeenCalledWith('profile');

暂无
暂无

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

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