Utilizing the Injector for Quality Testing Services

After bootstrapping my service before its dependency, I rely on the Injector to handle the dependency once it's ready.

constructor(private readonly injector: Injector) {
  const interval = setInterval(() => {
    const myService = injector.get(MyService);

    if (myService) {
      this.myService = myService;
      clearInterval(interval);
    }
  }, 200);
}

During testing, my setup is as follows:

beforeEach(() => {
  return TestBed.configureTestingModule({
    providers: [
       {
          provide: MyClass,
          useClass: MyClass,
          deps: [
            Injector,
          ]
       },
       {
         provide: MyService,
         useValue: myServiceMock
       },
     ]
  });
});

Yet, the issue arises where

TestBed.get(MyService) !== TestBed.get(MyClass).myService
.

For some reason, there are two different instances of the same. How can I ensure they are one instance?

Answer №1

Resolved through the utilization of fakeAsync. The service's use of setInterval results in eventual resolution in various instances.

The updated service assignment now appears as follows:

beforeEach(fakeAsync(() => {
  myClass = TestBed.get(MyClass);
  tick(200);
  myService = TestBed.get(MyService);
}));

In addition, a test has been developed to confirm the same instance:

expect(myService).toBe((myClass as any).myService)

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

ng2-dragula error: issues with setting options and dropping version

It seems that version 1.5.0 supports this.dragulaService.setOptions, while version 2.1.1 does not, and vice versa with this.dragulaService.drop subscribe where version 2.1.1 supports it but 1.5.0 does not. Check out the Stackblitz Fork for version 1.5.0 ...

I am having trouble getting my angular image to switch using angular animations

I am attempting to implement image swapping using Angular animations based on a 10-second timer. However, the swap is not occurring and I have been troubleshooting without success. The goal is for the images to change when the timer reaches 5 seconds, but ...

"An error occurred while trying to resolve "npm" from npm.fontawesome.com

Within my Angular project, I am utilizing a module from When I run the following command: npm --loglevel info install grun locally, it finishes without any issues. However, when I run this command on the build server, an error occurs. In my .npmrc file: ...

When incorporating Papaparse with Angular 2, encountering the issue "Identifier 'Papa' is not found" may arise

Currently, I am facing an issue in my project where after deleting and re-installing node_modules to resolve errors, the definition of 'Papa' is missing. As a result, when npm updated the node modules again, Angular 2 is unable to find 'Papa ...

Upon initializing an Angular project from the ground up, I encountered an issue where a custom pipe I had created was not

After creating an Angular 16.1.0 application and a custom pipe, I encountered error messages during compilation. Here are the steps I took: Ran ng new exampleProject Generated a pipe using ng generate pipe power Modified the content of app.compone ...

Is it necessary for me to develop an Angular library in order to release a basic TypeScript class that makes use of Angular components?

In one of my Angular projects, I have a Typescript class called APIResponse that I want to convert into an NPM package for use in other projects. This class is not specific to Angular like a Service or Component. After doing some research on creating non-A ...

Verify role declarations and display components if valid

I am currently developing an application using Angular on the front-end and ASP.NET on the back-end. Within this application, there are two roles: user and admin. I have implemented a navigation bar with several buttons that I need to hide based on the use ...

Including the --aot flag in the Angular CLI can cause issues with the app

Recently, I encountered an issue with my Angular app while using dynamic forms. Everything was working fine until I added the --aot flag to my CLI command. Suddenly, I started receiving the error message "Property 'controls' does not exist on typ ...

Angular2 - Breaking down applications into reusable components

Utilizing custom properties permits seamless data binding between multiple components. <section id="main"> <app-home [dict]="dict">Hello there!</app-home> </section> In this scenario, dict serves ...

I am having trouble getting my angular library published successfully

I'm facing an issue while trying to publish my angular package. I keep encountering this error. https://i.stack.imgur.com/nhYMY.png Here is a screenshot of my package.json file https://i.stack.imgur.com/mWsin.png. ...

Learn how to connect a formArray from the parent component to the child component in Angular with reactive forms, allowing you to easily modify the values within the formArray

In my parent component, there is a reactive form with controls and a form group. When the user selects a playerType from a dropdown menu, I dynamically add a formArray to the formGroup. This form array will contain either 2 or 3 form groups based on the p ...

Modifying a Component's Value in its Template Based on an IF Condition in Angular 6

How can I display or hide the 'separator-container' based on a specific condition in the row data? The condition to satisfy is mentioned as "myConditionCheck" in the 5th line of code. I attempted to achieve this by using "isWarningSeperatorVisib ...

Updating a label dynamically in Angular

QUESTION: Is there a way to dynamically change the text of a label based on a certain condition? Specifically, I want the label to be blank when I'm on a specific route in my App. CURRENT APPROACH: <RadSideDrawer allowEdgeSwipe=&quo ...

Converting JSON data into an array of a particular type in Angular

My current challenge involves converting JSON data into an array of Recipe objects. Here is the response retrieved from the API: { "criteria": { "requirePictures": true, "q": null, "allowedIngredient": null, "excluded ...

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...

What is the best approach to incorporate a stopwatch?

I'm exploring ways to track the time it takes for a user to click a button. While I have a working solution, I'm curious if there's a more efficient method available. Below is my current implementation: export class MainComponent implements ...

Tips for checking dropzone functionality during development

I'm currently working on an Angular 5 application and incorporating dropzonejs (the angular wrapper) into it. However, as I am not the backend developer, I do not have full visibility into how the backend has been developed. Currently, CORS is being ...

What is the proper way to manage the refresh token on the client's end within a JWT system?

Curious about what exactly occurs on the client side when the refresh token expires. Is the user directed to a login page and remains logged in, or does the client side log them out automatically? My understanding is that the refresh token is saved in an ...

mat-table dataSource is not functioning properly with REST API integration

I'm facing an issue while trying to populate a Material Table with data. My model Block has fields such as id, date, etc. The API call is made in data.service and the function getAllBlock() fetches the blocks. I tested this in the app.component.html ...

I'm having trouble getting my Ionic Angular App to start up properly. When I try to launch it, it just gets stuck on the splash screen and displays an error message saying "ReferenceError

The challenge I am facing involves developing an IOS app using ionic v7 and angular v15.2. While the app functions smoothly in the browser, upon deployment to my iPhone (iphone 13 pro, running IOS 15.6), I encounter a perplexing error message within XCode: ...