|
9 | 9 | * immediately pollutes the tests with false negatives. Even if something should
|
10 | 10 | * fail, it won't.
|
11 | 11 | */
|
12 |
| -import{act,renderHook,screen}from"@testing-library/react"; |
| 12 | + |
| 13 | +import{renderHook,screen}from"@testing-library/react"; |
13 | 14 | import{GlobalSnackbar}from"components/GlobalSnackbar/GlobalSnackbar";
|
14 | 15 | import{ThemeOverride}from"contexts/ThemeProvider";
|
| 16 | +import{act}from"react"; |
15 | 17 | importthemes,{DEFAULT_THEME}from"theme";
|
16 | 18 | import{
|
17 | 19 | COPY_FAILED_MESSAGE,
|
@@ -259,4 +261,49 @@ describe.each(secureContextValues)("useClipboard - secure: %j", (isSecure) => {
|
259 | 261 |
|
260 | 262 | expect(result.current.error).toBeInstanceOf(Error);
|
261 | 263 | });
|
| 264 | + |
| 265 | +// This check is really important to ensure that it's easy to plop this |
| 266 | +// inside of useEffect calls without having to think about dependencies too |
| 267 | +// much |
| 268 | +it("Ensures that the copyToClipboard function always maintains a stable reference across all re-renders",async()=>{ |
| 269 | +constinitialOnError=jest.fn(); |
| 270 | +const{ result, rerender}=renderUseClipboard({ |
| 271 | +onError:initialOnError, |
| 272 | +}); |
| 273 | +constinitialCopy=result.current.copyToClipboard; |
| 274 | + |
| 275 | +// Re-render arbitrarily with no clipboard state transitions to make |
| 276 | +// sure that a parent re-rendering doesn't break anything |
| 277 | +rerender({onError:initialOnError}); |
| 278 | +expect(result.current.copyToClipboard).toBe(initialCopy); |
| 279 | + |
| 280 | +// Re-render with new onError prop and then swap back to simplify |
| 281 | +// testing |
| 282 | +rerender({onError:jest.fn()}); |
| 283 | +expect(result.current.copyToClipboard).toBe(initialCopy); |
| 284 | +rerender({onError:initialOnError}); |
| 285 | + |
| 286 | +// Trigger a failed clipboard interaction |
| 287 | +setSimulateFailure(true); |
| 288 | +awaitact(()=>result.current.copyToClipboard("dummy-text-2")); |
| 289 | +expect(result.current.copyToClipboard).toBe(initialCopy); |
| 290 | +}); |
| 291 | + |
| 292 | +it("Always uses the most up-to-date onError prop",async()=>{ |
| 293 | +constinitialOnError=jest.fn(); |
| 294 | +const{ result, rerender}=renderUseClipboard({ |
| 295 | +onError:initialOnError, |
| 296 | +}); |
| 297 | +setSimulateFailure(true); |
| 298 | + |
| 299 | +constsecondOnError=jest.fn(); |
| 300 | +rerender({onError:secondOnError}); |
| 301 | +awaitact(()=>result.current.copyToClipboard("dummy-text")); |
| 302 | + |
| 303 | +expect(initialOnError).not.toHaveBeenCalled(); |
| 304 | +expect(secondOnError).toHaveBeenCalledTimes(1); |
| 305 | +expect(secondOnError).toHaveBeenCalledWith( |
| 306 | +"Failed to copy text to clipboard", |
| 307 | +); |
| 308 | +}); |
262 | 309 | });
|