1

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.

1 Answer 1

2

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));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Forgive my ignorance, but I'm getting the error "Property 'pageSelected' does not exist on type 'myComponent'"...?
this 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>();
And "dispatchFakeEvent" is also an event emitter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.