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

Guide to importing a function from a Javascript module without declaration

Currently, I am utilizing a third-party Javascript library that includes Typescript type declarations in the form of .d.ts files. Unfortunately, as is often the case, these type declarations are inaccurate. Specifically, they lack a crucial function which ...

How can I automatically select the first radio button using Angular?

I am facing an issue with displaying a dynamic list of radio buttons, where the first one always needs to be pre-selected. Initially, I used: [checked]="i === 0" Then, when I added: [(ngModel)]="item.modifType" The first radio button was no longer sele ...

Limiting the use of the Tab key within a modal dialog box

Currently, I have implemented a modal window that appears when a .btn link is clicked. However, I am facing an issue where users can still navigate through links and buttons in the background by pressing the Tab key. This becomes problematic especially fo ...

Issue with @Input causing detectChanges error in Angular 6 unit testing

A basic component is utilized to accept a configuration object as an input and utilize it to initialize certain values in the ngOnInit lifecycle hook. export class MyComponent implements OnInit { @input() config: ConfigObject; min: number; max ...

Using react-confetti to create numerous confetti effects simultaneously on a single webpage

I'm looking to showcase multiple confetti effects using the react-confetti library on a single page. However, every attempt to do so in my component seems to only display the confetti effect on the last element, rather than all of them. The canvas fo ...

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...

Waiting for completion of two observables in RxJS/Angular 11 while also managing errors

Currently, I am facing the challenge of waiting for two requests to complete (observables) and performing certain actions. Here is what I need: Wait for both requests (observables) to finish If one of them fails - show one error message If both of them f ...

When you call Subscribe(), you will receive the output "complete: () => void; 'complete' is defined in this context. What exactly does this signify?

Currently, I am following a tutorial and after meticulously checking and rechecking, I can confidently say that my code matches exactly with the one the professor is using. The tutorial involves creating a simple Single Page Application in Angular using Ty ...

Jenkins is causing the npm test to fail, whereas the test passes without any

Encountering Issue with npm test Below is the error message received: FAIL src/Tests/Workflow.test.js ● Test suite failed to run ENOENT: no such file or directory, mkdir '/tmp/jest_4df/jest-transform-cache-4e6d562894209be60da269aa86f9333c-d1 ...

Exploring the dynamic changes in user authentication state with Angular Fire subscriptions

At the moment, I have been listening to authentication state changes in my ngOnInit method of my AppComponent: export class AppComponent implements OnInit { constructor(public fireAuth: AngularFireAuth) { } ngOnInit(): void { this.fireAuth.auth ...

What is preventing the value from changing in auth.guard?

I am encountering an issue with the variable loggined, which I modify using the logTog() method. When I call this method, a request is made to a service where the current result is passed to auth.guard. However, in the console, it displays "undefined". Can ...

Setting up Webpack for react-pdf in a Next.js application

In my Next.js application, I am utilizing the react-pdf library to generate and handle PDF files on the client side without involving the server. However, I am facing challenges in setting up Webpack for Next.js as I lack sufficient expertise in this area. ...

Display embedded ng-template in Angular 6

I've got a template set up like this <ng-template #parent> <ng-template #child1> child 1 </ng-template> <ng-template #child2> child 2 </ng-template> </ng-template> Anyone know how t ...

Is it acceptable to use Angular to poll data from Laravel?

I have created a platform where users can stay updated with notifications and messages without the need to constantly refresh the page. Instead of using third-party services like Pusher, I decided to utilize polling to achieve this functionality. Essentia ...

Checking for the presence of a specific function in a file using unit testing

I am curious if there is a possible way to utilize mocha and chai in order to test for the presence of a specific piece of code, such as a function like this: myfunction(arg1) { ...... } If the code has been implemented, then the test should return t ...

Displaying ASP.Net Core Application on local IIS - Unable to locate content

I started a new project in Visual Studio Code by running the following command: dotnet new angular --use-local-db Afterwards, I upgraded Angular from version 8 to 10 and completed the project. To test it, I used dotnet watch run Everything was running ...

Different ways to separate an axios call into a distinct method with vuex and typescript

I have been working on organizing my code in Vuex actions to improve readability and efficiency. Specifically, I want to extract the axios call into its own method, but I haven't been successful so far. Below is a snippet of my code: async updateProf ...

How can props be defined in Vue3 using Typescript?

When using Vue3's defineComponent function, it requires the first generic parameter to be Props. To provide props type using Typescript interface, you can do it like this: export default defineComponent<{ initial?: number }>({ setup(props) { ...

Tips for accessing child elements within an Angular component

I'm struggling to get a reference of child elements within a component. I have experimented with ElementRef, TemplateRef, QueryList, ViewChild, ViewChildren, ContentChild, and ContentChildren without success. <app-modal> <section #referenc ...

Creating a FormGroup dynamically using an observable: A step-by-step guide

My current project involves creating a page with multiple reactive forms, tailored for different countries. These forms are generated based on JSON arrays received from the backend, allowing users to view and update settings individually. As I am uncertain ...