" CUSTOM_ELEMENTS_SCHEMA"测试Angular 2应用程序时出错

时间:2017-02-13 23:42:32

标签: javascript unit-testing angular typescript

在为我的Angular 2应用编写测试时,我遇到了这些错误:我们正在使用的选择器:

"): AppComponent@12:35 'tab-view' is not a known element:
1. If 'my-tab' is an Angular component, then verify that it is part of this module.
2. If 'my-tab' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
    </div>
    <div class="app-body">
        [ERROR ->]<tab-view class="my-tab" [options]="tabOptions"></tab-view>
    </div> </div> 

我已将CUSTOM_ELEMENTS_SCHEMA添加到我的根模块以及所有其他模块中,但我仍然收到错误。

  • 我还需要做什么?
  • 这需要在所有模块中,还是只需要根目录?
  • 我还需要添加其他内容吗?

2 个答案:

答案 0 :(得分:22)

因此,我需要做的就是在TestBed.configureTestingModule中设置模式 - 这不是一个单独的模块文件,而是app.component.spec.ts文件的一部分。感谢@camaron提示。我认为在这一点上,文档可能更清晰。

无论如何,这是我为了让它发挥作用而添加的内容。以下是我的app.component.spec.ts文件的开头内容。

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './../app.component';
import { RouterTestingModule } from '@angular/router/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

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

答案 1 :(得分:3)

这对我有用,在您的spec.ts文件中,您必须import您的组件,并且需要将其添加到declarations。在我的情况下,它在about.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AboutComponent } from './about.component';
import { SidebarComponent } from './../sidebar/sidebar.component';
import { FooterComponent } from './../footer/footer.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
       declarations: [ AboutComponent, SidebarComponent, FooterComponent ]
    })
    .compileComponents();
  }));

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

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