Angular 使用输入装饰器抛出错误的单元测试

Angular Unit testing with Input decorator throw error

这是我 运行 测试的组件:

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'shell-bread-crumbs',
    templateUrl: './shell-bread-crumbs.component.html',
    styleUrls: ['./shell-bread-crumbs.component.scss']
})
export class ShellBreadCrumbsComponent implements OnInit {

    @Input() breadCrumb;

    constructor() { }

    ngOnInit() {}

}

这是我的规范文件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ShellBreadCrumbsComponent } from './shell-bread-crumbs.component';

describe('ShellBreadCrumbsComponent', () => {

  let component: ShellBreadCrumbsComponent;
  let fixture: ComponentFixture<ShellBreadCrumbsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ShellBreadCrumbsComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ShellBreadCrumbsComponent);
    component = fixture.componentInstance;
    component.breadCrumb = ""; //i given empty declaration,
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

但仍然出现错误:

Template parse errors:
    Can't bind to 'breadCrumb' since it isn't a known property of 'bread-crumbs'.
    1. If 'bread-crumbs' is an Angular component and it has 'breadCrumb' input, then verify that it is part of this module.
    2. If 'bread-crumbs' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
    3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("<bread-crumbs [ERROR ->][breadCrumb]="breadCrumb"></bread-crumbs>")

如何解决这个问题?

因为你在shell-bread-crumbs.component.html

内使用了bread-crumbs

您可以做两件事

  1. TestBed
  2. 中导入 BreadCrumbsModule 或声明 BreadCrumbsComponent
beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ 
          ShellBreadCrumbsComponent,
          BreadCrumbsComponent // if you own this component
      ],
      imports: [BreadCrumbsModule] // if you have module
    })
    .compileComponents();
}));

这样,Angular 就会识别出 bread-crumbs。但是,这可能会产生其他问题。 BreadCrumbsComponent 可能有其他依赖项并使用您需要声明或定义的其他组件。此外,您可能不关心此测试的 BreadCrumbsComponent,这将我们带到您可以做的第二件事

  1. 使用 CUSTOM_ELEMENTS_SCHEMA 以便 angular 将跳过它不识别的元素。您可以按如下方式进行
beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ShellBreadCrumbsComponent ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
    .compileComponents();
}));