I am currently developing a web application using Angular for the frontend and Python for the backend. My implementation involves utilizing server-sent events (SSE) to stream data from the server to the user interface. While everything is functioning properly, I have encountered difficulty in writing unit tests specifically for this functionality in Angular.
abc.component.ts
streamMessages() {
this.isPaused = false;
this.messages = [];
const url = this.urlConfig.stream;
var eventSource = new EventSource(url);
eventSource.addEventListener('message', (e) => {
this.messages.push(e.data);
});
eventSource.addEventListener('error', (e) => {
eventSource.close();
console.log('ERROR!');
this.isPaused = true;
});
eventSource.addEventListener('close', () => {
eventSource.close();
console.log('CLOSED!');
});
}
abc.component.spec.ts
describe('#streamMessages', () => {
let mockEventSource: jasmine.SpyObj<EventSource>;
beforeEach(() => {
mockEventSource = jasmine.createSpyObj('EventSource', ['addEventListener']);
});
it('should push new message when new message is received', () => {
mockEventSource.addEventListener.and.callFake((type: string, event: any) => {
console.log(type, event)
});
component.streamMessages();
expect(component.messages.length).toBeGreaterThan(0);
});
});
I am seeking guidance on how to write unit tests for all three scenarios mentioned above. Any assistance or suggestions would be greatly appreciated. Thank you in advance!
P.S: I am looking to accomplish this task solely with the help of Karma-Jasmine and do not wish to use test bed.