Angular: 如何在 jasmine 单元测试中测试键盘事件
Angular: How test keyboard event in jasmine unit testing
我创建了自定义指令来填充自动破折号。这是 stackblitz 中的完整自定义指令代码。我可以知道如何在茉莉花(单元测试)中测试 mask.ts 中的以下行吗?
mask.ts
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
let trimmed = input.value.replace(/\s+/g, '');
mask.spec.ts
@Component({
template: `
<input type="text" dobMask />
`,
})
class TestdobMaskComponent {}
describe('dobMask', () => {
let component: TestdobMaskComponent;
let fixture: ComponentFixture<TestdobMaskComponent>;
let inputEl: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestdobMaskComponent],
});
fixture = TestBed.createComponent(TestdobMaskComponent);
component = fixture.componentInstance;
inputEl = fixture.debugElement.query(By.css('input'));
});
it('should auto populate dash when reach 6 characters', () => {
const input = inputEl.nativeElement as HTMLInputElement;
});
});
尝试:
it('should auto populate dash when reach 6 characters', () => {
const input = inputEl.nativeElement as HTMLInputElement;
input.dispatchEvent(new KeyboardEvent('keydown', { key: ' ' }));
// put a console.log in onKeyDown to make sure it is triggered.
fixture.detectChanges();
// grab a new reference
const newInputEl = fixture.debugElement.query(By.css('input')) as HTMLInputElement;
// trimmed is a local variable to the function so I don't know how you're going to test it
// expect the space got trimmed
expect(newInputEl.nativeElement.value).toEqual("");
});
我创建了自定义指令来填充自动破折号。这是 stackblitz 中的完整自定义指令代码。我可以知道如何在茉莉花(单元测试)中测试 mask.ts 中的以下行吗?
mask.ts
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
let trimmed = input.value.replace(/\s+/g, '');
mask.spec.ts
@Component({
template: `
<input type="text" dobMask />
`,
})
class TestdobMaskComponent {}
describe('dobMask', () => {
let component: TestdobMaskComponent;
let fixture: ComponentFixture<TestdobMaskComponent>;
let inputEl: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestdobMaskComponent],
});
fixture = TestBed.createComponent(TestdobMaskComponent);
component = fixture.componentInstance;
inputEl = fixture.debugElement.query(By.css('input'));
});
it('should auto populate dash when reach 6 characters', () => {
const input = inputEl.nativeElement as HTMLInputElement;
});
});
尝试:
it('should auto populate dash when reach 6 characters', () => {
const input = inputEl.nativeElement as HTMLInputElement;
input.dispatchEvent(new KeyboardEvent('keydown', { key: ' ' }));
// put a console.log in onKeyDown to make sure it is triggered.
fixture.detectChanges();
// grab a new reference
const newInputEl = fixture.debugElement.query(By.css('input')) as HTMLInputElement;
// trimmed is a local variable to the function so I don't know how you're going to test it
// expect the space got trimmed
expect(newInputEl.nativeElement.value).toEqual("");
});