Angular 5 - Jasmine Tests explained: Encounter with the puzzling error message: "Error: Provider for the NgModule 'DynamicTestModule' is invalid, as only instances of Provider and Type are permitted"

I'm having trouble running tests on a component class.

Here's the error message from the stack:

Error: Invalid provider for the NgModule 'DynamicTestModule' - only instances of Provider and Type are allowed, got: [AlertModaldataComponent, [object Object], [object Object], ?[object Object]?, ...] in http://localhost:9878/_karma_webpack_/main.bundle.js (line 94300)
_reportError@http://localhost:9878/_karma_webpack_/main.bundle.js:94300:24
http://localhost:9878/_karma_webpack_/main.bundle.js:94095:39
forEach@[native code]
_getProvidersMetadata@http://localhost:9878/_karma_webpack_/main.bundle.js:94063:26

This is my component class:

import { Component, OnInit, ViewChildren, QueryList, OnDestroy } from '@angular/core';
    import { MatMenuTrigger } from '@angular/material';
    import { Router } from '@angular/router';
    import { RefreshOnActionService } from './../../../services/refresh-on-action.service';
    import { AlertModaldataComponent } from './../../common/modal/alert-modaldata.component';
    import { RefreshEntityEnum } from './../../../shared/models/refresh-entity-enum';
    import { RefreshService } from './../../../services/refresh.service';
    import { AppService } from '../../../services/app.service';
    import { setInterval, clearInterval } from 'timers';
    import { StatusRefreshEnum } from '../../../shared/models/status-refresh-enum';

    @Component({
      selector: 'app-header',
      templateUrl: './header.component.html',
      styleUrls: ['./header.component.scss']
    })
    export class HeaderComponent implements OnInit, OnDestroy {
      loggedUserId;
      showHeader = true;
      isLoading: boolean;
      isAdmin = false;
      menuItens: Array<any> = [];
      refreshId: number;
      balloon = false;
      balloonItens = 0;
      second = '00';
      minute = '00';
      hour = '00';
      timerZeroed = true;
      updatingList = false;
      getItemsQuantityInterval: any;
      private timer: any = null;

      constructor(
        private appService: AppService,
        private refreshService: RefreshService,
        private modal: AlertModaldataComponent,
        private router: Router,
        private refreshOnActionService: RefreshOnActionService
      ) {
        ...
      }

      @ViewChildren(MatMenuTrigger) trigger: QueryList<MatMenuTrigger>;

      ngOnInit() {
        ...
      }

      ngOnDestroy() {
        ...
      }

      refreshMenuItems(): void {
        ...
      }

      refreshBalloonInfo() { 
        ...
      }

      startTimer(): void {
        ...
      }

      activateSetTimeIntervalForItemsQuantity() {
        ...
      }

      openMatMenu() {
        ...
      }

      closeMatMenu() {
        ...
      }

      itemView(itemKey: any, type: RefreshEntityEnum, status: StatusRefreshEnum) {
        ...
      }

      timing(timestamp: number) {
        ...
      }

      aprove() {
        ...
      }
    }

And this is my spec class...

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { Router } from '@angular/router';

import { RefreshOnActionService } from './../../../services/refresh-on-action.service';
import { RefreshService } from './../../../services/refresh.service';
import { CommonOsgComponentsModule } from './../../common/common-osg-components.module';
import AppServiceStub from '../../../shared/testStubs/app-stub.service';
import RefreshServiceStub from '../../../shared/testStubs/refreshService-stub';
import { AppService } from '../../../services/app.service';
import { setCssTransformAsValidForPhantomBrowser } from '../../../shared/helpers';
import { HeaderComponent } from './header.component';
import { AngularMaterialModule } from '../../../angular-material/angular-material.module';
import RouterStub from '../../../shared/testStubs/router-stub';
import { RefreshEntityEnum } from '../../../shared/models/refresh-entity-enum';
import { StatusRefreshEnum } from '../../../shared/models/status-refresh-enum';
import { AlertModaldataComponent } from '../../common/modal/alert-modaldata.component';

fdescribe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(() => {
    setCssTransformAsValidForPhantomBrowser();
    TestBed.configureTestingModule({
      imports: [
        NoopAnimationsModule,
        AngularMaterialModule,
        CommonOsgComponentsModule
      ],
      declarations: [
        HeaderComponent
      ],
      providers: [
        AlertModaldataComponent,
        {
          provide: AppService,
          useClass: AppServiceStub
        },
        {
          provide: Router,
          useClass: RouterStub
        },
        {
          provider: RefreshService,
          useClass: RefreshServiceStub
        },
        {
          provide: RefreshOnActionService,
          useClass: RefreshOnActionService
        }
      ]
    });

    fixture = TestBed.createComponent(HeaderComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    const appService: AppService = TestBed.get(AppService);
    appService['_userData'] = 'x195363';
    expect(component).toBeTruthy();

  });

});

Every time I run the tests, this error occurs consistently. I have tried to locate the 'DynamicTestModule' in my project but it doesn't seem to exist. I'm unsure how to debug or resolve this issue. Can someone please assist me?

Answer №1

In my personal experience, I encountered a situation where resolving the issue involved deleting the file and subsequently creating a new file with identical content. Surprisingly, this resolved all problems that were previously occurring. I cannot pinpoint the exact cause of the issue but my speculation is that certain bits of information may have become corrupted within the original file.

Answer №2

benefit from

suggest: UtilizeService,
actualClass: UtilizeServiceStub

In lieu of

sponsor: UtilizeService,
actualClass: UtilizeServiceStub

Answer №3

Just recently, I encountered a similar error with one of my components that relies on route data for its initialization process. Thankfully, the problem was resolved by simply including RouterTestingModule in the configureTestingModule within the corresponding .spec file.

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CustomComponent],
      imports: [RouterTestingModule],
      providers: [ RouterTestingModule],
    })
    .compileComponents();
 }));

I sincerely hope this information proves valuable to someone else facing the same issue.

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

Has anyone discovered an Angular2 equivalent to $provide.value() while testing promises?

I am currently experimenting with testing a promise in Angular2. Here is what I have so far: this.fooService.getData().then(data => this.fooData = data); If you are interested in learning about testing promises for Angular 1, check out this article. ...

What type is the appropriate choice for this handler?

I´m struggling to select the right type for this particular function. It serves as an async handler for express js in a project that utilizes typescript and eslint for linting with specific rules. export function asyncHandler( handler: any ): (req: Requ ...

Struggling to make Typescript recognize the css prop (emotion) when styling Material-UI components

I'm on a mission to set up a Typescript project with Material-UI v4.11.4 and implement emotion for styling in anticipation of the MUI v5 release. The aim is to integrate emotion into the project so developers can transition to using the new styling in ...

How come the information I receive when I subscribe always seems to mysteriously disappear afterwards?

I've been working on a web project using Angular, and I've run into an issue with my code that's been causing problems for a while now. The problem lies in fetching data from a server that contains translations: getTranslations(): Observab ...

The arrow function in Jest is missing a name property

Currently, my setup includes: node.js: 9.8.0 Jest: 23.4.2 ts-jest: 23.1.3 typescript: 2.9.2 While attempting the following in my *.test.ts files: const foo = () => 'bar'; console.log(foo.name); // '' foo contains the name pro ...

Tips on utilizing index and eliminating React Warning: Ensure every child within a list has a distinct "key" prop

Hello, I am encountering an issue where I need to properly pass the index in this component. Can you help me figure out how to do that? Error: react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop ...

"What is the most effective way to utilize and integrate the `setValue` function from react-hook-form within a custom react hook

Struggling to pass setValue to a react hook? In my custom react hook, I need to set values in a form using react-hook-form's setValue. Yet, after migrating from v6 to v7, I'm having trouble figuring out the proper typing for this. This is how t ...

"Unindexing data in Angular: A step-by-step guide

Can someone help me figure out how to delete an item by index in Angular? I have a parameter and a remove button, but when I tried putting my parameter inside the remove button it didn't work. How can I fix this? deleteRowFiles(rowIndex: number){ th ...

Is there a way to automatically determine the parameters of a constructor to match the default class type in TypeScript

I need a function in a class that can utilize a type from constructor arguments, but I am unsure how to achieve this. class CustomClass<Type1, Type2=any>{ a: string = 'a' constructor(private readonly parameters: { attributes: Type ...

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

Subscribing to Observables in Angular Services: How Using them with ngOnChanges Can Trigger Excessive Callbacks

Consider the following scenario (simplified): Main Component List Component List Service Here is how they are connected: Main Component <my-list [month]="month"></my-list> List Component HTML <li *ngFor="let item in list | async>&l ...

It is not possible to access an object's properties using bracket notation when the index is a variable

Is there a way to convert the JavaScript code below into TypeScript? function getProperties(obj) { for (let key in obj) { if (obj.hasOwnProperty(key)) { console.log(obj[key]); } } } I've been trying to find a solution but it seems t ...

Injecting universal data into ValidationErrors in Angular

Trying to bind a value into ValidationErrors. Having this method: isUniqueEmail(control: FormControl): ValidationErrors { if (control.value != null) { console.log(control.value) if(control.value == this.foundEmail){ console ...

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

Using vue-router within a pinia store: a step-by-step guide

I'm currently setting up an authentication store using Firebase, and I want to direct users to the login/logged page based on their authentication status. My goal is similar to this implementation: https://github.com/dannyconnell/vue-composition-api- ...

Creating Excel documents using Angular and XLSX template generator

In my Angular application, I am utilizing the XLSX library to manipulate an Excel file. The file I start with is encoded in base64 format, so my first task is to decode it, make some changes to specific cells, and then save the modified file back in base64 ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

leveraging third party plugins to implement callbacks in TypeScript

When working with ajax calls in typical javascript, I have been using a specific pattern: myFunction() { var self = this; $.ajax({ // other options like url and stuff success: function () { self.someParsingFunction } } } In addition t ...

Error: Attempting to access the 'pipe' property of an object that is undefined in the context of Jasmine and Angular

I'm encountering an issue with unit testing in Angular. Specifically, I'm getting a TypeError: Cannot read property 'pipe' of undefined when trying to test the output of an observable subscribe function. Any assistance on resolving this ...

React: Issue with passing arguments to redux action hooks

In my React application, I have implemented Redux-Toolkit to manage reducers and actions with slices. I am currently working on creating actions that can update and delete values from the store, requiring arguments for their usage. To achieve this, I have ...