Failed to simulate Angular 2 unit test key event (Jasmine)

I use the directive to get input data used as filter text.

here is my hostlistener in the directive:

@HostListener('input', ['$event.target.value']) public onChangeFilter(event: any): void { console.log('input event fired, value: ' + event); this.columnFiltering.filterString = event; this.filterChanged.emit({filtering: this.columnFiltering}); } 

this code works fine, i can't unit test the same.

I subscribed to filterChanged EventEmitter, in my unit test, to check the value.

I tried to simulate a keypress event to change the value, and also tried the parameter value attribute. None of them work for me.

here is my spec file:

 describe('Table View', () => { let fixture: ComponentFixture<any>; let context: TableComponent; beforeEach(() => { TestBed.configureTestingModule({ providers: [ TableComponent, ], imports: [TableModule], }); fixture = TestBed.createComponent(TableComponent); context = fixture.componentInstance; }); it('should allow filter', () => { const element = fixture.nativeElement; context.config = config; fixture.detectChanges(); let tableChangeCount = 0; let tableEvent: any; context.tableChanged.subscribe((event: any) => { tableChangeCount++; tableEvent = event; }); // Check if table exists let inputElement = element.querySelectorAll('tr')[1].querySelector('input'); let e = new KeyboardEvent("keypress", { key: "a", bubbles: true, cancelable: true, }); inputElement.dispatchEvent(e); }); }); 

I tried setting the value:

 let attrs = inputElement.attributes; inputElement.setAttribute('value', 'abc'); for (let i = attrs.length - 1; i >= 0; i--) { // Attribute value is set correctly if (attrs[i].name === 'value') { console.log(attrs[i].name + "->" + attrs[i].value); } } 

Can someone help me how can I unit test the same?

+17
input unit-testing angular jasmine keypress
source share
2 answers

I had problems simulating a unit test key press. But I came across the answer of Seyed Jalal Hosseini. Perhaps this is what you need.

If you are trying to simulate a keystroke, you can raise an event by calling dispatchEvent(new Event('keypress')); in the element.

Here is the answer I'm referring to that gives more details: fooobar.com/questions/175877 / ...

If you want to set the key pressed, this can also be done.

 const event = new KeyboardEvent("keypress",{ "key": "Enter" }); el.dispatchEvent(event); 

Additional info I just came across: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

+31
source share

If you want to use key code (or "which"), you can do this:

 // @HostListener('document:keypress') const escapeEvent: any = document.createEvent('CustomEvent'); escapeEvent.which = 27; escapeEvent.initEvent('keypress', true, true); document.dispatchEvent(escapeEvent); 
+3
source share

All Articles