根据https://github.com/airbnb/enzyme/issues/1937中的讨论,这就是解决方案
可以使用非箭头函数对类进行猴子修补,其中“ this”关键字将传递到正确的作用域。
function mockGetRef(ref:any) { this.contentRef = {offsetHeight: 100}}jest.spyOn(MyComp.prototype, 'getRef').mockImplementationOnce(mockGetRef);const comp = mount(<MyComp />);expect(comp.state('contentHeight')).toEqual(100);


