Search code examples
angularunit-testingangular-cliangular7

Angular how not to import all the dependencies in component unit tests each time


I have a working app(when run ng serve all works fine) however, when I run ng test compiler complains about not recognizing directives/properties such as Can't bind to 'formControl' since it isn't a known property of 'input'. When I add

TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        SomeComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        .. other dependencies
    ]

what is the smart way not to add all the imports that I have already added in the app.module ?

UPDATE: I am talking about unit testing a component.


Solution

  • Your tests are Independent from your app.module. So you need to import all needed modules.

    If you want, you can do a shared.module.ts where you have all the modules for test:

    const MODULE_DEPENDENCIES = [
      TranslateModule,
      HttpClientModule,
      ReactiveFormsModule,
      ScrollingModule,
      MatFormFieldModule,
      MatInputModule,
    ];
    
    @NgModule({
      imports: MODULE_DEPENDENCIES,
      exports: [
        ...MODULE_DEPENDENCIES
      ],
    })
    
    export class SharedModule {
      constructor() { }
    
      }
    }