如何在Angular中为带有星号*的结构指令编写单元测试

时间:2019-07-08 19:24:09

标签: angular unit-testing karma-jasmine

我正在创建Angular示例项目,并为此添加了单元测试。开始添加带有指令的示例,并在通过简单的创建测试添加结构指令之后,其他指令测试开始失败,并显示一条消息,提示消息不够清晰

`Failed: Template parse errors:
Property binding appSimpleStructural 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". ("
      </p>
      <div *ngIf="4 === index">
        [ERROR ->]<div *appSimpleStructural="!isOnlyOdd">
          <li
            *ngFor="let even of evenNumbers"
"): ng:///DynamicTestModule/DirectivesComponent.html@17:8`

directives.component.html

    <div *ngIf="4 === index">
        <div *appSimpleStructural="!isOnlyOdd">
          <li
            *ngFor="let even of evenNumbers"
            [ngStyle]="{backgroundColor: even % 2 !== 0 ? 'yellow' : 'transparent'}">
            {{ even }}
          </li>
        </div>
      </div>

directives.module.ts

    @NgModule({
      declarations: [
        ...
        SimpleStructuralDirective
    ],
    imports: [
        CommonModule,
      ],
    exports: [
        ....
        SimpleStructuralDirective,
      ]
    ....

simple-structural.directive.ts


    @Directive({
      selector: '[appSimpleStructural]'
    })
    export class SimpleStructuralDirective {
      @Input() set appSimpleStructural(condition: boolean) {
        if (!condition) {
          this.vcRef.clear();
        } else {
          this.vcRef.createEmbeddedView(this.templateRef);
        }
      }

      constructor(
        private templateRef: TemplateRef<any>,
        private vcRef: ViewContainerRef,
      ) { }
    }

simple-structural.directive.spec.ts

    describe('SimpleStructuralDirective', () => {
      let templateRef: jasmine.SpyObj<TemplateRef<any>>;
      let vcRef: jasmine.SpyObj<ViewContainerRef>;

      let component: DirectivesComponent;
      let fixture: ComponentFixture<DirectivesComponent>;

      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [
            DirectivesComponent,
            SimpleStructuralDirective,
          ],
          schemas: [ NO_ERRORS_SCHEMA ]
        })
        .compileComponents();

        fixture = TestBed.createComponent(DirectivesComponent);
        component = fixture.componentInstance;
      }));

      it('should create an instance', () => {
        const directive = new SimpleStructuralDirective(
          templateRef,
          vcRef
        );

        fixture.detectChanges();

        expect(directive)
          .toBeTruthy();
      });
    });

完整代码可在以下地址获得: https://github.com/dirdakas/ng-playground

预计失败的测试为0,但是在添加结构指令后,其他指令测试开始失败。

1 个答案:

答案 0 :(得分:1)

不幸的是,NO_ERRORS_SCHEMA无法通过在ng-template上进行属性绑定来抑制这种情况。

https://github.com/angular/angular/issues/13713

您应该在使用SimpleStructuralDirective的所有spec.ts文件中,将declarations添加到TestBed.configureTestingModule的{​​{1}}数组中。