具有模拟结构指令的角度测试组件失败

时间:2019-09-20 07:48:21

标签: angular angular-directive angular-test

我正在尝试在组件测试中模拟结构指令,但是我遇到了错误。

以下测试失败,并显示一条消息:

  

属性绑定应用程序嵌入式模板上的任何指令均未使用该属性。确保属性名称拼写正确,并且所有指令均在“ @ NgModule.declarations”中列出。 (“ [ERROR->] TEST

我正在模拟app.component.spec.ts中定义的SomeDirective结构指令SomeMockDirective测试失败

如果我切换声明,使其包含SomeDirective,则-测试通过

我想知道为什么我不能使其与模拟版本一起使用。

模板:

<h1 *appSome="true">TEST</h1>

指令(生产类型:)):

@Directive({
  selector: '[appSome]'
})
export class SomeDirective implements OnDestroy {
  show: boolean;
  ...
}


测试:

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { Directive, NO_ERRORS_SCHEMA } from '@angular/core';

@Directive({
  selector: '[appSome]'
})
export class SomeMockDirective {}

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent, SomeMockDirective], // test is failing, switch the directive to SomeDirective and it passes
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });
});

复制回购: https://github.com/felikf/angular-test-directive

git clone https://github.com/felikf/angular-test-directive.git 
npm i
ng test

我的问题是,即使providers: []中提供了模拟版本并且指令具有相同的选择器,为何模拟版本也不起作用。

1 个答案:

答案 0 :(得分:2)

模拟版本不起作用,因为您尚未定义appSome输入属性:

@Directive({
  selector: '[appSome]'
})
export class SomeMockDirective {
  @Input() appSome;  <================= add this
}