Angular 使用模拟结构指令测试组件失败

Angular testing component with mocked structural directive fails

我正在尝试在组件测试中模拟结构指令,但出现错误。

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

Property binding appSome not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("[ERROR ->]TEST

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

如果我切换声明使其包含 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: [] 中提供了模拟版本并且指令具有相同的选择器。

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

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