测试Directive

测试准备

我们测试一个指令:HoverFocusDirective. 属性选择器定义为hoverfocus,被应用的元素获得功能:鼠标滑过时背景颜色变为蓝色.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import {
    Directive,
    HostListener,
    HostBinding
} from '@angular/core';

@Directive({
  selector: '[hoverfocus]'
})
export class HoverFocusDirective {

  @HostBinding("style.background-color") backgroundColor: string;

  @HostListener('mouseover') onHover() {
    this.backgroundColor = 'blue';
  }

  @HostListener('mouseout') onLeave() {
    this.backgroundColor = 'inherit';
  }
}

测试代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import {TestBed} from '@angular/core/testing';
import {HoverFocusDirective} from './hoverfocus.directive';

describe('Directive: HoverFocus', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [HoverFocusDirective]
    });
  });
});

通常我们需要创建一个测试用的组件来与被测试directive进行交互。

1
2
3
4
5
@Component({
  template: `<input type="text" hoverfocus>` 
})
class TestHoverFocusComponent {
}

测试代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
describe('Directive: HoverFocus', () => {

  let component: TestHoverFocusComponent;
  let fixture: ComponentFixture<TestHoverFocusComponent>;
  let inputEl: DebugElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestHoverFocusComponent, HoverFocusDirective] 
    });
    fixture = TestBed.createComponent(TestHoverFocusComponent); 
    component = fixture.componentInstance;
    inputEl = fixture.debugElement.query(By.css('input'));
  });
});

与视图交互

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
it('hovering over input', () => {
  inputEl.triggerEventHandler('mouseover', null); 
  fixture.detectChanges();
  expect(inputEl.nativeElement.style.backgroundColor).toBe('blue'); 

  inputEl.triggerEventHandler('mouseout', null);
  fixture.detectChanges();
  console.log(inputEl.nativeElement.style.backgroundColor);
  expect(inputEl.nativeElement.style.backgroundColor).toBe('inherit');
});
  • triggerEventHandler 触发事件.