11import React from "react" ;
2- import { cleanup , fireEvent , render } from "@testing-library/react" ;
2+ import { cleanup , fireEvent , render , act } from "@testing-library/react" ;
33import useClipboard from "./" ;
44
55afterEach ( cleanup ) ;
@@ -24,3 +24,71 @@ test("display sucess message if the copy worked", () => {
2424
2525 expect ( button . textContent ) . toBe ( "Yes" ) ;
2626} ) ;
27+
28+ describe ( "successDuration" , ( ) => {
29+ test ( "`isCopied` becomes false after `successDuration` time ellapses" , ( ) => {
30+ jest . useFakeTimers ( ) ;
31+ const successDuration = 1000 ;
32+
33+ const Component = ( ) => {
34+ const [ isCopied , setCopied ] = useClipboard ( "Text to copy" , {
35+ successDuration
36+ } ) ;
37+
38+ return (
39+ < button onClick = { setCopied } data-testid = "btn-example" >
40+ { isCopied ? "Yes" : "Nope" }
41+ </ button >
42+ ) ;
43+ } ;
44+
45+ const { getByTestId } = render ( < Component /> ) ;
46+ const button = getByTestId ( "btn-example" ) ;
47+
48+ expect ( button . textContent ) . toBe ( "Nope" ) ;
49+
50+ fireEvent . click ( button ) ;
51+
52+ expect ( button . textContent ) . toBe ( "Yes" ) ;
53+
54+ // Fast-forward half-way
55+ jest . advanceTimersByTime ( successDuration / 2 ) ;
56+
57+ expect ( button . textContent ) . toBe ( "Yes" ) ;
58+
59+ act ( ( ) => {
60+ // Go to the end
61+ jest . advanceTimersByTime ( successDuration / 2 ) ;
62+ } ) ;
63+
64+ expect ( button . textContent ) . toBe ( "Nope" ) ;
65+ } ) ;
66+
67+ test ( "`isCopied` is always true if `successDuration` is not provided" , ( ) => {
68+ jest . useFakeTimers ( ) ;
69+
70+ const Component = ( ) => {
71+ const [ isCopied , setCopied ] = useClipboard ( "Text to copy" , { } ) ;
72+
73+ return (
74+ < button onClick = { setCopied } data-testid = "btn-example" >
75+ { isCopied ? "Yes" : "Nope" }
76+ </ button >
77+ ) ;
78+ } ;
79+
80+ const { getByTestId } = render ( < Component /> ) ;
81+ const button = getByTestId ( "btn-example" ) ;
82+
83+ expect ( button . textContent ) . toBe ( "Nope" ) ;
84+
85+ fireEvent . click ( button ) ;
86+
87+ expect ( button . textContent ) . toBe ( "Yes" ) ;
88+
89+ // Fast-forward half-way
90+ jest . runAllTimers ( ) ;
91+
92+ expect ( button . textContent ) . toBe ( "Yes" ) ;
93+ } ) ;
94+ } ) ;
0 commit comments