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

时间:2017-07-22 15:42:17

标签: angular unit-testing angular-directive

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

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>!

它有效

hover text changes color

然后我开始构建一些测试,在一次测试中我尝试绑定不同的颜色(就像上面的例子一样),但它没有绑定值,字段是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');
  });
});

测试输出显示

fallback color

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

1 个答案:

答案 0 :(得分:3)

我发现默认情况下,Angular在测试期间不会对模板运行绑定。即使是简单的{{ myVar }}也不会起作用,除非你让它运行绑定和生命周期事件,如Angular detectchanges documentation中所述。

此方案有两个选项,我可以手动调用

fixture.detectChanges();

刚拿到夹具后。

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

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