InjectableToken missing in Angular Standalone Component - Provider Not Found

In my standalone component, I am using an Injection Token to set a path (the paths are not the same for all micro-frontends). However, I do not provide this token in the component itself because I need to override it using providers in my app-module.ts.

Here is the constructor of my component:

constructor(
    @Inject(ICON_SVG_PATH) public iconSvgPath: string,
    private readonly renderer: Renderer2
  ) {}

When using the component, I can simply import it and provide the token in the providers. For example, this is how I do it in storybook:

imports: [IconComponent],
providers: [
   {
       provide: ICON_SVG_PATH,
       useValue: '/assets/icons',
   },
],

The issue arises when trying to write tests for this component in my spec.ts file, resulting in the following error:

NullInjectorError: R3InjectorError(Standalone[IconComponent])[InjectionToken ICON_SVG_PATH -> InjectionToken ICON_SVG_PATH -> InjectionToken ICON_SVG_PATH]: NullInjectorError: No provider for InjectionToken ICON_SVG_PATH! error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'InjectionToken ICON_SVG_PATH', 'InjectionToken ICON_SVG_PATH', 'InjectionToken ICON_SVG_PATH' ] })

Initially, I attempted to provide the Token similar to its usage:

await TestBed.configureTestingModule({
      imports: [IconComponent],
      providers: [
        {
          provide: ICON_SVG_PATH,
          useValue: '/assets/icons',
        },
      ],
    })
      .overrideComponent(IconComponent, {
        set: { changeDetection: ChangeDetectionStrategy.Default },
      })
      .compileComponents();

However, I encountered the same error.

I also tried providing it like this:

TestBed.overrideProvider(MY_INJECTION_TOKEN, { useValue: {} });

Yet, the outcome was unchanged.

Lastly, I attempted to provide it from the test.ts file with no success.

getTestBed().initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting([
        {
            provide: MY_INJECTION_TOKEN,
            useValue: {},
        },
    ])
);

Thank you.

Answer №1

Have you ensured that your configuration is placed inside the beforeEach function?

beforeEach(waitForAsync(() => {
   TestBed.configureTestingModule({
      imports: [IconComponent],
      providers: [
        {
          provide: ICON_SVG_PATH,
          useValue: '/assets/icons',
        },
      ],
    })
      .overrideComponent(IconComponent, {
        set: { changeDetection: ChangeDetectionStrategy.Default },
      })
      .compileComponents();
  }));

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

Error in Typescript for callback function: The type 'Function' does not match any signature

I am encountering an error stating that Type 'Function' does not match the signature for the filter function below. This is because the filter function expects a specific type. How can I define my callback function to align with what the filter f ...

Retrieve the file from the REST API without using the window.open method

I'm looking for a method to download files from an API without using window.open(). I want the download process to start immediately upon calling the API. Currently, I am downloading an .xls file generated by a REST API using window.open() API Endpo ...

Form submission resulting in 405 error

Currently, I am facing an issue while trying to send data to the server. The PHP side seems to be functioning correctly as the post request is successful when tested using Postman. However, when attempting to do so from Angular, I encounter a 405 (Method N ...

Using multiple flatMap responses within the map operator across various functions: a guide

I've been working on a solution to connect multiple operations within a map function that follows the flatMap operator. Here's how it currently functions: flatMap( someResponse => combineLatest([ this.locator.function(someResponse, var ...

How can you consistently emphasize data points in a line chart using NGRX?

I'm currently working with a line chart that displays line series. Is there any way to ensure all data points are highlighted at all times? Right now, the only time a data point is highlighted is when the mouse hovers over it. <ngx-charts-line ...

Issue: NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper]:

While I am going through a tutorial on the abp framework, I encountered an error with the Author route that says "ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelp ...

What is the procedure for setting up the typings folder in AngularJS 1.5 with TypeScript?

I'm currently working on a project using AngularJS 1.5 and TypeScript. I need to install the "angularjs/angular.d.ts" and "angularjs/angular-route.d.ts" files. Despite installing tsd globally, when I run the command "tsd install angular," I receive a ...

Deleting a specific row from a material table mat-table

Can anyone provide guidance on how to remove a selected row in mat-table using Angular? Please refer to the Stackblitz link provided below. https://stackblitz.com/edit/angular-qzh8g4?file=app/table-basic-example.ts I attempted to implement a solution, but ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

Confirm the object received from the API and assign default values

Seeking to extract data from an API and verify if all fields are strings, but if they are missing I aim to assign default values. My intention was to utilize the yup library to validate the object accordingly, ensuring that the returned function is prope ...

A script object must only permit one property at a time

I am unfamiliar with TypeScript and I have an object named obj with 3 properties: a, b, c. However, it is important to note that b and c cannot exist together in the same object. So, my object will either be: obj = { a: 'xxx', b: 'x ...

Implementing TypeScript with react-router-dom v6 and using withRouter for class components

Trying to migrate my TypeScript React app to use react-router-dom version v6, but facing challenges. The official react-router-dom documentation mentions: When upgrading to v5.1, it's advised to replace all instances of withRouter with hooks. Howe ...

Bring in jspm libraries to your project via typescript

While researching how to import jspm packages into typescript, I noticed that most examples assumed the use of SystemJS for loading and interpreting them in the browser. However, I prefer using tsc to compile commonjs modules and only import the js code, a ...

angular index.html code displayed

I successfully deployed an Angular app on a server in the past without any issues. The Angular version is 6.1.1, Angular CLI version is 6.2.9, npm version is 6.13.4, and node version is 10.18.0 for both local and server environments. The server is running ...

How can one effectively monitor the progress of multiple ajax requests in Angular8 for optimal professionalism?

There is a single completed variable made up of 6 parts, outlined below: selectedCandidateData: Candidate = { candidateBasic: null, experienceList: null, educationList: null, certificationList: null, candidateAbout: null, }; Each part ...

Exploring the use of index signatures in TypeScript when working with React

I'm struggling to properly implement the index signature in this code. I have an enum and I need to loop through it to display some JSX on the screen. I understand the error message, but I'm having trouble resolving it in my code. The issue seems ...

Using a callback function with a function outside the scope in Angular 6

I am currently utilizing DevExtreme components, and here is where the callback function is invoked within the HTML: <dxi-validation-rule type="custom" [validationCallback]="validationCallback" message="Email exists"> </dxi-validation-ru ...

What is the best way to seamlessly update a Redux state array in an immutable manner using Typescript?

I'm embarking on a journey to grasp Typescript through the creation of a simple Todo-List application. However, I've hit a roadblock in updating the Redux state array within a slice that I've established (or rather, I'm unsure how to go ...

The child element is triggering an output event that is in turn activating a method within the parent

I am currently utilizing @Output in the child component to invoke a specific method in the parent component. However, I am encountering an issue where clicking on (click)="viewPromotionDetails('Learn more')" in the child component is al ...

Tips for submitting a request following a change in the variable

I am in the process of developing a React application and I have implemented Auth0 for authentication. My goal is to initiate an HTTP request upon page refresh, but only if the variable isLoading is false. This way, I can access the user object once the ...