使用React,Ease和Jest,如何在closeDrawer()
内的useEffect()
回调道具上获得代码覆盖率
import React, {useEffect} from 'react';
import {Button} from './button';
const DrawerClose = ({closeDrawer}) => {
useEffect(() => {
const handleEsc = (e: any) => {
if (e.key === 'Escape') {
closeDrawer();
}
};
window.addEventListener('keyup', handleEsc);
return () => window.removeEventListener('keyup', handleEsc);
});
return (
<Button>
close
</Button>
);
};
export {DrawerClose};
测试:
import React from 'react';
import {DrawerClose as Block} from './drawer-close';
describe(`${Block.name}`, () => {
it('should have drawer open', () => {
const wrapper = shallow(<Block closeDrawer={() => 'closed'} />);
expect(wrapper).toMatchSnapshot(); // will not hit the useEffect
});
});
答案 0 :(得分:0)
Uncaught TypeError: Cannot read property 'length' of undefined
尚未呼叫shallow()
。这是known issue #2086,是由于React的浅层渲染器而发生的。
您可以使用useEffect
并完全渲染,也可以模拟每个/某些嵌套组件,仍然使用mount()
,但结果更像mount()
。像这样:
shallow()
对于测试本身,您需要确保在击中ESC时将调用jest.mock('../../Button.jsx', (props) => <span {...props} />);
。因此我们需要使用间谍程序并模拟模拟击中ESC
closeDrawer
关于模拟在窗口上按下的ESC,我不确定jest-dom是否允许,您可以尝试(摘自Simulate keydown on document for JEST unit testing)
const closeDrawerSpy = jest.fn();
const wrapper = mount(<Block closeDrawer={closeDrawerSpy} />);
// simulate ESC pressing
如果这不起作用(var event = new KeyboardEvent('keyup', {'keyCode': 27});
window.dispatchEvent(event);
或类似的东西),您总是can mock addEventListener
可以直接访问处理程序。