maia
maia

Reputation: 4360

Testing select input change in Angular2/Jasmine

I'm having trouble figuring out how to simulate a change in the value of a dropdown list in my jasmine unit test.

When the dropdown list value is changed, it emits an event.

My current test looks like:

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]);

The error I receive is:Expected spy emit to have been called with [ Object({ ... }) ] but it was never called.

Upvotes: 1

Views: 3795

Answers (1)

Julia Passynkova
Julia Passynkova

Reputation: 17889

This the way how I test a similar component with select box:

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 is an output of the component. Basically I have to test when an select option got changed the component fires event.

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

====

here is 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));
}

Upvotes: 2

Related Questions