Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullInjectorError: R3InjectorError(DynamicTestModule)[Router -> Function -> Function]: NullInjectorError: No provider for Function

Recently I have started learning angular and in my first project (ToDo API) I have been stuck on a problem occuring when I test the application with: ng test. As you can see the error is in the title.

This is my component, where I get the error:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';

import { TodosComponent } from './todos.component';

describe('TodosComponent', () => {
  let component: TodosComponent;
  let fixture: ComponentFixture<TodosComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      providers: [ Router ],
      declarations: [ TodosComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(TodosComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

And this is my app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserComponent } from './user/user.component';
import { RegistrationComponent } from './user/registration/registration.component';
import { LoginComponent } from './user/login/login.component';
import { TodosComponent } from './user/todos/todos.component';
import { CreateItemComponent } from './user/todos/create-item/create-item.component';
import { UserService } from './shared/user.service';
import { AuthInterceptor } from './auth/auth.interceptor';
import { ShowCompleteDeleteComponent } from './user/todos/show-complete-delete/show-complete-delete.component';

@NgModule({
  declarations: [
    AppComponent,
    UserComponent,
    RegistrationComponent,
    LoginComponent,
    TodosComponent,
    CreateItemComponent,
    ShowCompleteDeleteComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [UserService, {
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true
  }],
  bootstrap: [AppComponent]
})
export class AppModule { }

I would really appreciate your help!

like image 802
Georgi Dimitrov Dimitrov Avatar asked Nov 25 '20 14:11

Georgi Dimitrov Dimitrov


1 Answers

Use RouterTestingModule, and it must be in imports.

await TestBed.configureTestingModule({
  declarations: [ TodosComponent ]
  imports: [ RouterTestingModule ],
})
.compileComponents();
like image 140
Bojan Kogoj Avatar answered Sep 29 '22 06:09

Bojan Kogoj