KeyboardEvent的Angular 4单元测试 [英] Angular 4 unit test for KeyboardEvent

查看:192
本文介绍了KeyboardEvent的Angular 4单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

模板的当前输入

<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,也是如此.

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.

推荐答案

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

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

正如一位响应者回答的那样,不可能创建一个真正的isTrusted按键事件(根据我的阅读).因此,为了对此进行测试,我使用了一个茉莉花间谍,以查看将KeyboardEvent传递给所构建的实用程序函数时是否调用了preventDefault.希望这可以节省某人的时间...花了我一段时间才能到达这里!

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!

这篇关于KeyboardEvent的Angular 4单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆