【发布时间】:2021-06-05 16:29:44
【问题描述】:
我有一个应该在不久的将来执行的函数,我想开玩笑地测试它,但不知道如何正确地执行此操作。实际上,我正在使用 React + 测试反应库,但这并没有改变我认为的任何东西。
这是函数本身:
let start;
const holdClick = (el, delayedClickHandler, time = 0) => {
if (time === 0) return delayedClickHandler();
let counter = 0;
function countToExecute() {
if (counter === time) delayedClickHandler();
else {
start = requestAnimationFrame(countToExecute);
counter += 1;
}
}
start = window.requestAnimationFrame(countToExecute);
el.ontouchend = () => {
window.cancelAnimationFrame(start);
};
};
我的组件
function Component() {
const [clicked, setClicked] = useState(false);
return (
<span
// data attribute must be changed to "active" after 30 ticks
data-testid={clicked ? 'active' : 'static'}
onTouchStart={e => holdClick(e.target, () => setClicked(true), 30)}
>
click me
</span>
);
}
还有我的测试
test('execute delayed click', () => {
beforeEach(() => {
jest.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => cb());
});
const { getByTestId } = render(<App />);
const el = getByTestId('static');
fireEvent.click(el);
jest.useFakeTimers();
setTimeout(() => {
expect(el).toHaveAttribute('data-testid', 'active');
}, 10000);
jest.runAllTimers();
});
我的猜测是问题出在requestAnimationFrame,但正如我之前提到的,我几乎不知道有什么方法可以解决这个问题。我尝试添加jest.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => cb());,但它没有改变任何东西。 所以我想知道是否有不需要麻烦的模拟 window 对象的解决方案。
【问题讨论】:
标签: javascript reactjs testing jestjs react-testing-library