【发布时间】:2019-11-10 11:10:54
【问题描述】:
在单击按钮组件中,我强制禁用按钮 500 毫秒以防止多次提交,并且在 0.5 秒后禁用状态恢复为默认值。尽管有不同的方法,但我得到了两行代码,我似乎无法在单元测试中涵盖这些代码。
请看下面的简化组件源码:
import React, {useState, useEffect} from 'react';
const Button = ({disabled, onClick}) => {
const [disableButton, forceDisabledButton] = useState(false);
useEffect(() => {
let timeId;
if (disableButton) {
timeId = setTimeout(() => {
forceDisabledButton(false);
}, 500);
}
return () => {
if (timeId) {
clearTimeout(timeId);
}
}
}, [disableButton]);
const onButtonClick = (e) => {
onClick && onClick(e);
forceDisabledButton(true);
}
return (
<button onClick={onButtonClick} disabled={!disableButton ? disabled : disableButton}>Button</button>
)
}
disabled 的默认值设置为false。
测试用例:
(...)
it('should become disabled after click and then return to its previous disabled state', () => {
const mountButton = shallow(<Button/>);
jest.useFakeTimers();
expect(mountButton.find('button').length).toEqual(1);
mountButton.find('button').simulate('click');
expect(mountButton.find('button').prop('disabled')).toEqual(true);
setTimeout(() => {
expect(mountButton.find('button').prop('disabled')).toEqual(false);
expect(clearTimeout).toHaveBeenCalledWith(expect.any(Number));
}, 600)
})
未被覆盖的行是:forceDisabledButton(false); 和 clearTimeout(timeId);。我最初尝试了jest.runAllTimers(),但它也没有设法涵盖这两个功能。测试通过并且在应用程序中我没有任何内存泄漏警告(并且视觉确认按钮被禁用 500 毫秒),所以我知道它工作正常并且这两个函数都被调用。我可以尝试哪些修改来解决我的单元测试中的这两个功能?
谢谢
【问题讨论】:
标签: reactjs jestjs react-hooks use-effect