简体   繁体   English

Angular 6 Karma测试'@input装饰器

[英]Angular 6 Karma Test '@input decorator

In the AppComponent, I'm using the nav component in the HTML code. 在AppComponent中,我在HTML代码中使用了nav组件。 The UI looks fine. 用户界面看起来不错。 No errors when doing ng serve. 服务时没有错误。 and no errors in console when I look at the app. 当我查看该应用程序时,控制台中也没有错误。 But when I ran Karma for my project, there is an error: 但是当我为我的项目运行Karma时,出现了一个错误:

Error: 错误:

Failed: Template parse errors:
Can't bind to 'head' since it isn't a known property of 'app-widget'.
1. If 'app-widget' is an Angular component and it has 'head' input, then verify that it is part of this module.
2. If 'app-widget' 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. ("<app-widget [ERROR ->][head]="heading"></app-widget>

Spec.ts: 规格:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeService } from './../../service/home.service';
import { MyFavoriteComponent } from './my-favorite.component';

describe('MyFavoriteComponent', () => {
  let component: MyFavoriteComponent;
  let fixture: ComponentFixture<MyFavoriteComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyFavoriteComponent ],
      providers: [{provide: HomeService}]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyFavoriteComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

TS: TS:

import { Component, OnInit, Input } from '@angular/core';
import { HomeService } from './../../service/home.service';

@Component({
  selector: 'app-my-favorite',
  templateUrl: './my-favorite.component.html',
  styleUrls: ['./my-favorite.component.scss']
})
export class MyFavoriteComponent implements OnInit {
  heading = '';
  constructor(private homeService: HomeService) {}

   ngOnInit() {
    this.homeService.homeDataWidget().subscribe(response => {
      this.heading = response.myfavoirte;
    });

   }

}

HTML 的HTML

<app-widget [head]="heading"></app-widget>

Your component probably use app-widget. 您的组件可能使用app-widget。 You should add it to "declaration" (if it's component) or to "imports" (if it's module) in your test. 您应该在测试中将其添加到“声明”(如果是组件)或“导入”(如果是模块)。

Second way is adding "NO_ERRORS_SCHEMA": 第二种方法是添加“ NO_ERRORS_SCHEMA”:

TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [ MyFavoriteComponent, WidgetComponent],
      providers: [{provide: HomeService}],
      schemas: [NO_ERRORS_SCHEMA]
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM