Angular4 - 如何使用Karma和Jasmine对指令进行单元测试

时间:2017-10-16 18:03:44

标签: javascript angular karma-jasmine keypress directive

我创建了一个非常简单的指令,用于输入元素,只允许输入一个十进制数字(带小数点的数字)。

该指令的定义如下:

import { HostListener, Directive, ElementRef  } from '@angular/core';

// Directive attribute to stop any input, other than a decimal number.
@Directive({
    selector: '[decimalinput]'
})
export class DecimalInputDirective {

    constructor(private element : ElementRef) { }

    // Hook into the key press event.
    @HostListener('keypress', ['$event']) onkeypress( keyEvent : KeyboardEvent ) : boolean {

        // Check if a full stop already exists in the input.
        var alreadyHasFullStop = this.element.nativeElement.value.indexOf('.') != -1;

        // Get the key that was pressed in order to check it against the regEx.
        let input = String.fromCharCode(keyEvent.which);

        // Test for allowed character using regEx. Allowed is number or decimal.
        var isAllowed = /^(\d+)?([.]?\d{0,2})?$/.test( input );

        // If this is an invlid character (i.e. alpha or symbol) OR we already have a full stop, prevent key press.
        if (!isAllowed || (isAllowed && input == '.' && alreadyHasFullStop)){
            keyEvent.preventDefault();
            return false;
        }

        return true;
    }
}

此指令应允许"123.123"不是"abc",也不允许"1.2.1"。现在我想测试这个指令,在线阅读,到目前为止我已经提出了这个:

import { Component, OnInit, TemplateRef,DebugElement, ComponentFactory, ViewChild, ViewContainerRef } from '@angular/core';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { DecimalInputDirective } from './decimalinput.directive';
import { By } from '@angular/platform-browser';

@Component({
    template: `<input type="text" name="txtDecimalTest" decimalinput>` 
})
class TestDecimalComponent { }


describe('Directive: DecimalInputDirective', () => {

    let component: TestDecimalComponent;
    let fixture: ComponentFixture<TestDecimalComponent>;
    let decimalInput: DebugElement;

    beforeEach(() => {

      TestBed.configureTestingModule({
        declarations: [TestDecimalComponent]
      });

      fixture = TestBed.createComponent(TestDecimalComponent);
      component = fixture.componentInstance;
      decimalInput = fixture.debugElement.query(By.css('input[name=txtDecimalTest]'));
    });

    it('Entering email and password emits loggedIn event', () => {

        // This sets the value (I can even put "abc" here and it will work.
        decimalInput.nativeElement.value = "12345";

        // But I am trying to initialize the keypress event, so the character is tested in a real world way when the user is using.
        decimalInput.nativeElement.dispatchEvent(new KeyboardEvent("keypress", { key: "a" })); // Nothing happens here!  This was my attempt...

        // This 
        expect(decimalInput.nativeElement.value).toBe("12345");
    });
});

您可以从代码中看到以下行:

decimalInput.nativeElement.dispatchEvent(new KeyboardEvent...

我是否尝试模拟按键,就好像用户正在输入一样。如果我模拟a,那么b,然后是c,然后是1,然后是2,然后是3,我希望测试确保该值仅为&#34; 123&#34;并忽略了#34; abc&#34;在指令的工作方式。

两个问题 - 1)这是我应该做的正确测试吗? 2)我的代码出了什么问题 - 为什么模拟按键什么都不做?

提前感谢任何指示! :)

1 个答案:

答案 0 :(得分:0)

通常指令的测试方式是在实际组件中使用它。因此,您可以创建一个使用您的指令的假组件,您可以测试该组件来处理您的指令。

这是大多数人的建议。

所以在你的测试文件中创建一个假指令

// tslint:disable-next-line:data
@Component({
  selector: 'sd-test-layout',
  template: `
    <div sdAuthorized [permission]="'data_objects'">test</div>`
})
export class TestDecimalInputDirectiveComponent {

  @Input() permission;

  constructor() {
  }
}

然后在每个使用TestBed之前创建组件实例,现在您已准备好应用鼠标事件并在实际情况下测试它们

TestBed.configureTestingModule({
  imports: [
    HttpModule,
    SharedModule
  ],
  declarations: [
    TestDecimalInputDirectiveComponent,
  ],
  providers: [
    {
      provide: ElementRef,
      useClass: MockElementRef
    },
    AuthorizedDirective,
  ]
}).compileComponents();

刚给你提示。您可以follow this link获取更多信息