Mocking clientHeight and scrollHeight in React + Enzyme for test
Jest spyOn can be used to mock getter and setter from version 22.1.0+. See jest docs
I used below code to mock implementation of document.documentElement.scrollHeight
const scrollHeightSpy = jest .spyOn(document.documentElement, 'scrollHeight', 'get') .mockImplementation(() => 100);
It returns 100 as scrollHeight value.
JSDOM doesn't do any actual rendering - it just simulates the DOM structure - so things like element dimensions aren't calculated as you might expect. If you grab dimensions via method calls there are ways to mock these within your test. For example:
beforeEach(() => { Element.prototype.getBoundingClientRect = jest.fn(() => { return { width: 100, height: 10, top: 0, left: 0, bottom: 0, right: 0 }; }); });
This obviously won't work in your example. It may be possible to override these properties on the elements and mock changes to them; but I suspect that wouldn't lead to particularly meaningful/useful tests.
See also this thread
A simplified solution will only need to mock useRef
or createRef
since the component under test depends on the return value from useRef
:
import { useRef } from 'react';jest.mock('react', () => ({ ...jest.requireActual('react'), useRef: jest.fn(),}));test('test ref', () => { useRef.mockReturnValue({ // insert required properties here }); // do assertions as normal});