Javascript 深谋远虑

Javascript 深谋远虑,javascript,jestjs,Javascript,Jestjs,如何在实例属性中监视发布和发布批处理: Object.defineProperty(Provider, 'instance', { get: jest.fn(() => { return { publish: jest.fn(), publishBatch: jest.fn() } }), }); 我知道jest.spyOn(Provider,'instance,'get')但我需要更深入,

如何在
实例
属性中监视
发布
发布批处理

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

我知道jest.spyOn(Provider,'instance,'get')但我需要更深入,在文档中找不到任何信息。

解决方案比我想象的要简单得多:

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();

只是一个简短的提示…您不需要在
obj.publish
上调用
jest.spyOn
,因为它已经是一个模拟函数了…您可以完全跳过这一行,只需执行
expect(obj.publish).tohavebeencall()