@@ -3,6 +3,7 @@ import { useClipboardText } from "src";
3
3
4
4
const mockReadText = vi . fn ( ) ;
5
5
const mockWriteText = vi . fn ( ) ;
6
+ const mockVisibilityState = vi . spyOn ( document , "visibilityState" , "get" ) ;
6
7
7
8
beforeAll ( ( ) => {
8
9
vi . stubGlobal ( "navigator" , {
@@ -125,6 +126,32 @@ it("listens to copy events", async () => {
125
126
expect ( mockReadText ) . toHaveBeenCalledTimes ( 2 ) ;
126
127
} ) ;
127
128
129
+ it ( "refreshes clipboard text when the user goes back to the tab" , async ( ) => {
130
+ mockReadText . mockResolvedValueOnce ( "hello" ) . mockResolvedValueOnce ( "world" ) ;
131
+ mockVisibilityState . mockReturnValue ( "visible" ) ;
132
+
133
+ const { result } = renderHook ( ( ) => useClipboardText ( ) ) ;
134
+ await waitFor ( ( ) => expect ( result . current . text ) . not . toEqual ( "" ) ) ;
135
+
136
+ expect ( result . current . text ) . toEqual ( "hello" ) ;
137
+ expect ( result . current . error ) . toEqual ( null ) ;
138
+ expect ( mockReadText ) . toHaveBeenCalledTimes ( 1 ) ;
139
+
140
+ mockVisibilityState . mockReturnValue ( "hidden" ) ;
141
+ await act ( async ( ) => fireEvent ( document , new Event ( "visibilitychange" ) ) ) ;
142
+
143
+ expect ( result . current . text ) . toEqual ( "hello" ) ;
144
+ expect ( result . current . error ) . toEqual ( null ) ;
145
+ expect ( mockReadText ) . toHaveBeenCalledTimes ( 1 ) ;
146
+
147
+ mockVisibilityState . mockReturnValue ( "visible" ) ;
148
+ await act ( async ( ) => fireEvent ( document , new Event ( "visibilitychange" ) ) ) ;
149
+
150
+ expect ( result . current . text ) . toEqual ( "world" ) ;
151
+ expect ( result . current . error ) . toEqual ( null ) ;
152
+ expect ( mockReadText ) . toHaveBeenCalledTimes ( 2 ) ;
153
+ } ) ;
154
+
128
155
it ( "recovers from error after any successful read" , async ( ) => {
129
156
mockReadText
130
157
. mockRejectedValueOnce ( new Error ( "error" ) )
0 commit comments