Angular Component in Provider Array in Testbed.configureTestingModule()

Viewed 14

I'm reading the basics on component testing in Angular and there is this code snippet of the file app/welcome/welcome.component.spec.ts (class-only setup) in the Component Class Testing section:

beforeEach(() => {
  TestBed.configureTestingModule({
    // provide the component-under-test and dependent service
    providers: [
      WelcomeComponent,
      { provide: UserService, useClass: MockUserService }
    ]
  });
  // inject both the component and the dependent service.
  comp = TestBed.inject(WelcomeComponent);
  userService = TestBed.inject(UserService);
});

My question is, why is the WelcomeComponent present in the providers array, and not in the declaration array? I thought this is where components should go.

This is the code of the WelcomeComponent

export class WelcomeComponent implements OnInit {
  welcome = '';
  constructor(private userService: UserService) { }

  ngOnInit(): void {
    this.welcome = this.userService.isLoggedIn ?
      'Welcome, ' + this.userService.user.name : 'Please log in.';
  }
}

In the Documentation of NgModule, which TestBed is based on, it states for declarations and providers:

Providers: The set of injectable objects that are available in the injector of this module.

Declarations: The set of components, directives, and pipes (declarables) that belong to this module.

Looking at the definition of declarable in the Angular glossary, it says:

Do not declare the following:

  • A class already declared as standalone.
  • A class that is already declared in another NgModule.
  • An array of directives imported from another package. For example, do not declare FORMS_DIRECTIVES from @angular/forms.
  • NgModule classes.
  • Service classes.
  • Non-Angular classes and objects, such as strings, numbers, functions, entity models, configurations, business logic, and helper classes.

As far as I can tell, none of these situations seems to be the case for the WelcomeComponent. Am I wrong? Is it just "good practice" to put components in the declarations array, and I could just put them in the providers array if I wanted to?

0 Answers
Related