Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

refactor(site): clean up clipboard functionality and define tests#12296

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Parkreiner merged 19 commits intomainfrommes/clipboard-tests
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
19 commits
Select commitHold shift + click to select a range
d1dd31a
refactor: clean up and update API for useClipboard
ParkreinerFeb 25, 2024
91123d9
wip: commit current progress on useClipboard test
ParkreinerFeb 25, 2024
118151a
docs: clean up wording on showCopySuccess
ParkreinerFeb 25, 2024
035e678
chore: make sure tests can differentiate between HTTP/HTTPS
ParkreinerFeb 26, 2024
eb8b552
chore: add test ID to dummy input
ParkreinerFeb 26, 2024
ba0dad8
wip: commit progress on useClipboard test
ParkreinerFeb 26, 2024
97e0c8d
wip: commit more test progress
ParkreinerFeb 26, 2024
6c697e3
refactor: rewrite code for clarity
ParkreinerFeb 26, 2024
abbec2d
chore: finish clipboard tests
ParkreinerFeb 26, 2024
47604cc
fix: prevent double-firing for button click aliases
ParkreinerFeb 26, 2024
e1ff73f
refactor: clean up test setup
ParkreinerFeb 26, 2024
ba26ef3
fix: rename incorrect test file
ParkreinerFeb 26, 2024
734b4f1
refactor: update code to display user errors
ParkreinerFeb 27, 2024
5cfbc8e
refactor: redesign useClipboard to be easier to test
ParkreinerFeb 27, 2024
4caa0a1
refactor: clean up GlobalSnackbar
ParkreinerFeb 27, 2024
325ab9e
feat: add functionality for notifying user of errors (with tests)
ParkreinerFeb 27, 2024
fe5bcef
refactor: clean up test code
ParkreinerFeb 27, 2024
72ba489
refactor: centralize cleanup steps
ParkreinerFeb 27, 2024
567da76
Merge branch 'main' into mes/clipboard-tests
ParkreinerFeb 28, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletionsite/src/components/CodeExample/CodeExample.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,11 @@ export const CodeExample: FC<CodeExampleProps> = ({
}) => {
const buttonRef = useRef<HTMLButtonElement>(null);
const triggerButton = (event: KeyboardEvent | MouseEvent) => {
if (event.target !== buttonRef.current) {
const clickTriggeredOutsideButton =
event.target instanceof HTMLElement &&
!buttonRef.current?.contains(event.target);

if (clickTriggeredOutsideButton) {
buttonRef.current?.click();
}
};
Expand Down
6 changes: 4 additions & 2 deletionssite/src/components/CopyButton/CopyButton.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,7 +32,9 @@ export const CopyButton = forwardRef<HTMLButtonElement, CopyButtonProps>(
buttonStyles,
tooltipTitle = Language.tooltipTitle,
} = props;
const { isCopied, copyToClipboard } = useClipboard(text);
const { showCopiedSuccess, copyToClipboard } = useClipboard({
textToCopy: text,
});

return (
<Tooltip title={tooltipTitle} placement="top">
Expand All@@ -45,7 +47,7 @@ export const CopyButton = forwardRef<HTMLButtonElement, CopyButtonProps>(
variant="text"
onClick={copyToClipboard}
>
{isCopied ? (
{showCopiedSuccess ? (
<Check css={styles.copyIcon} />
) : (
<FileCopyIcon css={styles.copyIcon} />
Expand Down
6 changes: 4 additions & 2 deletionssite/src/components/CopyableValue/CopyableValue.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,12 +16,14 @@ export const CopyableValue: FC<CopyableValueProps> = ({
children,
...attrs
}) => {
const { isCopied, copyToClipboard } = useClipboard(value);
const { showCopiedSuccess, copyToClipboard } = useClipboard({
textToCopy: value,
});
const clickableProps = useClickable<HTMLSpanElement>(copyToClipboard);

return (
<Tooltip
title={isCopied ? "Copied!" : "Click to copy"}
title={showCopiedSuccess ? "Copied!" : "Click to copy"}
placement={placement}
PopperProps={PopperProps}
>
Expand Down
30 changes: 15 additions & 15 deletionssite/src/components/GlobalSnackbar/GlobalSnackbar.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -24,37 +24,37 @@ const variantFromMsgType = (type: MsgType) => {
};

export const GlobalSnackbar: FC = () => {
const [open, setOpen] = useState<boolean>(false);
const [notification, setNotification] = useState<NotificationMsg>();

const [notificationMsg, setNotificationMsg] = useState<NotificationMsg>();
useCustomEvent<NotificationMsg>(SnackbarEventType, (event) => {
setNotification(event.detail);
setOpen(true);
setNotificationMsg(event.detail);
});

if (!notification) {
const hasNotification = notificationMsg !== undefined;
if (!hasNotification) {
return null;
}

return (
<EnterpriseSnackbar
key={notification.msg}
open={open}
variant={variantFromMsgType(notification.msgType)}
onClose={() => setOpen(false)}
autoHideDuration={notification.msgType === MsgType.Error ? 22000 : 6000}
key={notificationMsg.msg}
open={hasNotification}
variant={variantFromMsgType(notificationMsg.msgType)}
onClose={() => setNotificationMsg(undefined)}
autoHideDuration={
notificationMsg.msgType === MsgType.Error ? 22000 : 6000
}
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
message={
<div css={{ display: "flex" }}>
{notification.msgType === MsgType.Error && (
{notificationMsg.msgType === MsgType.Error && (
<ErrorIcon css={styles.errorIcon} />
)}

<div css={{ maxWidth: 670 }}>
<span css={styles.messageTitle}>{notification.msg}</span>
<span css={styles.messageTitle}>{notificationMsg.msg}</span>

{notification.additionalMsgs &&
notification.additionalMsgs.map((msg, index) => (
{notificationMsg.additionalMsgs &&
notificationMsg.additionalMsgs.map((msg, index) => (
<AdditionalMessageDisplay key={index} message={msg} />
))}
</div>
Expand Down
15 changes: 15 additions & 0 deletionssite/src/hooks/useClipboard-http.test.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
/**
* This test is for all useClipboard functionality, with the browser context
* set to insecure (HTTP connections).
*
* See useClipboard.test-setup.ts for more info on why this file is set up the
* way that it is.
*/
import { useClipboard } from "./useClipboard";
import { scheduleClipboardTests } from "./useClipboard.test-setup";

describe(useClipboard.name, () => {
describe("HTTP (non-secure) connections", () => {
scheduleClipboardTests({ isHttps: false });
});
});
15 changes: 15 additions & 0 deletionssite/src/hooks/useClipboard-https.test.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
/**
* This test is for all useClipboard functionality, with the browser context
* set to secure (HTTPS connections).
*
* See useClipboard.test-setup.ts for more info on why this file is set up the
* way that it is.
*/
import { useClipboard } from "./useClipboard";
import { scheduleClipboardTests } from "./useClipboard.test-setup";

describe(useClipboard.name, () => {
describe("HTTPS (secure/default) connections", () => {
scheduleClipboardTests({ isHttps: true });
});
});
218 changes: 218 additions & 0 deletionssite/src/hooks/useClipboard.test-setup.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
/**
* @file This is a very weird test setup.
*
* There are two main things that it's fighting against to insure that the
* clipboard functionality is working as expected:
* 1. userEvent.setup's default global behavior
* 2. The fact that we need to reuse the same set of test cases for two separate
* contexts (secure and insecure), each with their own version of global
* state.
*
* The goal of this file is to provide a shared set of test behavior that can
* be imported into two separate test files (one for HTTP, one for HTTPS),
* without any risk of global state conflicts.
*
* ---
* For (1), normally you could call userEvent.setup to enable clipboard mocking,
* but userEvent doesn't expose a teardown function. It also modifies the global
* scope for the whole test file, so enabling just one userEvent session will
* make a mock clipboard exist for all other tests, even though you didn't tell
* them to set up a session. The mock also assumes that the clipboard API will
* always be available, which is not true on HTTP-only connections
*
* Since these tests need to split hairs and differentiate between HTTP and
* HTTPS connections, setting up a single userEvent is disastrous. It will make
* all the tests pass, even if they shouldn't. Have to avoid that by creating a
* custom clipboard mock.
*
* ---
* For (2), we're fighting against Jest's default behavior, which is to treat
* the test file as the main boundary for test environments, with each test case
* able to run in parallel. That works if you have one single global state, but
* we need two separate versions of the global state, while repeating the exact
* same test cases for each one.
*
* If both tests were to be placed in the same file, Jest would not isolate them
* and would let their setup steps interfere with each other. This leads to one
* of two things:
* 1. One of the global mocks overrides the other, making it so that one
* connection type always fails
* 2. The two just happen not to conflict each other, through some convoluted
* order of operations involving closure, but you have no idea why the code
* is working, and it's impossible to debug.
*/
import {
type UseClipboardInput,
type UseClipboardResult,
useClipboard,
} from "./useClipboard";
import { act, renderHook } from "@testing-library/react";
import { GlobalSnackbar } from "components/GlobalSnackbar/GlobalSnackbar";

const initialExecCommand = global.document.execCommand;
beforeAll(() => {
jest.useFakeTimers();
});

afterAll(() => {
jest.restoreAllMocks();
jest.useRealTimers();
global.document.execCommand = initialExecCommand;
});

type MockClipboardEscapeHatches = Readonly<{
getMockText: () => string;
setMockText: (newText: string) => void;
simulateFailure: boolean;
setSimulateFailure: (failureMode: boolean) => void;
}>;

type MockClipboard = Readonly<Clipboard & MockClipboardEscapeHatches>;
function makeMockClipboard(isSecureContext: boolean): MockClipboard {
let mockClipboardValue = "";
let shouldFail = false;

return {
get simulateFailure() {
return shouldFail;
},
setSimulateFailure: (value) => {
shouldFail = value;
},

readText: async () => {
if (shouldFail) {
throw new Error("Clipboard deliberately failed");
}

if (!isSecureContext) {
throw new Error(
"Trying to read from clipboard outside secure context!",
);
}

return mockClipboardValue;
},
writeText: async (newText) => {
if (shouldFail) {
throw new Error("Clipboard deliberately failed");
}

if (!isSecureContext) {
throw new Error("Trying to write to clipboard outside secure context!");
}

mockClipboardValue = newText;
},

getMockText: () => mockClipboardValue,
setMockText: (newText) => {
mockClipboardValue = newText;
},

addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
read: jest.fn(),
write: jest.fn(),
};
}

function renderUseClipboard(inputs: UseClipboardInput) {
return renderHook<UseClipboardResult, UseClipboardInput>(
(props) => useClipboard(props),
{
initialProps: inputs,
wrapper: ({ children }) => (
<>
<>{children}</>
<GlobalSnackbar />
</>
),
},
);
}

type ScheduleConfig = Readonly<{ isHttps: boolean }>;

export function scheduleClipboardTests({ isHttps }: ScheduleConfig) {
const mockClipboardInstance = makeMockClipboard(isHttps);

const originalNavigator = window.navigator;
beforeAll(() => {
jest.spyOn(window, "navigator", "get").mockImplementation(() => ({
...originalNavigator,
clipboard: mockClipboardInstance,
}));

if (!isHttps) {
// Not the biggest fan of exposing implementation details like this, but
// making any kind of mock for execCommand is really gnarly in general
global.document.execCommand = jest.fn(() => {
if (mockClipboardInstance.simulateFailure) {
return false;
}

const dummyInput = document.querySelector("input[data-testid=dummy]");
const inputIsFocused =
dummyInput instanceof HTMLInputElement &&
document.activeElement === dummyInput;

let copySuccessful = false;
if (inputIsFocused) {
mockClipboardInstance.setMockText(dummyInput.value);
copySuccessful = true;
}

return copySuccessful;
});
}
});

afterEach(() => {
mockClipboardInstance.setMockText("");
mockClipboardInstance.setSimulateFailure(false);
});

const assertClipboardTextUpdate = async (
result: ReturnType<typeof renderUseClipboard>["result"],
textToCheck: string,
): Promise<void> => {
await act(() => result.current.copyToClipboard());
expect(result.current.showCopiedSuccess).toBe(true);

const clipboardText = mockClipboardInstance.getMockText();
expect(clipboardText).toEqual(textToCheck);
};

/**
* Start of test cases
*/
it("Copies the current text to the user's clipboard", async () => {
const textToCopy = "dogs";
const { result } = renderUseClipboard({ textToCopy });
await assertClipboardTextUpdate(result, textToCopy);
});

it("Should indicate to components not to show successful copy after a set period of time", async () => {
const textToCopy = "cats";
const { result } = renderUseClipboard({ textToCopy });
await assertClipboardTextUpdate(result, textToCopy);

setTimeout(() => {
expect(result.current.showCopiedSuccess).toBe(false);
}, 10_000);

await jest.runAllTimersAsync();
});

it("Should notify the user of an error using the provided callback", async () => {
const textToCopy = "birds";
const onError = jest.fn();
const { result } = renderUseClipboard({ textToCopy, onError });

mockClipboardInstance.setSimulateFailure(true);
await act(() => result.current.copyToClipboard());
expect(onError).toBeCalled();
});
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp