我找到了解决办法。我只检查事件的defaultPrevented属性,而不是检查值(它永远不会更改)。
我还遗漏了两件事:
以下是完整测试:
describe('PreventInputDirective', () => {
let fixture;
let input: DebugElement;
beforeEach(() => {
fixture = TestBed.configureTestingModule({
declarations: [PreventInputDirective, TestComponent]
}).createComponent(TestComponent);
input = fixture.debugElement.query(By.directive(PreventInputDirective));
fixture.detectChanges();
});
it('should create an instance', () => {
const directive = new PreventInputDirective();
expect(directive).toBeTruthy();
});
it('should prevent keypress event', () => {
const event = new KeyboardEvent('keypress', {
'key': '.',
cancelable: true
});
input.nativeElement.dispatchEvent(event);
expect(event.defaultPrevented).toBeTruthy();
});
it('should not prevent keypress event', () => {
const event = new KeyboardEvent('keypress', {
'key': '5',
cancelable: true
});
input.nativeElement.dispatchEvent(event);
expect(event.defaultPrevented).toBeFalsy();
});
@Component({
template: `<input cdtPreventInput="." />`
})
class TestComponent { }
});