0

I decided to experiment the testing features of Angular. I have an app already so I just ran ng test and instantly it has errors that I don't understand. This is my first time running Angular testing.

Here is the output:

AppComponent should create the app
Failed: Template parse errors:
Can't bind to 'routerLink' since it isn't a known property of 'button'. ("<mat-toolbar color="primary">
    <mat-toolbar-row>
        <button mat-button [ERROR ->][routerLink]="'/'">{{title}}</button>
        <button mat-button (click)="login()" *ngIf="!user">Logi"): ng:///DynamicTestModule/AppComponent.html@2:27
'mat-toolbar-row' is not a known element:
1. If 'mat-toolbar-row' is an Angular component, then verify that it is part of this module.
2. If 'mat-toolbar-row' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("<mat-toolbar color="primary">

Here is the HTML snippet in app.component.html:

<button mat-button [routerLink]="[ ... ]">{{title}}</button>

And I definitely imported RouterModule into app.module.ts:

@NgModule({
    declarations: [
        ...
    ],
    imports: [
        RouterModule.forRoot(routes),
        ...
    ],
    ...
})
export class AppModule {}
Kim Kern
  • 54,283
  • 17
  • 197
  • 195
AskYous
  • 4,332
  • 9
  • 46
  • 82
  • Have a look at this answer: https://stackoverflow.com/a/44508549/4694994 – Kim Kern Jul 25 '18 at 20:57
  • @KimKern, I have to import all the modules that were in `app.module.ts` into `app.component.spec.ts` as well? – AskYous Jul 25 '18 at 21:02
  • No, only those that are used by the tested component. Better than importing would be mocking them. You want to test your component in isolation. Some modules offer test implementations, like the `RouterTestingModule`. – Kim Kern Jul 25 '18 at 21:04

1 Answers1

1

You need to import the RouterTestingModule in your test's module declaration. The same with all material components you are using. Either also import the MatButtonModule in your test or mock all used components and directives as described in this SO answer. Unit tests have their own module declaration, so that they can be tested in isolation. This means, that you need to import all dependencies again or mock them.

Another option is to use NO_ERRORS_SCHEMA but I would not recommend this. This will only work in cases where you do not use any logic from your imports.

describe('AppComponent', () => {
beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [
      AppComponent
    ],
    schemas: [NO_ERRORS_SCHEMA]
  }).compileComponents();
}));
Kim Kern
  • 54,283
  • 17
  • 197
  • 195