10 个规格,10 个故障 - 无法绑定到"routerLink",因为它不是"按钮"的已知属性



我决定试验Angular的测试特性。我已经有了一个应用程序,所以我只运行了ng test,它立即出现了我不理解的错误。这是我第一次运行Angular测试。

这是输出:

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">

以下是app.component.html:中的HTML片段

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

我肯定把RouterModule导入了app.module.ts:

@NgModule({
declarations: [
...
],
imports: [
RouterModule.forRoot(routes),
...
],
...
})
export class AppModule {}

您需要在测试的模块声明中导入RouterTestingModule。与您正在使用的所有材质组件相同。也可以在测试中导入MatButtonModule,或者按照SO答案中的描述模拟所有使用的组件和指令。单元测试有自己的模块声明,因此可以对它们进行隔离测试。这意味着,您需要再次导入所有依赖项或模拟它们。

另一种选择是使用NO_ERRORS_SCHEMA,但我不建议这样做。这只适用于不使用导入中的任何逻辑的情况。

describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));

相关内容

最新更新