When i run the unit testing in angular 8 project, i found an error in ngx-toastr

NullInjectorError: StaticInjectorError(DynamicTestModule)[ToastrService -> InjectionToken ToastConfig]:

And i imported the requierd modules in the spec.ts file, And also i declared forRoot() in app.module.ts

  beforeEach(async(() => {
TestBed.configureTestingModule({
  imports: [MatTabsModule,
    ReactiveFormsModule,
    MatTooltipModule,
    HttpClientTestingModule,
    RouterTestingModule,
    ToastrModule
  ],
  declarations: [CommunicationComponent],
  providers: [
    ToastrService,
  ]
})
  .compileComponents();

}));

4

There are 4 best solutions below

0
On BEST ANSWER

import { ToastrModule } from 'ngx-toastr';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ToastrModule.forRoot()],

    })
      .compileComponents();
  }));

Add ToastrModule.forRoot() in imports as shown above and your error might be resolved

0
On

You may forgot to add .forRoot()

Just add this way in your module.ts

ToastrModule.forRoot()

0
On

Change the providers like below

providers: [
  {provide: ToastrService, useClass: ToastrService}
]
0
On

These approaches did not work for me. I had to provide my own value for the provider. This is what worked for me:

First, I declared my own "dummy" implementation:

const toastrService = {
    success: (message?: string, title?: string, override?: Partial<IndividualConfig>) => { },
    error: (message?: string, title?: string, override?: Partial<IndividualConfig>) => { }
  };

Then, I indicated the value to use in the providers section:

providers: [
        ...
        { provide: ToastrService, useValue: toastrService },
      ],