I have a functional component, which uses a method to scrollTo a certain div (via a ref), so very simplified it's like that:
import React, {useRef} from 'react';
export const DummyComponent: React.FC = props => {
const divRef = useRef<HTMLDivElement>();
const scrollToDiv = () => divRef.current.scrollTo();
return (
<div ref={divRef} />
<button onClick={scrollToDiv}>scroll</button>
</div>
);
}
I want to simulate the button click, but the error message is Error: Uncaught [TypeError: divRef.current.scrollTo is not a function]
.
What I've tried in the test so far (including this answer):
import React from 'react';
import { mount, ReactWrapper } from 'enzyme';
import {DummyComponent} from "./DummyComponent";
let wrapper: ReactWrapper;
describe('test', () => {
beforeEach(() => {
wrapper = mount(<DummyComponent/>);
});
test('simulate', () => {
/* despite the spyOn, when I debug the ref is actually holding the div - scrollTo is not working though */
jest.spyOn(React, 'useRef').mockReturnValue({current: {scrollTo: jest.fn()}});
/* this also has no effect */
jest.mock('./DummyComponent', () => ({
scrollToTop: jest.fn()
}));
wrapper.find('button').simulate('click');
});
});
Any help or hints would be highly appreciated.