简体   繁体   中英

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 . Normally you pass it a callback to process the data returned from a remote 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 . 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.

I've tried:

  • Defining a function with an empty watch method defined on it, and using it as the implementation for get.
  • Trying to also replace the watch method using mockImplementation calls

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. Do I have any other options?

What about the straightforward approach:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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