Как написать модульный тест для структурной директивы со звездочкой * в Angular - PullRequest
1 голос
/ 08 июля 2019

Я создаю проект примеров 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,
      ]
    ....

простой-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,
      ) { }
    }

простой-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 Ответ

1 голос
/ 08 июля 2019

К сожалению, NO_ERRORS_SCHEMA не может подавить случай с привязкой свойства к ng-template

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

Вы должны добавить свой SimpleStructuralDirective к declarations массиву TestBed.configureTestingModule во всех ваших файлах spec.ts, где вы используете DirectivesComponent.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...