Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SecretInput.browser.test.tsx

66 lines2.1 KB

1import { act } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4import { userEvent } from "vite-plus/test/browser";
5​
6import { SecretInput } from "./SecretInput";
7​
8let root: Root;
9let container: HTMLDivElement;
10​
11beforeEach(() => {
12 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
13 container = document.createElement("div");
14 document.body.append(container);
15 root = createRoot(container);
16});
17​
18afterEach(async () => {
19 await act(async () => root.unmount());
20 container.remove();
21 vi.unstubAllGlobals();
22});
23​
24const input = () => container.querySelector("input")!;
25​
26async function edit(value: string) {
27 await userEvent.clear(input());
28 if (value) await userEvent.type(input(), value);
29 await userEvent.click(document.body);
31​
32describe("SecretInput", () => {
33 it("preserves a configured secret on empty edits and commits a replacement", async () => {
34 const onCommit = vi.fn();
35 await act(async () => root.render(<SecretInput configured value="" onCommit={onCommit} />));
36 expect(input().type).toBe("password");
37​
38 await userEvent.click(input());
39 await userEvent.click(document.body);
40 expect(onCommit).not.toHaveBeenCalled();
41​
42 await edit("replacement");
43 expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");
44 expect(input().value).toBe("");
45 });
46​
47 it("allows clearing an unsaved draft", async () => {
48 const onCommit = vi.fn();
49 await act(async () => root.render(<SecretInput value="draft" onCommit={onCommit} />));
50 await edit("");
51 expect(onCommit).toHaveBeenCalledExactlyOnceWith("");
52 });
53​
54 it("keeps an in-progress replacement when settings refresh", async () => {
55 const onCommit = vi.fn();
56 const render = () => root.render(<SecretInput configured value="" onCommit={onCommit} />);
57 await act(async () => render());
58​
59 await userEvent.type(input(), "replacement");
60 await act(async () => render());
61 expect(input().value).toBe("replacement");
62​
63 await userEvent.keyboard("{Enter}");
64 expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");
65 });
66});