11import { ChatComponent } from './chat-page.component' ;
2- import { ComponentFixture , TestBed } from '@angular/core/testing' ;
2+ import { ComponentFixture , fakeAsync , TestBed , tick } from '@angular/core/testing' ;
33import { HttpClientTestingModule , HttpTestingController } from '@angular/common/http/testing' ;
44import { NgClass , NgForOf , NgIf , NgStyle } from '@angular/common' ;
55import { FormsModule } from '@angular/forms' ;
@@ -12,6 +12,7 @@ describe('ChatComponent', () => {
1212 let component : ChatComponent ;
1313 let fixture : ComponentFixture < ChatComponent > ;
1414 let httpMock : HttpTestingController ;
15+ let historyMock : jasmine . Spy ;
1516
1617 beforeEach ( async ( ) => {
1718 const setup = await setupChatComponentTest ( ) ;
@@ -20,6 +21,7 @@ describe('ChatComponent', () => {
2021 httpMock = setup . httpMock ;
2122
2223 localStorage . setItem ( 'accessToken' , 'mock-token' ) ;
24+ historyMock = spyOnProperty ( history , 'state' , 'get' ) . and . returnValue ( { selectedChatId : 123 } ) ;
2325 } ) ;
2426
2527 afterEach ( ( ) => {
@@ -31,6 +33,49 @@ describe('ChatComponent', () => {
3133 expect ( component ) . toBeTruthy ( ) ;
3234 } ) ;
3335
36+ it ( 'should set selectedChatId if chatId is in history state' , ( ) => {
37+ historyMock . and . returnValue ( { selectedChatId : 123 } ) ;
38+ component . ngOnInit ( ) ;
39+ expect ( component . selectedChatId ) . toEqual ( 123 ) ;
40+ } ) ;
41+ it ( 'should not set selectedChatId if no chatId is in history state' , ( ) => {
42+ historyMock . and . returnValue ( { selectedChatId : undefined } ) ;
43+ component . ngOnInit ( ) ;
44+ expect ( component . selectedChatId ) . toEqual ( undefined ) ;
45+ } ) ;
46+ it ( 'should call selectChat method if selectedChatId was provided' , fakeAsync ( ( ) => {
47+ const selectChatSpy = spyOn ( component , 'selectChat' ) . and . callThrough ( ) ;
48+ component . selectedChatId = 123 ;
49+ spyOn ( component [ 'http' ] , 'get' ) . and . returnValue (
50+ of ( {
51+ page : [
52+ {
53+ id : 123 ,
54+ username : '61' ,
55+ chatId : '123' ,
56+ lastMessage : { text : 'test' , sendAt : '2025-07-29T10:00:00Z' }
57+ }
58+ ]
59+ } )
60+ ) ;
61+
62+ component . loadAllChats ( ) ;
63+ tick ( ) ;
64+
65+ expect ( component . selectedChatId ) . toEqual ( 123 ) ;
66+ expect ( selectChatSpy ) . toHaveBeenCalled ( ) ;
67+ expect ( selectChatSpy ) . toHaveBeenCalledWith ( jasmine . objectContaining ( { chatInternalId : 123 } ) ) ;
68+ } ) ) ;
69+
70+ it ( 'should not call selectChat method if selectedChatId was not provided' , ( ) => {
71+ const selectChatSpy = spyOn ( component , 'selectChat' ) ;
72+
73+ component . loadAllChats ( ) ;
74+
75+ expect ( component . selectedChatId ) . toEqual ( undefined ) ;
76+ expect ( selectChatSpy ) . not . toHaveBeenCalled ( ) ;
77+ } ) ;
78+
3479 it ( 'should not send message if newMessage is blank or no chat' , ( ) => {
3580 spyOn ( component [ 'http' ] , 'post' ) ;
3681 component . newMessage = ' ' ;
0 commit comments