我想在" keydown"上测试一个输入元素。事件并写下以下案例。
it('should accept input', fakeAsync(() => {
let inputSelector = fixture.debugElement.query(By.css('input')).nativeElement;
expect(inputSelector.value).toBe('', 'value not empty at start');
fixture.detectChanges();
tick();
const event = new KeyboardEvent("keydown", {
key: "a",
code: "KeyA"
});
inputSelector.dispatchEvent(event);
tick();
expect(inputSelector.value).toBe('a', 'value empty after some alphabet keypress');
const eventNum = new KeyboardEvent("keydown", {
key: "1",
code: "Digit1"
});
inputSelector.dispatchEvent(eventNum);
tick();
expect(inputSelector.value).toBe('1', 'value empty after some number keypress');
}));

但inputSelector
的值始终为空。我不确定我做错了什么以及我应该做些什么。
答案 0 :(得分:0)
您应该能够执行与此答案相同的操作:https://stackoverflow.com/a/54042368/6835260
describe('NumberComponent', () => {
let component: NumberComponent;
let fixture: ComponentFixture<NumberComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [NumberComponent, NumberOnlyDirective],
imports: [FormsModule]
})
.compileComponents();
}));
beforeEach(async(() => {
fixture = TestBed.createComponent(NumberComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should prohibit non-numeric input', () => {
let numberDebug = fixture.debugElement.query(By.css('.number-input'));
let numberInput = numberDebug.nativeElement as HTMLInputElement;
fakeTyping('12abc34de', numberInput);
expect(numberInput.value).toBe('1234');
});
function fakeTyping(value: string, inputEl: HTMLInputElement) {
let result: string = '';
for (let char of value) {
let eventMock = createKeyDownEvent(char);
inputEl.dispatchEvent(eventMock);
if (eventMock.defaultPrevented) {
// invalid char
} else {
result = result.concat(char);
}
}
inputEl.value = result;
inputEl.dispatchEvent(new Event('input'));
fixture.detectChanges();
}
});