@@ -85,24 +85,55 @@ describe("copyToClipboard", () => {
8585 expect ( document . querySelector ( "textarea" ) ) . toBeNull ( ) ;
8686 } ) ;
8787
88- it ( "restores focus after the execCommand fallback " , async ( ) => {
88+ it ( "keeps deferred focus restoration bound to its document after globals retire " , async ( ) => {
8989 vi . stubGlobal ( "navigator" , { } ) ;
90- mockExecCommand ( true ) ;
91- const button = document . createElement ( "button" ) ;
92- document . body . append ( button ) ;
93- button . focus ( ) ;
94- const focus = vi . spyOn ( button , "focus" ) ;
95- button . disabled = true ;
96-
97- expect ( await copyToClipboard ( "hello" ) ) . toBe ( true ) ;
98- button . disabled = false ;
99- button . blur ( ) ;
100- await new Promise < void > ( ( resolve ) => {
101- window . setTimeout ( resolve , 0 ) ;
102- } ) ;
103- expect ( document . activeElement ) . toBe ( button ) ;
104- expect ( focus ) . toHaveBeenCalledWith ( { preventScroll : true } ) ;
105-
106- button . remove ( ) ;
90+ mockExecCommand ( false ) ;
91+ vi . useFakeTimers ( ) ;
92+ try {
93+ expect ( await copyToClipboard ( "hello" ) ) . toBe ( false ) ;
94+ expect ( vi . getTimerCount ( ) ) . toBeGreaterThan ( 0 ) ;
95+ vi . stubGlobal ( "document" , undefined ) ;
96+ expect ( ( ) => vi . runAllTimers ( ) ) . not . toThrow ( ) ;
97+ } finally {
98+ vi . unstubAllGlobals ( ) ;
99+ vi . useRealTimers ( ) ;
100+ }
107101 } ) ;
102+
103+ it . each ( [ "restore" , "newer focus" , "removed target" ] as const ) (
104+ "restores focus only when still appropriate after the fallback: %s" ,
105+ async ( state ) => {
106+ vi . stubGlobal ( "navigator" , { } ) ;
107+ mockExecCommand ( true ) ;
108+ const button = document . createElement ( "button" ) ;
109+ const input = document . createElement ( "input" ) ;
110+ document . body . append ( button ) ;
111+ button . focus ( ) ;
112+ const focus = vi . spyOn ( button , "focus" ) ;
113+ button . disabled = true ;
114+
115+ expect ( await copyToClipboard ( "hello" ) ) . toBe ( true ) ;
116+ button . disabled = false ;
117+ button . blur ( ) ;
118+ if ( state === "newer focus" ) {
119+ document . body . append ( input ) ;
120+ input . focus ( ) ;
121+ } else if ( state === "removed target" ) {
122+ button . remove ( ) ;
123+ }
124+ await new Promise < void > ( ( resolve ) => {
125+ window . setTimeout ( resolve , 0 ) ;
126+ } ) ;
127+ if ( state === "restore" ) {
128+ expect ( document . activeElement ) . toBe ( button ) ;
129+ expect ( focus ) . toHaveBeenCalledWith ( { preventScroll : true } ) ;
130+ } else {
131+ expect ( document . activeElement ) . toBe ( state === "newer focus" ? input : document . body ) ;
132+ expect ( focus ) . not . toHaveBeenCalled ( ) ;
133+ }
134+
135+ button . remove ( ) ;
136+ input . remove ( ) ;
137+ } ,
138+ ) ;
108139} ) ;
0 commit comments