Search code examples
angularunit-testingjasminehttpclient

Unexpected value 'HttpTestingController' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation


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

  let service: StudentService;
  let httpclient: HttpClient;
  // let httptestcontroller: HttpTestingController; <--

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ComponentHttpRServiceComponent],
      imports: [HttpClientTestingModule],// HttpTestingController <--
      providers: [StudentService],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(ComponentHttpRServiceComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    service = TestBed.inject(StudentService);
    // httptestcontroller = TestBed.inject(HttpTestingController); <--
  });

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

  it('httpclient get method', () => {});
});

whenever I add the HttpTestingController inside the imports array, I get an error written as Unexpected value 'HttpTestingController' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.

how to resolve the above issue?


Solution

  • You don't need to add HttpTestingController anywhere, neither imports nor providers, you just need to add HttpClientTestingModule in imports which you already did.

    HttpTestingController is part of HttpClientTestingModule, So you will get the HttpTestingController in the below line, just uncomment it then you are good to go.

    httptestcontroller = TestBed.inject(HttpTestingController);
    

    Here is the full configuration

    //*Removed extra code for readability
    beforeEach(async () => {
      await TestBed.configureTestingModule({
        imports: [HttpClientTestingModule],
      }).compileComponents();
    });
    
    beforeEach(() => {
      httptestcontroller = TestBed.inject(HttpTestingController);
    });