简体   繁体   中英

How Can I test my custom Hook in React JS?

How Can I test my custom Hook? Thank you for your help.

import { useEffect, useRef } from 'react';

export function useInterval(callback, delay) {
  const savedCallback = useRef();
  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      const id = setInterval(tick, delay);
      return () => {
        clearInterval(id);
      };
    }
  }, [delay]);
}

In my component I am using it as a timer - perform an action after time declared in a dependency

Here is an example I got working:


import { mount } from 'enzyme';
import React from 'react';
import useInterval from 'YOUR CODE ABOVE'; // <------- Adjust this Import



function MockComponent({ timer, updateTimer }) {
  const handleStartButton = () => {
    updateTimer({ ...timer });
  };

  useInterval(
    () => {
      updateTimer({ ...timer });
    },
    timer.isTicking ? 1000 : null
  );

  return (
    <button type="button" className="start" onClick={() => handleStartButton()}>
      Start Countdown
    </button>
  );
}

describe('useInterval', () => {
  const spyFunction = jest.fn();

  const timer = {
    isTicking: true,
  };

  let wrapper = null;

  jest.useFakeTimers();

  beforeEach(() => {
    wrapper = mount(<MockComponent updateTimer={spyFunction} timer={timer} />);
  });

  afterEach(() => {
    wrapper.unmount();
    wrapper = null;
  });

  it('timer should run', () => {

    expect(spyFunction).not.toHaveBeenCalled();

    wrapper.find('button.start').simulate('click');

    // works as expected
    expect(spyFunction).toHaveBeenCalled();

    // Increment
    jest.advanceTimersByTime(1000);

    // It should have been called at least twice.
    expect(spyFunction).toHaveBeenCalledTimes(2);
  });
});



The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM