1 | initial version |
To create unit tests for a custom hook in React that triggers a callback function when an element becomes visible, we can use the following steps:
mount
method to mount the component.find
method to find the element of interest.simulate
method to simulate scrolling to the element and verifying that the callback is called.Here is a sample test code for a custom hook that triggers a callback function when an element becomes visible:
import React, { useRef } from 'react';
import useScrollTrigger from '../useScrollTrigger';
const MyComponent = () => {
const ref = useRef(null);
const isVisible = useScrollTrigger(ref);
return (
<div ref={ref}>
{isVisible ? 'Visible' : 'Not Visible'}
</div>
);
};
describe('useScrollTrigger', () => {
let wrapper;
beforeEach(() => {
wrapper = mount(<MyComponent />);
});
afterEach(() => {
wrapper.unmount();
});
it('calls the callback function when an element becomes visible', () => {
const callback = jest.fn();
const ref = wrapper.find('div').getDOMNode();
useScrollTrigger(ref, callback);
expect(callback).toHaveBeenCalled();
});
});
In this example, we first import the custom hook useScrollTrigger
and a simple component MyComponent
that uses it. useScrollTrigger
takes the ref to the element of interest and an optional callback function that is called when the element becomes visible.
We then use Jest and Enzyme to test the custom hook by rendering the MyComponent
and checking whether the callback is called when the element becomes visible. We simulate that by using Enzyme's getDOMNode
to get the element and call useScrollTrigger
with it and the callback function.
This test code verifies that the custom hook "useScrollTrigger" works as expected and triggers a callback function when an element becomes visible.