Search code examples
htmlnode.jsangulartestingkarma-jasmine

Testing Angular with template containing mat-toolbar


I'm trying to write some tests for my Angular project. Here is my template I'm using in my AppComponent:

<mat-toolbar color="primary">
  <span>CRUD Exercise</span>
  <span class="example-spacer"></span>
  <button mat-raised-button (click)="openAddEditPersonForm()" >
    Add Person
  </button>
</mat-toolbar>

and here is my app module @NgModule:

@NgModule({
  declarations: [
    AppComponent,
    PerAddEditComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatToolbarModule,
    MatIconModule,
    MatButtonModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    ReactiveFormsModule,
    HttpClientModule,
    MatDialogModule
  ],
 
  providers: [
    provideClientHydration()
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

and here is what I get when I run the tests for creating the app:

Error: NG0304: 'mat-toolbar' is not a known element (used in the 'AppComponent' component template):
1. If 'mat-toolbar' is an Angular component, then verify that it is a part of an @NgModule where this component is declared.
2. If 'mat-toolbar' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Solution

  • Wow, I actually managed to solve the issue, I was just missing the MatToolbarModule in imports of TestBed.configureTestingModule(). now the code looks like this:

     beforeEach(async () => {
        await TestBed.configureTestingModule({
          imports: [
            RouterTestingModule,
            MatToolbarModule //the missing part
          ],
          declarations: [
            AppComponent
          ]
        }).compileComponents();
      });