Testing server sent events with Angular solely using Karma-Jasmine

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.

Answer №1

After some investigation, I was successful in finding a resolution to the issue at hand.

The modification I made was to this specific line:

I initialized a new EventSource instance as follows: this.eventSource = new EventSource(url);

Subsequently, I utilized the eventSource's dispatchEvent method to trigger the events in the following manner:

this.eventSource.dispatchEvent(new Event('error'));

In a similar fashion, I replicated this process for two additional events and conducted thorough unit testing to ensure proper functionality and code coverage.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the empty object return from the Async function in my Typescript code on Next JS?

Encountering issues with an async function. In the ../lib folder, I have a class for handling data from an API website. However, when attempting to load the API data within an async function, I encounter difficulties. The async function does not return a ...

Do not allow nested objects to be returned

I am facing an issue with typeorm, where I have a queryBuilder set up like this: const projects = await this.conn.getRepository(UserProjectRelations).createQueryBuilder("userProject") .innerJoin("userProject.userId", ...

Update the Angular material table with the set filtered results

Currently, I have a functioning Angular Material table with search capabilities. However, I am encountering an issue. The problem lies in the fact that when I navigate from 'route A' to 'route B' and pass a value to the search box in t ...

Use Ramda to convert an array of objects into nested objects

As a beginner, please forgive me for asking what may be considered a naive question. I currently have an array of objects const arr = [{id: 1, name: 'Pete'}, {id: 5, name: 'John'}, {id: 3, name: 'Peter'}] and I am looking to ...

Creating a component in Angular that utilizes multiple nested FormGroups

When attempting to nest multiple FormGroups, everything works smoothly if the template is not extracted into separate components. For instance, the following example functions as expected: Template <form [formGroup]="baseForm"> <div formGr ...

Modified the imports within Angular Material

I recently began developing a new website using Angular 9 and Angular Material. Initially, this code snippet worked fine: import {MatSidenavModule, MatToolbarModule} from '@angular/material'; However, I encountered an error that prompted me to u ...

Verify the dimensions of the file being uploaded

I have a file uploader component that requires a dimensions validator to be added. Below is the code for the validator: export const filesDimensionValidator = (maxWidth: number, maxHeight: number): ValidatorFn => (control: AbstractControl): Vali ...

Adding the highcharts-more.src.js file to an Angular 2 project: A step-by-step guide

I have linked highcharts-more to the system variable: 'highcharts-more': 'node_modules/highcharts/highcharts-more.src.js' But I keep getting an error message saying: Error in dev/process/templates/detail.template.html:40:33 ORIGINAL ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

Firestore error: "Unable to retrieve document due to offline client" specifically happening with Cypress tests

While testing my Ionic Angular app with Firebase for logging in, I encountered the following error: "Failed to get document because the client is offline" The app runs smoothly on http://localhost:8100/ and logs in successfully when done manua ...

During the installation of Angular CLI, an error occurred indicating an unexpected ending of JSON input while parsing near the string '...gsJjnNLbV xrOnxOWiCk'

C:\Users\BB>node --version v14.15.0 C:\Users\BB>npm --version 8.3.2 npm install -g @react/react-native npm ERR! Error: Unable to find module '@react/react-native' npm ERR! A detailed log of this process can be locate ...

typescript React-Redux challenge: Boosting Your mapDispatchToProps Skills

I'm having trouble determining the type of my mapDispatchToProps function in the SignInComponent. See the code snippet below: Here is my authAction.ts file: import firebase from 'firebase/app' import { Dispatch } from 'react'; ty ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

Tips for showing a DialogBox when a blur event occurs and avoiding the re-firing of onBlur when using the DialogBox

Using React and Material UI: In the code snippet provided below, there is a table with TextFields in one of its columns. When a TextField triggers an onBlur/focusOut event, it calls the validateItem() method that sends a server request to validate the ite ...

Is there a way to specify patternProperties in a JSON schema and then map it to a TypeScript interface?

I'm in the process of developing a TypeScript interface that corresponds to a JSON schema. The specific field in my JSON schema is as follows: "styles": { "title": "Style Definitions", &qu ...

The type 'EventTarget & HTMLTextAreaElement' does not contain the property 'files'

When trying to call a method in React TypeScript on the onChange Event of a MUI Input field, an error is encountered. The error message received is: Type '(event: { target: { files: any[]; }; }) => void' is not assignable to type 'Chang ...

Discovering if the array data is already present in Angular can be accomplished by using specific methods

Here is the snippet of code: data = [ { 'id': 'asdjxv', 'username': 'emma', }, { 'id': 'asqweja', 'username': 'adam', }, { ...

Customize the datepicker locale in Valor

Currently, I am working with Angular2 and typescript alongside the Valor datepicker. Unfortunately, the datepicker does not have the necessary locale built-in. After some research, I discovered that the essential JavaScript file containing the locale infor ...

When selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...