'How to trigger onblur in Jasmine unit test?
I have a function which logs something out onblur on a field. How can I trigger the onblur function in unit test?
inputFunction() {
const inputElements = document.querySelectorAll('input, textarea');
inputElements[0].onblur = () => {
return console.log('test');
};
}
Spec file:
describe('inputFunction', () => {
it('should', function() {
// data
const ctrl = new inputController();
const inputs = [angular.element('<input type="text">Test</input>'), angular.element('<input type="text">test</input>')];
spyOn(document, 'querySelectorAll').and.returnValue(inputs);
inputs[0].triggerHandler('blur');
// when
const expect = ctrl.inputFunction();
// expect
expect(expect).toEqual('test');
});
});
Tried with inputs[0].triggerHandler('blur'); but it doesn't work, it doesn't go inside the onblur function in my Unit Test.
How can I trigger onblur and go inside the onblur function?
Solution 1:[1]
I succeeded to triggered an event with the following code in my unit test:
const inputEvent = new InputEvent('blur');
inputs[0].dispatchEvent(inputEvent);
Solution 2:[2]
My solution to a similar problem is based on the the first answer but I had to add this line after each event:
fixture.detectChanges();
My code is different to your question, but I suppose the gist is relatively clear:
it('should show the required error message when there is no value in the first name input field', () => {
// Arrange
const inputElement = fixture.debugElement.query(By.css('#inputFirstName')).nativeElement as HTMLElement;
// Act
const focusEvent = new InputEvent('focus');
inputElement.dispatchEvent(focusEvent);
fixture.detectChanges();
const blurEvent = new InputEvent('blur');
inputElement.dispatchEvent(blurEvent);
fixture.detectChanges();
const firstSpanElement = fixture.debugElement.query(By.css('#inputFirstName + .form-validation > span:first-child'));
// Assert
expect(firstSpanElement).toBeTruthy();
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jnovack |
| Solution 2 | MikhailRatner |
