Mock react hook in jest



如何在Jest中模拟下面的钩子?我在另一个钩子中使用这个钩子,当我想测试另一个钩子时,我需要模拟useScrollDetect并删除throttle部分,这意味着我需要立即在滚动事件上调用onScroll

出于教育目的,我不想嘲笑lodash.throttle

use-scroll-detect.ts

import { useCallback, useEffect, useRef } from 'react';
import { throttle } from 'lodash';
/**
* A hook to listen to the scroll event
* @param onScroll Scroll listener
* @param throttleTime Throttling time of the events
* @param enable Enable or disable the listener
*/
const useScrollDetect = (
onScroll: (e: Event) => void,
throttleTime = 100,
enable = true
) => {
const handleScrollThrottle = useCallback(
throttle(onScroll, throttleTime, {
leading: false,
trailing: true,
}),
[onScroll, throttleTime]
);
useEffect(() => {
if (enable) {
window.addEventListener('scroll', handleScrollThrottle, {
passive: true,
});
}
return () => {
if (enable) {
window.removeEventListener('scroll', handleScrollThrottle);
}
};
}, [enable, handleScrollThrottle]);
};
export { useScrollDetect };

您可以尝试通过以下方法模拟它:

// your test file
import * as hooks from './use-scroll-detect.ts';
// typescript will highlight useScrollDetect from jest.spyOn and hooks object
jest.spyOn(hooks, 'useScrollDetect').mockImplementation((
onScroll: (e: Event) => void, 
throttleTime: number, 
enable: boolean
) => {
const mockEvent = {}; // pass necessary values into the object
onScroll(mockEvent); // call your mock fn with some info
});

或者您可以只模拟lodash:

中的throttle函数
jest.mock('lodash', () => ({
...jest.requireActual('lodash'),
throttle: jest.fn().mockImplementation((onScroll: (e: Event) => void) => {
onScroll(new Event('scroll'));
})
}))
fireEvent.scroll(screen.getByText('bla bla')) // put your own function from screen to find element for scrolling

最新更新