11import { describe , expect , it , vi } from 'vitest'
2- import { EventClient } from '../src'
32import { ClientEventBus } from '@tanstack/devtools-event-bus/client'
3+ import { EventClient } from '../src'
44
55// start the client bus for testing
6- new ClientEventBus ( ) . start ( )
6+ const bus = new ClientEventBus ( )
7+ bus . start ( )
78// client bus uses window to dispatch events
89const clientBusEmitTarget = window
9-
1010describe ( 'EventClient' , ( ) => {
1111 describe ( 'debug config' , ( ) => {
1212 it ( 'should emit logs when debug set to true and have the correct plugin name' , ( ) => {
@@ -35,7 +35,19 @@ describe('EventClient', () => {
3535 describe ( 'getGlobalTarget' , ( ) => {
3636 it ( 'if the global target is set it should re-use it for emitting/listening/removing of events' , ( ) => {
3737 const target = new EventTarget ( )
38- globalThis . __TANSTACK_EVENT_TARGET__ = target
38+ const handleSuccessConnection = vi . fn ( )
39+ target . addEventListener ( 'tanstack-connect' , ( ) => {
40+ target . dispatchEvent ( new CustomEvent ( 'tanstack-connect-success' ) )
41+ } )
42+ globalThis . __TANSTACK_EVENT_TARGET__ = null
43+
44+ vi . spyOn (
45+ globalThis ,
46+ '__TANSTACK_EVENT_TARGET__' ,
47+ 'get' ,
48+ ) . mockImplementation ( ( ) => {
49+ return target
50+ } )
3951 const client = new EventClient ( {
4052 debug : false ,
4153 pluginId : 'test' ,
@@ -55,9 +67,9 @@ describe('EventClient', () => {
5567 expect . any ( String ) ,
5668 expect . any ( Function ) ,
5769 )
58- globalThis . __TANSTACK_EVENT_TARGET__ = null
70+ vi . resetAllMocks ( )
71+ target . removeEventListener ( 'tanstack-connect' , handleSuccessConnection )
5972 } )
60-
6173 it ( 'should use the window object if the globalTarget is not set for emitting/listening/removing of events' , ( ) => {
6274 const target = window
6375 const client = new EventClient ( {
@@ -183,6 +195,27 @@ describe('EventClient', () => {
183195 } )
184196 } )
185197
198+ describe ( 'queued events' , ( ) => {
199+ it ( 'emits queued events when connected to the event bus' , async ( ) => {
200+ bus . stop ( )
201+ const client = new EventClient ( {
202+ debug : false ,
203+ pluginId : 'test' ,
204+ } )
205+ const eventHandler = vi . fn ( )
206+ client . on ( 'event' , eventHandler )
207+ client . emit ( 'event' , { foo : 'bar' } )
208+
209+ bus . start ( )
210+ // wait to connect to the bus
211+ await new Promise ( ( resolve ) => setTimeout ( resolve , 500 ) )
212+ expect ( eventHandler ) . toHaveBeenCalledWith ( {
213+ type : 'test:event' ,
214+ payload : { foo : 'bar' } ,
215+ pluginId : 'test' ,
216+ } )
217+ } )
218+ } )
186219 describe ( 'onAllPluginEvents' , ( ) => {
187220 it ( 'should listen to all events that come from the plugin' , ( ) => {
188221 const client = new EventClient ( {
0 commit comments