如何测试我的自定义 Hook?谢谢你的帮助。
import { useEffect, useRef } from 'react';
export function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => {
clearInterval(id);
};
}
}, [delay]);
}
在我的组件中,我将其用作计时器 - 在依赖项中声明的时间后执行操作
这是我开始工作的一个例子:
import { mount } from 'enzyme';
import React from 'react';
import useInterval from 'YOUR CODE ABOVE'; // <------- Adjust this Import
function MockComponent({ timer, updateTimer }) {
const handleStartButton = () => {
updateTimer({ ...timer });
};
useInterval(
() => {
updateTimer({ ...timer });
},
timer.isTicking ? 1000 : null
);
return (
<button type="button" className="start" onClick={() => handleStartButton()}>
Start Countdown
</button>
);
}
describe('useInterval', () => {
const spyFunction = jest.fn();
const timer = {
isTicking: true,
};
let wrapper = null;
jest.useFakeTimers();
beforeEach(() => {
wrapper = mount(<MockComponent updateTimer={spyFunction} timer={timer} />);
});
afterEach(() => {
wrapper.unmount();
wrapper = null;
});
it('timer should run', () => {
expect(spyFunction).not.toHaveBeenCalled();
wrapper.find('button.start').simulate('click');
// works as expected
expect(spyFunction).toHaveBeenCalled();
// Increment
jest.advanceTimersByTime(1000);
// It should have been called at least twice.
expect(spyFunction).toHaveBeenCalledTimes(2);
});
});