Angular TypeScript subscription unit testing

Here is a code snippet for a Helper class:

export class Helper {
  static unsubscribeSubscriptions(subscriptions: Subscription[]): void {
    subscriptions.forEach(subscription => {
      if (subscription) {
        subscription.unsubscribe();
      }
    });
  }

  static isNullOrEmpty(value: string): boolean {
    return (!value || value === undefined || value === '' || value.length === 0);
  }
}

I have successfully tested the isNullOrEmpty method, but I am unsure how to test the unsubscribeSubscriptions method. Here is my current testing setup:

describe('Helper', () => {
  it('isNullOrEmpty should return true', () => {
    // WHEN
    const value = '';
    const res = Helper.isNullOrEmpty(value);
    // THEN
    expect(res).toBeTruthy();
  });

  it('isNullOrEmpty should return false', () => {
     // WHEN
     const value = 'FULL';
     const res = Helper.isNullOrEmpty(value);
     // THEN
     expect(res).toBeFalsy();
  });
}); 

If anyone has any suggestions on how to test the unsubscribeSubscriptions method, please let me know.

Answer №1

Utilize the jasmine.createSpyObj() function to generate simulated subscriptions and provide them as parameters to the unsubscribeSubscriptions() function. Verify if the unsubscribe method has been invoked on these mock subscriptions.

For example:

helper.ts:

import { Subscription } from 'rxjs';

export class Helper {
  static unsubscribeSubscriptions(subscriptions: Subscription[]): void {
    subscriptions.forEach((subscription) => {
      if (subscription) {
        subscription.unsubscribe();
      }
    });
  }

  static isNullOrEmpty(value: string): boolean {
    return !value || value === undefined || value === '' || value.length === 0;
  }
}

helper.test.ts:

import { Helper } from './helper';

fdescribe('Helper', () => {
  describe('isNullOrEmpty', () => {
    it('should return true', () => {
      const value = '';
      const res = Helper.isNullOrEmpty(value);
      expect(res).toBeTruthy();
    });

    it('should return false', () => {
      const value = 'FULL';
      const res = Helper.isNullOrEmpty(value);
      expect(res).toBeFalsy();
    });
  });

  describe('unsubscribeSubscriptions', () => {
    it('should unsubscribe all subscriptions', () => {
      const sub1 = jasmine.createSpyObj('sub1', ['unsubscribe']);
      const sub2 = jasmine.createSpyObj('sub1', ['unsubscribe']);
      const subscriptions = [sub1, sub2];
      Helper.unsubscribeSubscriptions(subscriptions);
      expect(sub1.unsubscribe).toHaveBeenCalled();
      expect(sub2.unsubscribe).toHaveBeenCalled();
    });
  });
});

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

Creating dynamic checkboxes in Angular4 and binding them to an array of IDs

Hey there developers, I've been encountering an issue while trying to bind my dynamically generated checkboxes to an array in my project. In my users.template.html file, I have the following code snippet: <div *ngFor="let r of roles" class="checkb ...

Using js/jsx files in a TypeScript + Webpack project: A beginner's guide

I encountered an issue while trying to import and utilize a regular .jsx file within my typescript project that is built with webpack. The error message I received reads: ERROR in ./src/components/App/Test.jsx 72:4 Module parse failed: Unexpected token (72 ...

Determining the Right Version of a Framework in npm: A Guide

One common issue I encounter is the uncertainty of which versions of npm, Ionic, and other tools I should have installed. It often goes like this: "Oh, there's a new version of the Ionic CLI out. Let's update." I install CLI v3.9.0. ...

Issues are arising with Angular Form where the FormControl is not being properly set up for the first field in my form

After grappling with this issue for several weeks, I am still unable to pinpoint the cause. (Angular version: 16.1.4) The form component is populated using a BehaviorSubject, and although the console prints out the correct values for both the form and dat ...

Making Angular table cells interactive with clicks

My table consists of multiple rows, and I want to change the color of a cell to red when clicked. However, only one cell should be red at a time. Whenever I click on a new cell, the previously red cell should return to its original color. How can I achieve ...

Is it possible to configure Angular 6 without relying on node.js/npm?

Is there a way to set up and run an Angular application without relying on the Angular CLI or needing Node.js and npm commands in the terminal? I would greatly appreciate any suggestions regarding this matter. ...

Tips for positioning the border properly within a scrollable table

My table has a sticky header with a fixed height, and in order to see more rows in the table, we have to scroll through them. The table design includes borders. The problem arises when there are more rows, as the border moves with the scroll. Initially, ...

What is the recommended data type to assign to the `CardElement` when using the `@stripe/react-stripe-js` package in TypeScript?

I'm struggling to determine the correct type to use for this import: import { CardElement } from '@stripe/react-stripe-js'; I have successfully used the types Stripe, StripeElements, and CreateTokenCardData for the stripe and elements props ...

Issue with accessing jQuery in index.html through webpack

I am currently using the angular 2 class seed with webpack for my project. Although I have successfully implemented jQuery in my application (being able to use $ after loading), I am encountering an issue when trying to utilize jQuery in index.html, resu ...

Having trouble setting up Nuxt with Typescript integration

I am venturing into the world of Typescript with Nuxt (version 2.6.1) for the first time. After creating a new project using create-nuxt-app, I followed the official guide for Typescript Support. npx create-nuxt-app my-first-app cd my-first-app npm instal ...

Failed deployment of a Node.js and Express app with TypeScript on Vercel due to errors

I'm having trouble deploying a Nodejs, Express.js with Typescript app on Vercel. Every time I try, I get an error message saying "404: NOT_FOUND". My index.ts file is located inside my src folder. Can anyone guide me on the correct way to deploy this? ...

Mapping Firestore documents to an array using AngularFire - A step-by-step guide to using valueChanges

In my Angular web application, I'm utilizing the AngularFire library to interact with Firestore database. Within the constructor of a component, I want to subscribe to a collection of documents and map these documents to an array whenever the value c ...

Utilizing PrimeNg with Angular 2 to dynamically update charts using @ViewChild

I'm currently utilizing Angular2 with PrimeNG for my application. My dashboard includes charts and after attempting to upgrade to PrimeNG rc7 (from rc5) where they addressed an issue with updating charts, I'm facing challenges updating my chart d ...

Passing a Typescript object as a parameter in a function call

modifications: { babelSetup?: TransformationModifier<babel.Configuration>, } = {} While examining some code in a React project, I came across the above snippet that is passed as an argument to a function. As far as I can tell, the modifications p ...

Best Javascript framework for ASP.NET MVC incorporating razor

Struggling to find the perfect JavaScript framework for ASP .NET MVC and razor? I decided to try out Angular 2, Aurelia, and AngularJS in a demo application. My experience shows that while Angular 2 and Aurelia can integrate with MVC and razor, they are ...

Examining numpy floating point arrays in test scenarios

Can anyone suggest the optimal method for performing a unittest that compares two numpy float arrays? I attempted to use unittest.assertEqual(), but it failed since floats are never completely equal. Using assertAlmostEqual is not an option either because ...

A guide to declaring functions based on certain conditions

I am looking to assign a function that is the result of a ternary operator, which in turn calls one of two functions. The code snippet I have written so far is as follows: const action1 = (x: number) => { // do something ...

Assign a value to a date field in Aurelia

<input class="" type="date" id="Broken" value.bind="dateval"> The current value of dateval is 2021-04-08T10:05:19.988Z. Is there a way to set a default date for the date input field above? ...

Deploying Angular and Spring Boot together as a WAR file

I am currently working on two projects, one being an Angular Project (Front End Application) and the other a Spring Boot (Rest Api's). My goal is to generate a single runnable war/jar file that contains both of these projects. After running the "java ...

What is the reason behind the smaller bundle size of Angular2 CLI with "--prod" compared to "--prod --aot"?

Using the latest angular-cli (beta-18) for my project has brought an interesting observation to light. Despite being in its early stages, I am puzzled by the fact that my final bundle size is actually smaller without ahead-of-time (AoT) compilation. Upon ...