【发布时间】:2020-09-07 10:19:58
【问题描述】:
我正在尝试为这个组件编写一些测试。在 Dan Abramov (code) 的这篇博文之后,我实现了一个自定义的 useInterval 钩子。它基本上是一个声明性的setInterval 函数。但是,我很难用 Jest 和 Enzyme 对其进行测试。该应用程序是使用 create-react-app 引导的。我已经安装了最新版本。当我单击开始按钮时,经过的时间会增加并完美地显示在页面上。在父组件中,我更新了存储经过时间的状态。它将更新的经过时间timer 属性传递给Timer.js。因此,它在屏幕上播下了正确的elapsedTime。这在浏览器中按预期工作。但是,运行测试时计时器不会运行。
// Timer.js
const TimerDisplay = ({ timer, updateTimer }) => {
useInterval(() => {
const delta = Math.floor((Date.now() - timer.offsetTime) / 1000);
updateTimer({ ...timer, elapsedTime: delta });
}, timer.isTicking ? 300 : null);
const handleStartButton = () => {
updateTimer({ ...timer, isTicking: true });
}
return (
<React.Fragment>
<div>{timer.elapsedTime}</div>
<button className='start' onClick={() => handleStartButton()}>Start</button>
<button className='stop' {/* removed for brevity*/}>Stop</button>
</React.Fragment>
);
};
测试代码如下。我使用 Jest 的间谍功能和酶的坐骑。我读到我需要安装而不是因为钩子而使用浅层。我设置 Jest 使用假计时器。然后,我模拟按下开始按钮的按钮,以验证按钮是否正常工作。然而,在这个测试中,我已经设置了isTicking: true,所以我真的不需要模拟开始。尽管功能 spy 按预期工作是一个健全的检查 - 它确实如此。预期的结果是它在 300 毫秒后调用了 spy 回调。因此,当我jest.advanceTimersByTime(500) 时,spy 函数应该在useInterval 回调中至少被调用一次。但是,这并没有在测试中发生。
// Timer.spec.js
describe('Timer', () => {
const spyFunction = jest.fn();
const timer = {
offsetTime: new Date(),
isTicking: true,
elapsedTime: 0
};
let wrapper = null;
beforeEach(() => {
wrapper = mount(<Timer updateTimer={spyFunction} timer={timer} />);
});
afterEach(() => {
wrapper.unmount();
wrapper = null;
});
it('timer should run', () => {
jest.useFakeTimers();
expect(spyFunction).not.toHaveBeenCalled();
wrapper.find('button.start').simulate('click', { button: 0 });
// works as expected
expect(spyFunction).toHaveBeenCalled();
// doesn't seem to work for some reason
jest.advanceTimersByTime(500);
// will fail; function only called once by the button.start. It should have been called at least twice.
expect(spyFunction).toHaveBeenCalledTimes(2);
});
});
我认为这个问题与 useInterval 挂钩有关。我怀疑在能够调用回调之前进行垃圾收集。有什么方法可以测试useInterval钩子的回调调用updateTimer又名Jest.Fn?
// useInterval hook
import { useEffect, useRef } from 'react';
export const useInterval = (callback, delay) => {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
【问题讨论】:
标签: reactjs jestjs react-hooks enzyme create-react-app