我有一个自定义钩子,用于检查页面何时重新加载以及选项卡何时关闭。
import { useRef, useEffect } from 'react';
const useUnload = fn => {
const cb = useRef(fn);
useEffect(() => {
cb.current = fn;
}, [fn]);
useEffect(() => {
const onUnload = (...args) => cb.current?.(...args);
window.addEventListener("beforeunload", onUnload);
return () => window.removeEventListener("beforeunload", onUnload);
}, []);
};
export default useUnload;
如何使用:
const MyComponent = () => {
useUnload(e => {
e.preventDefault();
e.returnValue = '';
});
return (
<div>
my component ...
</div>
);
};
基本上,当页面重新加载、url 更改或选项卡关闭时,会出现一个模式窗口,询问您是否要离开该页面。我需要用酶和笑话来测试这个钩子。
import { mount, shallow } from 'enzyme';
import React from 'react';
import { useUnload } from '../useUnload';
const HookWrapper = ({ hook }) => {
return <React.Component>{hook}</React.Component>;
};
describe('useUnload', () => {
it('should render', () => {
const wrapper = mount(
<HookWrapper
hook={() =>
useUnload((e) => {
e.preventDefault();
e.returnValue = '';
})
}
/>,
);
console.log(wrapper.debug())
});
});
但我收到错误:Component(...): No 渲染method found on the returned component instance: you may have forgotten to define渲染.。
谁能帮忙测试这个钩子?