jeff carey
jeff carey

Reputation: 2373

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:

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?

Upvotes: 3

Views: 687

Answers (1)

user268396
user268396

Reputation: 11966

What about the straightforward approach:

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

Upvotes: 2

Related Questions