在单击按钮组件中,我强制禁用按钮 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 毫秒),所以我知道它工作正常并且这两个函数都被调用。我可以尝试在单元测试中解决这两个功能的哪些修改?
谢谢