React - Jest - Enzyme: How to mock ref properties
You can mock the ref by using Object.defineProperty
. For example:
Object.defineProperty(Element.prototype, 'offsetHeight', {
value: 100,
writable: true,
configurable: true
});
So here's the solution, according to discussion in https://github.com/airbnb/enzyme/issues/1937
It is possible to monkey-patch the class with a non-arrow function, where "this" keyword is passed to the right scope.
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);