Exploring the Usage of Jasmine Testing for Subscribing to Observable Service in Angular's OnInit

Currently, I am facing challenges testing a component that contains a subscription within the ngOnInit method. While everything runs smoothly in the actual application environment, testing fails because the subscription object is not accessible. I have attempted to create a stub svc to generate the observable object within my unit test, but unfortunately, it has been unsuccessful.

Below is an excerpt of my Service and Component code (abrv):

Component

  ngOnInit() {
   this.userSvc.user.subscribe(user => {
    this.currentUser = user; //-- this.userSvc.user (which is an observable on that class) is available in the wild, but not when testing
   })
  }

UserService

  //-- User Subscribe items
  userSubject: BehaviorSubject<any> = new BehaviorSubject(null);
  user = this.userSubject.asObservable(); // this is the property I'm subscribing to which gets set after login.

Here is how I have set up my Test:

//SvcStub
const usrSvcStub = {
 user : {
  FirstName: "Test",
  LastName: "User",
  Username: "testuser"
 }
}

//Providers Configuration
 providers: [
    {provide: UserService, useValue: {usrSvcStub}}
   ]

During the test execution, I observe that my "StubSvc" is loaded, however, the user object is undefined and I cannot subscribe to it. I would appreciate any guidance on how to resolve this issue. The screenshot below illustrates the point at which the component's ngOnInit function is called and attempts to subscribe to the service observable.

https://i.stack.imgur.com/aMRam.png

Answer №1

Could you give this a shot?

const userFakeService = {
 user : new BehaviorSubject<any>({
  FirstName: "Tester",
  LastName: "Example",
  Username: "exampleuser"
 })
}

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

Navigating an angular collection like a pro

I have the following example data structure within a Component: const Questions = { "java": [ {text: "Is this a question?", answer: "Yes"}, {text: "Another question", answer: "Yes"} ], "python": [ {text: "A different qu ...

Unable to assign dynamic key to Vue 3 directive for object property

Currently, I am utilizing the maska npm package to mask input fields in Vuetify. Within my setup, I have an array of masks that I make use of: export const Masks = { hour: { mask: "##:##", eager: true }, host: { mask: "#00.#00.#00.# ...

Having trouble with Angular 2 not properly sending POST requests?

Having some trouble with a POST request using Angular 2 HTTP? Check out the code snippet below: import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add ...

What is the best way to save objects in the store (ngrx, ngxs) while preserving their methods functionality?

As I delve into the Redux pattern, I realize the importance of storing only plain objects in the Store. However, I find myself wanting to use more complex objects with methods like "hasParent", "isReadonly", and "isValid" in my application. While ngrx all ...

Instructions for removing a specific row from a table by clicking on the icon or button

Currently in my project, I am utilizing the Table with pagination component. My goal is to implement a feature where users can delete a single row at a time by clicking on the delete icon. To showcase what I have tried so far, I have set up a demonstration ...

Tips for arranging columns and rows in a mat-dialog box

In my Angular project, I am working on a mat dialog box and trying to achieve a layout with 1 row at the top and 3 rows at the bottom, similar to the image below. However, I am facing issues in making it work properly. Additionally, I want to hide the hori ...

Can you explain Angular's "rule of unidirectional data flow" to me?

The concept of Angular's "unidirectional data flow rule" is mentioned throughout various sections of the Angular documentation, yet a clear and concise definition of this rule is nowhere to be found. After thorough research, I discovered two somewhat ...

Enforce boundaries by constraining the marker within a specified polygon on a leaflet map

Currently, I am utilizing a leaflet map to track the user's location. The map includes a marker for the user and a polygon shape. My goal is to ensure that the user marker always stays within the boundaries of the defined polygon. In case the user mov ...

What is the recommended module to choose when importing MAT_DIALOG_DATA?

When working on my Angular project, I noticed that there are multiple options available for importing MAT_DIALOG_DATA. I have tried importing both @angular/material and @angular/material/dialog, and found that both options work successfully. However, I a ...

Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function. For example: interface employee { first: st ...

navigation trail click feature

I'm currently working on an Angular application using Chart.js to display dynamic pie charts. I want to include a breadcrumb navigation above the pie charts to show users the hierarchy of the data they are viewing. I also need to enable click functio ...

Creating unique navigation bar elements

I'm currently working on an application and facing an issue with the navigation from the Component to NavbarComponent. If you'd like to check out the application, you can visit: https://stackblitz.com/github/tsingh38/lastrada The goal is to hav ...

Building Reusable Components in Angular 2: A Step-by-Step Guide

I have implemented a feature in my component where a table can be sorted by clicking on the <th></th> tags. When a user clicks on a th tag, the data is sorted either in ascending (ASC) or descending (DESC) order. In my component, I have set up ...

Error in Node.js: Packet sequence mismatch. Received: 0, Expected: 244

For the past 10 days, I've been grappling with this issue. Despite trying everything I could find on Google, I still haven't found a suitable solution. After initiating "npm start" on the server at night, I woke up to an error in the morning. th ...

Function parameter constrained to a specific property of a generic type T

In my codebase, I have a custom function called uniqBy, which filters out duplicate items based on a specified key: export function uniqBy<T>(array: T[], key: any): T[] { const seen = {}; return array.filter(function (item) { if (item ...

Angular 2 date validation rule for dd/mm/yyyy format in forms with reactive functionality

this.seedFundForm = this.fb.group({ multipleSource: this.fb.array([]), amount:[data.amount, Validators.compose([Validators.required, Validators.pattern('[0-9]*'), Validators.maxLength(10)])], date:[data.date, Validators.compose([Valid ...

Tips on adjusting sticky behavior for responsiveness using bootstrap-4

In my project, I am utilizing angular with bootstrap. The header of the project consists of two parts and a content area. However, when the resolution is small, the header wraps. Check out the header and content on large screens View the header and conte ...

The directive is dynamically altering the disable attribute of its parent element

I am faced with a scenario where I have both a button and a directive in my template. The button can be disabled based on certain parameters defined in the template itself, as well as by the directive (it gets disabled in case of a double click event). B ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

What is the best way to save Azure Service Bus Message IDs with a package-internal type of 'Long' in MongoDB?

Currently, I am utilizing Azure Service Bus (@azure/service-bus) within a TypeScript-based nest.js service to schedule messages for delivery at a future date. In case the need arises, I must also have the ability to cancel these scheduled messages before t ...