测试运行时 Angular 2 模板解析错误

标签 angular testing typescript karma-runner

所以我有一个简单的组件:

画廊.comonent.ts

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


@Component({
  selector: 'galery-component',
  templateUrl: 'galery.component.html',
  styleUrls: ['galery.component.css']
})
export class GaleryComponent {
  @Input() userPosts;
}

在它的 html 文件中有一个自定义标签。这个标签是我模块的另一个组件的选择器。

画廊.comonent.html

 <div class="container">
        <post-details class="post-container" *ngFor="let post of userPosts" [singlePost] = "post">
        </post-details>
    </div>

当我尝试运行我的测试用例时它启动失败并出现此错误

  1. If 'post-details' is an Angular component and it has 'singlePost' input, then verify that it is part of this module.
  2. If 'post-details' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.

这是一个测试代码:

测试.spec.ts

describe('BannerComponent (inline template)', () => {

  let comp:    GaleryComponent;
  let fixture: ComponentFixture<GaleryComponent>;
  let de:      DebugElement;
  let el:      HTMLElement;


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

  beforeEach(() => {
    fixture = TestBed.createComponent(GaleryComponent); // here test fails

    comp = fixture.componentInstance;
    de = fixture.debugElement.query(By.css('post-details'));
    el = de.nativeElement;
  });

我已将 CUSTOM_ELEMENTS_SCHEMA 添加到我的模块,但没有任何效果。 这是 app.module.ts

应用程序模块.ts

import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {AppComponent} from './app.component';
import {GaleryComponent} from './Components/galeryComponent/galery.component';
import {PostDetailsComponent} from './Components/postDetailsComponent/post-details-component.component';

@NgModule({
  declarations: [
    AppComponent,
    GaleryComponent,
    PostDetailsComponent
  ],
  exports: [GaleryComponent],
  imports: [
    CommonModule,
    NgbModule.forRoot(),
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})

export class AppModule {
}

也许有人知道发生了什么事?我已经阅读了一些类似问题的答案,但它们不是很有帮助。

最佳答案

我怀疑你在错误的地方定义了模式

尝试

TestBed.configureTestingModule({
  declarations: [GaleryComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA] // will work if selector has '-' in its name
})

TestBed.configureTestingModule({
  declarations: [GaleryComponent],
  schemas: [NO_ERRORS_SCHEMA]
})

另见

关于测试运行时 Angular 2 模板解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42610700/

相关文章:

Angular2 http 同步

javascript - React.useMemo 无法防止重新渲染

http - 解析器错误 : Unexpected end of expression: {{value? }} | Angular 2 typescript

angular - ionic 4 : Cannot read property 'get' of undefined

angular - 如何在 Apache-tomcat 服务器中运行 Angular 4.6 应用程序?

javascript - 我可以在同一个 Angular 2 应用程序种子上启动 Angular 4 吗?

ScalaTest 规范编译错误

java - 如何为将输出打印到控制台的 void 函数编写 junit 测试用例

java - 单元测试应该使用绝对值吗?

javascript - 在 Typescript 中扩展 {}(对象)