我在功能组件中有以下方法:
const handleClickOutside = (e: CustomEvent) => {
if (dropdownRef.current!.contains(e.target as Node)) {
return;
}
changeFocusedElement(findSelectedItemIndex());
setShowList(!showList);
};
我正在尝试像这样测试它:
it('Hides list after call handleClickOutside method', () => {
const outerNode = document.createElement('div');
document.body.appendChild(outerNode);
const WrappingComponent = (props: { children: React.ReactElement }) => (
withTestTheme(props.children)
);
const wrapper = mount(
<SelectNew options={testOptions} value="test" />,
{
wrappingComponent: WrappingComponent,
},
);
wrapper.find('.dropdown__field').simulate('click');
expect(wrapper.find('ul').exists()).toBe(true);
outerNode.dispatchEvent(new Event('mousedown'));
wrapper.update();
expect(wrapper.find('ul').exists()).toBe(false);
});
但是我无法进入测试覆盖率报告中显示的功能:
该函数的调用方式如下:
useEffect(
() => {
if (showList) {
document.addEventListener('mousedown', handleClickOutside);
} else {
document.removeEventListener('mousedown', handleClickOutside);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
},
[showList],
);
有什么想法可以进入该函数吗?