我创建了一个非常简单的指令用于输入元素,它应该只允许输入十进制数(带有单个小数点的数字)。
该指令定义如下:
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,我希望测试能够确保该值仅为“123”,并且以指令的工作方式忽略“abc”。
两个问题 - 1)这是我应该做的正确测试吗? 2)我的代码有什么问题 - 为什么模拟按键没有执行任何操作?
感谢您提前的指点! :)
最佳答案
通常指令的测试方式是在实际组件中使用它。因此,您可以创建一个将使用您的指令的假组件,并且您可以测试该组件来处理您的指令。
这是大多数人的建议。
因此在您的测试文件中创建一个假指令
// 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获取更多信息
关于javascript - Angular4 - 如何使用 Karma 和 Jasmine 对指令进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46776450/