KeyboardEvent

时间:2017-11-03 17:44:00

标签: javascript angular unit-testing karma-jasmine

我正在尝试为我编写的实用程序编写单元测试,以限制输入字段可用的字符。该方法接受键盘事件并确定触发了哪个event.code并返回true或event.preventDefault()。这很好但我无法在茉莉/业力中测试它。

模板的当前输入

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

这是我目前的测试

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);
    }));

我还有其他测试,我已经对这些方法进行了间谍活动,并且他们被解雇了。我怀疑isTrusted属性设置为false,即使我试图将其设置为true。

2 个答案:

答案 0 :(得分:3)

所以 - 我最终使用的答案是:

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);
}));

正如其中一位回应者所回答的那样,不可能创建一个真正的isTrusted keypressed事件(从我读过的内容)。所以为了测试这个,我使用了一个茉莉花间谍来看看当我将KeyboardEvent传递给我构建的实用程序函数时是否调用了preventDefault。希望这可以节省一些时间......花了一段时间才到这里!

答案 1 :(得分:0)

触发事件时,不能强制isTrusted的值为false  通过dispatchEvent调用。这里是文件https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted