Testing server sent events with Karma and Jasmine in Angular




Asked on February 23, 2023
I am having difficulty writing unit tests in Angular for my application that is using Angular for the frontend and Python for the backend, while utilizing server sent events (SSE) to stream data from the server to the UI. It works fine, but I am struggling to write the tests.

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 need to write unit tests for all the three scenarios.

Any leads would be a great help. Thanks in advance!





Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us