0

这是我运行测试的组件:

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

如何解决这个问题?

4

1 回答 1

1

这是因为你使用bread-crumbsinsideshell-bread-crumbs.component.html

你可以做两件事

  1. 进口或BreadCrumbsModule申报BreadCrumbsComponentTestBed
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();
}));
于 2019-09-11T06:36:41.750 回答