Last active
March 22, 2024 17:10
-
-
Save cgarrovillo/13c3940890bf253d80629044299565bd to your computer and use it in GitHub Desktop.
useInterval with watched returns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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