简体   繁体   English

Jest - 模拟一个函数,该函数又定义了一个方法

[英]Jest - Mocking a function that in turn has a method defined on it

I am converting some old tests to use Jest, and I have a function that is called Services.Transactions.get . 我正在转换一些旧的测试以使用Jest,我有一个名为Services.Transactions.get的函数。 Normally you pass it a callback to process the data returned from a remote API. 通常,您传递一个回调来处理从远程API返回的数据。 In my tests I'm mocking it, using 在我的测试中,我正在嘲笑它,使用

jest.spyOn(Services.Transactions, 'get').mockImplementation((callback) => { callback(someJsObject); });

So far so good. 到现在为止还挺好。

Now the problem is that it in turn has a method Services.Transactions.get.watch . 现在的问题是它又有一个方法Services.Transactions.get.watch The module I'm testing uses both of these functions. 我正在测试的模块使用这两个功能。 Once I mock the first above, I can't mock the watcher method. 一旦我模仿了上面的第一个,我就无法模仿观察者的方法。 I'm told Services.Transactions.get.watch is not a function. 我被告知Services.Transactions.get.watch不是一个函数。

I've tried: 我试过了:

  • Defining a function with an empty watch method defined on it, and using it as the implementation for get. 使用在其上定义的空监视方法定义函数,并将其用作get的实现。
  • Trying to also replace the watch method using mockImplementation calls 尝试使用mockImplementation调用替换watch方法

None of the above worked. 以上都没有奏效。 The file services is coming from is not an ES6 module so doing a module-level mock is something I'd prefer to avoid. 文件服务来自不是ES6模块,所以做模块级模拟是我宁愿避免的。 Do I have any other options? 我还有其他选择吗?

What about the straightforward approach: 直截了当的方法怎么样:

const mock = jest.spyOn(Services.Transactions, 'get');
mock.watch = jest.fn();
mock.mockImplementation(...);

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

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