我正在尝试做一个非常基本的单元测试,以测试在文本字段中按退格键是否会删除字符。然而,我尝试了各种触发事件的方法,但它似乎并没有真正删除任何东西。到目前为止,我所得到的是基于来自这个库https://github.com/JsDaddy/ngx-mask/blob/develop/src/app/ngx-mask/test/delete.spec.ts的规范文件
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormControl } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { DebugElement, Component } from '@angular/core';
@Component({
template: `
<input type="text" (keydown)="keydown()"
(focus)="focus()"
(blur)="blur()"
(input)="input()" id="testField" [formControl]="formField" />`,
})
class TestInputComponent {
public formField: FormControl;
constructor() {
this.formField = new FormControl('ABCDE');
}
keydown() { console.error('keydown called'); }
input() { console.error('input called'); }
focus() { console.error('focus called'); }
blur() { console.error('blur called'); }
}
describe('Delete Characters', () => {
let fixture: ComponentFixture<TestInputComponent>;
let component: TestInputComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestInputComponent],
imports: [
ReactiveFormsModule,
],
});
fixture = TestBed.createComponent(TestInputComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should delete a character and move cursor back', () => {
const debugElement: DebugElement = fixture.debugElement.query(By.css('input'));
const inputTarget: HTMLInputElement = debugElement.nativeElement as HTMLInputElement;
spyOnProperty(document, 'activeElement').and.returnValue(inputTarget);
fixture.detectChanges();
inputTarget.value = 'ABCDE';
inputTarget.selectionStart = 3;
inputTarget.selectionEnd = 3;
debugElement.triggerEventHandler('keydown', { code: 'Backspace', keyCode: 8, target: inputTarget });
debugElement.triggerEventHandler('input', { target: inputTarget });
expect(inputTarget.selectionStart).toEqual(2); // Fails, is still 3
expect(inputTarget.value).toEqual('ABDE'); // Fails, is still ABCDE
});
});发布于 2019-10-11 15:10:25
您的triggerEventHandler未触发事件。请将triggerEventHandler替换为dispatchEvent,然后尝试。
debugElement.nativeElement.dispatchEvent(new Event('keydown'), { code: 'Backspace', keyCode: 8, target: inputTarget });
debugElement.nativeElement.dispatchEvent(new Event('input'), { target: inputTarget });请参考此comment。
https://stackoverflow.com/questions/58331562
复制相似问题