4

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?

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Can
  • 553
  • 1
  • 9
  • 29

2 Answers2

4

I succeeded to triggered an event with the following code in my unit test:

const inputEvent = new InputEvent('blur');
inputs[0].dispatchEvent(inputEvent);
jnovack
  • 7,629
  • 2
  • 26
  • 40
OL CO
  • 96
  • 3
  • Thanks @OL CO, I used your answer and added the ```fixture.detectChanges();``` after each event, then it finally worked! – MikhailRatner Mar 07 '22 at 10:46
1

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();
  })
MikhailRatner
  • 452
  • 6
  • 13