指令绑定在规范文件中不起作用

Directive binding not working in a spec file

我有一个突出显示文本的指令:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
  @Input('appHighlight') // tslint:disable-line no-input-rename
  highlightColor: string;

  constructor(private el: ElementRef) { }

  @HostListener('mouseenter')
  onMouseEnter() {
    this.highlight(this.highlightColor || 'yellow');
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

在我的应用程序上 HTML 我有:

This <span [appHighlight]="'pink'">is nice</span>!

而且有效

然后我开始构建一些测试,在一个测试中我尝试绑定不同的颜色(就像上面的例子),但它不绑定值,字段是 undefined

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';

@Component({
  selector: 'app-test-container',
  template: `
    <div>
      <span id="red" appHighlight>red text</span>
      <span id="green" [appHighlight]="'green'">green text</span>
      <span id="no">no color</span>
    </div>
  `
})
class ContainerComponent { }

const mouseEvents = {
  get enter() {
    const mouseenter = document.createEvent('MouseEvent');
    mouseenter.initEvent('mouseenter', true, true);
    return mouseenter;
  },
  get leave() {
    const mouseleave = document.createEvent('MouseEvent');
    mouseleave.initEvent('mouseleave', true, true);
    return mouseleave;
  },
};

fdescribe('HighlightDirective', () => {
  let fixture: ComponentFixture<ContainerComponent>;
  let container: ContainerComponent;
  let element: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ContainerComponent, HighlightDirective],
    });

    fixture = TestBed.createComponent(ContainerComponent);
    container = fixture.componentInstance;
    element = fixture.nativeElement;
  });

  fit('should set background-color green when passing green parameter', () => {
    const targetElement = <HTMLSpanElement>element.querySelector('#green');

    targetElement.dispatchEvent(mouseEvents.enter);
    expect(targetElement.style.backgroundColor).toEqual('green');
  });
});

测试输出显示

我做错了什么吗?为什么它不绑定 green 颜色?

我发现默认情况下 Angular 在测试期间不会 运行 绑定模板。即使是简单的 {{ myVar }} 也无法工作,除非您将其设为 运行 绑定和生命周期事件,如 Angular detectchanges documentation.

中所述

这个场景有两种选择,我可以手动调用

fixture.detectChanges();

刚拿到我的灯具。

或者我可以包含一个提供程序,自动将其设置为 运行 东西

providers: [
  { provide: ComponentFixtureAutoDetect, useValue: true },
],