【问题标题】:Cannot Get React Hook setInterval Timer to Run During Jest/Enzyme Test在 Jest/Enzyme 测试期间无法运行 React Hook setInterval Timer
【发布时间】: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


    【解决方案1】:

    问题在于jest.useFakeTimers();,更具体地说,是在你称之为它的地方。在伪造计时器之前,您正在将组件安装在 beforeEach 中。因此,您的useInterval 挂钩设置为使用真实的setInterval,而不是开玩笑的伪造。在测试中调用 jest.useFakeTimers(); 的那一刻为时已晚,因为它不会影响任何事情(您没有创建任何与计时器相关的新内容)。

    如果您在beforeEach 中将它移到mount 之前,测试将起作用。

    【讨论】:

    • 谢谢!我这辈子都想不通。我所有的测试都以 100% 的覆盖率通过。
    【解决方案2】:

    尝试做这样的事情

    it("should run the count until you get to 00:00", () => {
        loadWrapperAndInjectDependencies();
        jest.useFakeTimers();
    
        const resendOtpCode = wrapper.find({ testID: "buttonResendCode" });
        resendOtpCode.simulate("press");
    
        jest.runAllTimers();
    
        const timeText = wrapper.find({ testID: "resendCodeTime" });
        expect(timeText.props().children).toBe("00:00");
      });
    

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 2021-07-26
      • 2019-02-06
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 2017-02-12
      相关资源
      最近更新 更多