@@ -3,7 +3,9 @@ import { useUserState } from '../src/helper';
33
44describe ( 'useUserState Hook' , ( ) => {
55 const mockCC = {
6- setAgentState : jest . fn ( )
6+ setAgentState : jest . fn ( ) ,
7+ on : jest . fn ( ) ,
8+ off : jest . fn ( ) ,
79 } ;
810
911 const idleCodes = [
@@ -16,6 +18,8 @@ describe('useUserState Hook', () => {
1618 beforeEach ( ( ) => {
1719 jest . useFakeTimers ( ) ;
1820 mockCC . setAgentState . mockReset ( ) ;
21+ mockCC . on . mockReset ( ) ;
22+ mockCC . off . mockReset ( ) ;
1923 } ) ;
2024
2125 afterEach ( ( ) => {
@@ -31,6 +35,9 @@ describe('useUserState Hook', () => {
3135 elapsedTime : 0 ,
3236 currentState : { }
3337 } ) ;
38+
39+ expect ( mockCC . on ) . toHaveBeenCalledTimes ( 1 ) ;
40+ expect ( mockCC . on ) . toHaveBeenCalledWith ( 'agent:stateChange' , expect . any ( Function ) ) ;
3441 } ) ;
3542
3643 it ( 'should increment elapsedTime every second' , ( ) => {
@@ -93,4 +100,57 @@ describe('useUserState Hook', () => {
93100 } ) ;
94101 } ) ;
95102 } ) ;
103+
104+ it ( 'should handle agent state change events correctly' , async ( ) => {
105+ const { result } = renderHook ( ( ) => useUserState ( { idleCodes, agentId, cc : mockCC } ) ) ;
106+
107+ // Get the handler function that was registered
108+ const handler = mockCC . on . mock . calls [ 0 ] [ 1 ] ;
109+
110+ // Test with right event type
111+ act ( ( ) => {
112+ handler ( { type : 'AgentStateChangeSuccess' , auxCodeId : '123' } ) ;
113+ } ) ;
114+
115+ await waitFor ( ( ) => {
116+ expect ( result . current . currentState ) . toEqual ( { id : '123' } ) ;
117+ } ) ;
118+
119+ // Test with wrong event type
120+ act ( ( ) => {
121+ handler ( { type : 'WrongType' } ) ;
122+ } ) ;
123+
124+ await waitFor ( ( ) => {
125+ expect ( result . current . currentState ) . toEqual ( { id : '123' } ) ;
126+ } ) ;
127+
128+ // Test again with right event type but different value
129+ act ( ( ) => {
130+ handler ( { type : 'AgentStateChangeSuccess' , auxCodeId : '1213' } ) ;
131+ } ) ;
132+
133+ await waitFor ( ( ) => {
134+ expect ( result . current . currentState ) . toEqual ( { id : '1213' } ) ;
135+ } ) ;
136+
137+ // Test with empty auxCodeId
138+ act ( ( ) => {
139+ handler ( { type : 'AgentStateChangeSuccess' , auxCodeId : '' } ) ;
140+ } ) ;
141+
142+ await waitFor ( ( ) => {
143+ expect ( result . current . currentState ) . toEqual ( { id : '0' } ) ;
144+ } ) ;
145+ } ) ;
146+
147+ it ( 'should cleanup event listener on unmount' , ( ) => {
148+ const { unmount } = renderHook ( ( ) => useUserState ( { idleCodes, agentId, cc : mockCC } ) ) ;
149+
150+ unmount ( ) ;
151+
152+ // Verify that off was called with the same event and handler
153+ expect ( mockCC . off ) . toHaveBeenCalledTimes ( 1 ) ;
154+ expect ( mockCC . off ) . toHaveBeenCalledWith ( 'agent:stateChange' , expect . any ( Function ) ) ;
155+ } ) ;
96156} ) ;
0 commit comments