Skip to content

Commit

Permalink
test: test useDebounce
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Jun 3, 2023
1 parent b411482 commit 490355d
Showing 1 changed file with 88 additions and 1 deletion.
89 changes: 88 additions & 1 deletion packages/utils-react/src/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Compose } from "./compose";
import { Debug } from "./debug";
import { toArraySetState, toDelayedSetState, toSetSetState } from "./set-state";
import { renderToJson } from "./test/helper";
import { useDelay } from "./timer";
import { useDebounce, useDelay } from "./timer";
import { usePrevious, useRefCallbackEffect, useStableCallback } from "./utils";

describe("Debug", () => {
Expand Down Expand Up @@ -418,3 +418,90 @@ describe(useDelay.name, () => {
expect(result.current.state).toMatchInlineSnapshot("false");
});
});

// TODO: test effect cleanup
describe(useDebounce.name, () => {
beforeEach(() => {
vi.useFakeTimers();
});

it("basic", async () => {
const { result, unmount } = renderHook(() => {
const [state, setState] = React.useState<number[]>([]);
const { push } = toArraySetState(setState);
const [debounced, { isPending }] = useDebounce(push, 100);
return { result: { state, isPending }, push, debounced };
});

expect(result.current.result).toMatchInlineSnapshot(`
{
"isPending": false,
"state": [],
}
`);

act(() => {
result.current.push(0);
});
expect(result.current.result).toMatchInlineSnapshot(`
{
"isPending": false,
"state": [
0,
],
}
`);

act(() => {
result.current.debounced(1);
});
expect(result.current.result).toMatchInlineSnapshot(`
{
"isPending": true,
"state": [
0,
],
}
`);

act(() => {
vi.advanceTimersByTime(80);
});
expect(result.current.result).toMatchInlineSnapshot(`
{
"isPending": true,
"state": [
0,
],
}
`);

act(() => {
vi.advanceTimersByTime(80);
});
expect(result.current.result).toMatchInlineSnapshot(`
{
"isPending": false,
"state": [
0,
1,
],
}
`);

act(() => {
result.current.debounced(2);
unmount();
vi.runAllTimers();
});
expect(result.current.result).toMatchInlineSnapshot(`
{
"isPending": false,
"state": [
0,
1,
],
}
`);
});
});

0 comments on commit 490355d

Please sign in to comment.