Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest deep method spy

How can I spy on publish and publishBatch inside an instance property:

Object.defineProperty(Provider, 'instance', {
    get: jest.fn(() => { 
        return {
            publish: jest.fn(),
            publishBatch: jest.fn()
        }
    }),
});

I'm aware of jest.spyOn(Provider, 'instance', 'get'); but I need to go deeper and couldn't find any information in the documentation.

like image 442
freethinker Avatar asked Mar 31 '26 07:03

freethinker


1 Answers

The solution is much easier than I thought:

const obj = {
    publish: jest.fn(),
    publishBatch: jest.fn()
}

Object.defineProperty(Provider, 'instance', {
    get: jest.fn(() => { 
        return obj;
    }),
});

const publishSpy = jest.spyOn(obj, 'publish');

...

expect(publishSpy).toHaveBeenCalled();
like image 135
freethinker Avatar answered Apr 02 '26 20:04

freethinker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!