测试Angular2 / Jasmine中的选择输入更改

时间:2017-06-27 17:03:55

标签: angular testing select drop-down-menu jasmine

我无法弄清楚如何在我的茉莉花单元测试中模拟下拉列表值的变化。

当下拉列表值更改时,它会发出一个事件。

我目前的测试如下:

spyOn(component.varChange, 'emit');

let selectEl: DebugElement = fixture.debugElement.query(By.css("#selectBox"));
selectEl.nativeElement.selectedIndex = 0;
selectEl.nativeElement.dispatchEvent(new Event("input"));
fixture.detectChanges();
expect(component.varChange.emit).toHaveBeenCalledWith(testData[0]);

我收到的错误是:Expected spy emit to have been called with [ Object({ ... }) ] but it was never called.

1 个答案:

答案 0 :(得分:1)

这就是我用选择框测试类似组件的方式:

fit('should emit event when option is selected', async(() => {
  component.pageSelected.subscribe(() => {
     expect(true).toBeTruthy();
  });
  component.pages = [{id: 1, name: 'julia'}, {id: 2, name: 'xxx'}];
  fixture.detectChanges();

  const options = debugElement.queryAll(By.css('option'));
  dispatchFakeEvent(options[0].nativeElement, 'change');
  fixture.detectChanges();
}));

===

pageSelected是组件的输出。基本上我必须测试选择选项何时更改了组件触发事件。

  @Output() pageSelected = new EventEmitter<number>();

====

这里是dispatchFakeEvent

// from angular materail
export function createFakeEvent(type: string) {
 const event = document.createEvent('Event');
 event.initEvent(type, true, true);
 return event;
}

export function dispatchFakeEvent(node: Node | Window, type: string) 
{
  node.dispatchEvent(createFakeEvent(type));
}