Skip to content

Instantly share code, notes, and snippets.

@cgarrovillo
Last active March 22, 2024 17:10
Show Gist options
  • Save cgarrovillo/13c3940890bf253d80629044299565bd to your computer and use it in GitHub Desktop.
Save cgarrovillo/13c3940890bf253d80629044299565bd to your computer and use it in GitHub Desktop.
useInterval with watched returns
import { renderHook } from "@testing-library/react";
import useInterval from "./useInterval";
describe("useInterval", () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
jest.useRealTimers();
});
it("should start the interval on mount when called by itself", () => {
const callback = jest.fn();
renderHook(() => useInterval(callback, 1000));
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledTimes(1);
});
it("should start the interval on mount when return value is assigned", () => {
const callback = jest.fn();
renderHook(() => {
const interval = useInterval(callback, 1000);
return interval;
});
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledTimes(1);
});
it("should not start the interval on mount when return value at index 0 is extracted", () => {
const callback = jest.fn();
renderHook(() => {
const [poll] = useInterval(callback, 1000);
return poll;
});
jest.advanceTimersByTime(1000);
expect(callback).not.toHaveBeenCalled();
});
it("should start the interval on mount when return value at index 1 is extracted", () => {
const callback = jest.fn();
renderHook(() => {
const [, nullish] = useInterval(callback, 1000);
return nullish;
});
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledTimes(1);
});
it("should not start the interval on mount, but on command when return value is extracted and called", () => {
const callback = jest.fn();
const { result } = renderHook(() => {
const [poll] = useInterval(callback, 1000);
return poll;
});
jest.advanceTimersByTime(1000);
expect(callback).not.toHaveBeenCalled();
result.current();
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledTimes(1);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment