Angular2--属性型指令单元测试

2016-12-23  本文已影响117人  紫诺_qiu

属性型指令的单元测试

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

@Directive({ selector: '[highlight]' })

export class HighlightDirective implements OnChanges {

  defaultColor =  'rgb(211, 211, 211)'; // lightgray

  @Input('highlight') bgColor: string;

  constructor(private renderer: Renderer, private el: ElementRef) {
    renderer.setElementProperty(el.nativeElement, 'customProperty', true); /** set the element's customProperty to true */
  }

  ngOnChanges() {
    this.renderer.setElementStyle(
      this.el.nativeElement, 'backgroundColor',
      this.bgColor || this.defaultColor );
  }
}
import { Component } from '@angular/core';
@Component({
  template: `
  <h2 highlight="skyblue">About</h2>
  <twain-quote></twain-quote>
  <p>All about this sample</p>`
})
export class AboutComponent { }
beforeEach(() => {
  fixture = TestBed.configureTestingModule({
    declarations: [ AboutComponent, HighlightDirective],
    schemas:      [ NO_ERRORS_SCHEMA ]  //用来“浅化”组件测试程序,告诉编译器忽略不认识的元素和属性,这样你不再需要声明无关的组件和指令,
  })
  .createComponent(AboutComponent);
  fixture.detectChanges(); // initial binding
});

it('should have skyblue <h2>', () => {
  const de = fixture.debugElement.query(By.css('h2'));
  expect(de.styles['backgroundColor']).toBe('skyblue');
});

但是测试单一的用例无法探索该指令的全部能力。但是查找和测试所有使用该指令的组件非常繁琐和脆弱,并且通常无法覆盖所有组件,此时我们可以创建一个展示所有使用该指令的人工测试组件。

@Component({
  template: `
  <h2 highlight="yellow">Something Yellow</h2>
  <h2 highlight>The Default (Gray)</h2>
  <h2>No Highlight</h2>
  <input #box [highlight]="box.value" value="cyan"/>`
})
class TestComponent { }
beforeEach(() => {
  fixture = TestBed.configureTestingModule({
    declarations: [ HighlightDirective, TestComponent ]   //这里要把指令和人工组件都声明一下
  })
  .createComponent(TestComponent);
  fixture.detectChanges(); 
 /** 查找所有用到该指令的宿主元素 */
  des = fixture.debugElement.queryAll(By.directive(HighlightDirective));
  bareH2 = fixture.debugElement.query(By.css('h2:not([highlight])')); //没有用到该指令的宿主元素});

it('should have three highlighted elements', () => {
  expect(des.length).toBe(3);
});

it('should color 1st <h2> background "yellow"', () => {
  expect(des[0].styles['backgroundColor']).toBe('yellow');
});
it('should color 2nd <h2> background w/ default color', () => {
  const dir = des[1].injector.get(HighlightDirective) as HighlightDirective; //监听指令属性变化
  expect(des[1].styles['backgroundColor']).toBe(dir.defaultColor);
});

it('should bind <input> background to value color', () => {
  // easier to work with nativeElement
  const input = des[2].nativeElement as HTMLInputElement;
  expect(input.style.backgroundColor).toBe('cyan', 'initial backgroundColor');
  // dispatch a DOM event so that Angular responds to the input value change.
  input.value = 'green';
  input.dispatchEvent(newEvent('input'));
  fixture.detectChanges();
  expect(input.style.backgroundColor).toBe('green', 'changed backgroundColor');
});

// customProperty tests
it('all highlighted elements should have a true customProperty', () => {
  const allTrue = des.map(de => !!de.properties['customProperty']).every(v => v === true);
  expect(allTrue).toBe(true);
});
it('bare <h2> should not have a customProperty', () => {
  expect(bareH2.properties['customProperty']).toBeUndefined();
});

ps:自己在处理这块儿单元测试时遇到最大的坑就是无法监听属性值的变化以及获取到的DOM元素一直有问题(获取时机不对),花了很多时间。

上一篇下一篇

猜你喜欢

热点阅读