Angular 4 unit test for KeyboardEvent

2020-02-15 07:13发布

问题:

I'm trying to write a unit test for a utility I've written to limit the characters available to an input field. The method takes the keyboard event and determines which event.code has been fired and either returns true or event.preventDefault(). This works great but I cannot test it in jasmine / karma.

Current input from template

<input [(ngModel)]="donationValue" formControlName="donationAmount" 
type="tel" class="donation-amount" (keydown)="checkCharacter($event)" 
placeholder="Enter Amount..."/>

Here is my current test

it('should return have defaultPrevented as true', fakeAsync(() => {
        const goalInput = 
fixture.debugElement.query(By.css('input.donation-
amount')).nativeElement;
        const keyEventData = { isTrusted: true, code: 'KeyA' };
        const keyEvent = new KeyboardEvent('keydown', keyEventData);
        goalInput.dispatchEvent(keyEvent);
        tick();
        fixture.detectChanges();                
        expect(keyEvent.defaultPrevented).toBe(true);
    }));

I have other tests that I have spied on the methods and they are getting fired off. My suspicion is that the isTrusted property is set to false even though I'm trying to set it to true.

回答1:

So - the answer that I ended up using was this:

it('Should call prevent default', inject([ManageUtils], (manageUtils: ManageUtils) => {
    const keyEvent = new KeyboardEvent('keydown', { code: 'KeyA' });
    const spy = spyOn(keyEvent, 'preventDefault');        
    manageUtils.checkCharacterForProperCurrency(keyEvent);
    fixture.detectChanges();
    expect(spy).toHaveBeenCalled()
}));

it('Should not call prevent default', inject([ManageUtils], (manageUtils: ManageUtils) => {
    const keyEvent = new KeyboardEvent('keydown', { code: 'Digit0' });
    const spy = spyOn(keyEvent, 'preventDefault');        
    manageUtils.checkCharacterForProperCurrency(keyEvent);
    fixture.detectChanges();
    expect(spy).toHaveBeenCalledTimes(0);
}));

As one of the responders answered, it is impossible to create a true isTrusted keypressed event (from what I've read). So to test this, I used a jasmine spy to see if preventDefault was called when I passed the KeyboardEvent to the utility function that I built. Hopefully this can save someone time...took me a while to get here!



回答2:

You can't force the value of isTrusted to false when the event is triggred by a dispatchEvent call. Here the documetnation https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted