-
Notifications
You must be signed in to change notification settings - Fork 899
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 12 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
d1dd31a
refactor: clean up and update API for useClipboard
Parkreiner 91123d9
wip: commit current progress on useClipboard test
Parkreiner 118151a
docs: clean up wording on showCopySuccess
Parkreiner 035e678
chore: make sure tests can differentiate between HTTP/HTTPS
Parkreiner eb8b552
chore: add test ID to dummy input
Parkreiner ba0dad8
wip: commit progress on useClipboard test
Parkreiner 97e0c8d
wip: commit more test progress
Parkreiner 6c697e3
refactor: rewrite code for clarity
Parkreiner abbec2d
chore: finish clipboard tests
Parkreiner 47604cc
fix: prevent double-firing for button click aliases
Parkreiner e1ff73f
refactor: clean up test setup
Parkreiner ba26ef3
fix: rename incorrect test file
Parkreiner 734b4f1
refactor: update code to display user errors
Parkreiner 5cfbc8e
refactor: redesign useClipboard to be easier to test
Parkreiner 4caa0a1
refactor: clean up GlobalSnackbar
Parkreiner 325ab9e
feat: add functionality for notifying user of errors (with tests)
Parkreiner fe5bcef
refactor: clean up test code
Parkreiner 72ba489
refactor: centralize cleanup steps
Parkreiner 567da76
Merge branch 'main' into mes/clipboard-tests
Parkreiner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
File renamed without changes.
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
Original file line number | Diff line number | Diff 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 }); | ||
}); | ||
}); |
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
Original file line number | Diff line number | Diff 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 }); | ||
}); | ||
}); |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
/** | ||
* @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 UseClipboardResult, useClipboard } from "./useClipboard"; | ||
import { act, renderHook } from "@testing-library/react"; | ||
|
||
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; | ||
}>; | ||
|
||
type MockClipboard = Readonly<Clipboard & MockClipboardEscapeHatches>; | ||
function makeMockClipboard(isSecureContext: boolean): MockClipboard { | ||
let mockClipboardValue = ""; | ||
|
||
return { | ||
readText: async () => { | ||
if (!isSecureContext) { | ||
throw new Error( | ||
"Trying to read from clipboard outside secure context!", | ||
); | ||
} | ||
|
||
return mockClipboardValue; | ||
}, | ||
writeText: async (newText) => { | ||
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(textToCopy: string) { | ||
return renderHook<UseClipboardResult, { hookText: string }>( | ||
({ hookText }) => useClipboard(hookText), | ||
{ initialProps: { hookText: textToCopy } }, | ||
); | ||
} | ||
|
||
type ScheduleConfig = Readonly<{ isHttps: boolean }>; | ||
|
||
export function scheduleClipboardTests({ isHttps }: ScheduleConfig) { | ||
const mockClipboardInstance = makeMockClipboard(isHttps); | ||
|
||
beforeAll(() => { | ||
const originalNavigator = window.navigator; | ||
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(() => { | ||
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(""); | ||
}); | ||
|
||
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 hookText = "dogs"; | ||
const { result } = renderUseClipboard(hookText); | ||
await assertClipboardTextUpdate(result, hookText); | ||
}); | ||
|
||
it("Should indicate to components not to show successful copy after a set period of time", async () => { | ||
const hookText = "cats"; | ||
const { result } = renderUseClipboard(hookText); | ||
await assertClipboardTextUpdate(result, hookText); | ||
|
||
setTimeout(() => { | ||
expect(result.current.showCopiedSuccess).toBe(false); | ||
}, 10_000); | ||
|
||
await jest.runAllTimersAsync(); | ||
}); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.