In vanilla JS you can simulate a key up on an input by doing:
testComponent.dispatchEvent(new Event("keyup"))
However doing this in the angular-cli unit test or in the console doesn't trigger this function in my component, which responds to key events by:
@HostListener('keyup', ['$event'])
onKeyUp(event: KeyboardEvent) {
Any ideas?
For click event we can use triggerEventHandler method of Angular DebugElement class. We can also call native JavaScript click method of button. On click of button, we call a component method and it is possible that our component method has other dependencies to execute.
A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.
The describe code block represents the test suite for AppComponent. It contains specs and additional code that's used for testing AppComponent. beforeEach is a global function in Jasmine that runs some setup code before each spec in the test suite.
According to the Angular Testing documentation, to trigger the events from the tests, we use the triggerEventHandler() method on the debug element. This method takes the event name and the object .
You should create an event
const event = new KeyboardEvent('keyup', {
bubbles : true, cancelable : true, shiftKey : false
});
And then get the reference of the debugElement using css selector
const input = debugElement.query(By.css('#id_of_element'));
And then reference of native html element from the previous one
const inputElement = input.nativeElement;
Assign the value for the native element as , now the text field value contains 12.
inputElement.value = 12;
finally dispatch the key up event
inputElement.dispatchEvent(event);
it will trigger the function
Dont forget to add the following line in before each and make sure you define debugElement
debugElement = fixture.debugElement;
Hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With