Skip to content

Commit

Permalink
add tests for useControlledState
Browse files Browse the repository at this point in the history
  • Loading branch information
dartess committed Aug 25, 2022
1 parent fd852db commit d58d027
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 6 deletions.
12 changes: 6 additions & 6 deletions internal/test/utils.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import * as React from "react";
import { act } from "react-dom/test-utils";
import type { MatcherFunction } from "@testing-library/react";
import { render as tlRender, fireEvent } from "@testing-library/react";
import { renderHook as tlRenderHook } from "@testing-library/react-hooks";
import { fireEvent as fireDomEvent } from "@testing-library/dom";
import userEvent from "@testing-library/user-event";
import type {
RenderHookOptions,
RenderHookResult,
Expand Down Expand Up @@ -142,7 +139,10 @@ export function simulateEnterKeyClick(

type Query = (f: MatcherFunction) => HTMLElement | null;

export { cleanup as cleanupHooks } from "@testing-library/react-hooks";
export { cleanup, fireEvent, screen } from "@testing-library/react";
export { act, userEvent, fireDomEvent };
export {
cleanup as cleanupHooks,
act as actHooks,
} from "@testing-library/react-hooks";
export { cleanup, fireEvent, screen, act } from "@testing-library/react";
export * as userEvent from "@testing-library/user-event";
export type { RenderOptions, RenderResult };
50 changes: 50 additions & 0 deletions packages/utils/__tests__/use-controlled-state.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { afterEach, describe, expect, it } from "vitest";
import { renderHook, cleanupHooks, actHooks } from "@reach-internal/test/utils";
import { useControlledState } from "@reach/utils";

afterEach(cleanupHooks);

describe("useControlledState", () => {
const DEFAULT_VALUE = 10;
const CONTROLLED_VALUE = 42;

it("should return value and setter", () => {
const { result } = renderHook(() =>
useControlledState({
defaultValue: DEFAULT_VALUE,
controlledValue: undefined,
})
);

expect(result.current[0]).toBe(DEFAULT_VALUE);
expect(typeof result.current[1]).toBe("function");
});

it("should work as uncontrolled", () => {
const { result } = renderHook(() =>
useControlledState({
defaultValue: DEFAULT_VALUE,
controlledValue: undefined,
})
);
expect(result.current[0]).toBe(DEFAULT_VALUE);
actHooks(() => {
result.current[1](17);
});
expect(result.current[0]).toBe(17);
});

it("should work as controlled", () => {
const { result } = renderHook(() =>
useControlledState({
defaultValue: DEFAULT_VALUE,
controlledValue: CONTROLLED_VALUE,
})
);
expect(result.current[0]).toBe(CONTROLLED_VALUE);
actHooks(() => {
result.current[1](17);
});
expect(result.current[0]).toBe(CONTROLLED_VALUE);
});
});

0 comments on commit d58d027

Please sign in to comment.