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

Mui*_*rik 11 javascript unit-testing typescript angular

在为我的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> 
Run Code Online (Sandbox Code Playgroud)

我已经添加CUSTOM_ELEMENTS_SCHEMA到我的根模块,以及所有其他模块,但我仍然得到错误.

  • 我还需要做什么?
  • 这需要在所有模块中,还是只在根目录中?
  • 还有什么需要补充的吗?

Mui*_*rik 24

因此,我必须做的就是在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();
  });
Run Code Online (Sandbox Code Playgroud)


Ary*_*hna 5

它以这种方式对我有用,在您的 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();
  });
});
Run Code Online (Sandbox Code Playgroud)