如何在Jasmine单元测试中测试Angular自定义指令的键盘事件
如何在Jasmine中测试mask.ts的输入处理逻辑?
首先得先修正你现有测试代码里的一个小问题:你的TestBed.configureTestingModule里没有声明dobMask指令,测试组件根本找不到这个指令,所以第一步要把它加进declarations数组里。
接下来,我们分场景来测试(你提到了自动补全短横线,我会覆盖当前代码的去空格逻辑,以及你提到的补全短横线功能):
测试输入内容的去空格逻辑
这是你当前代码片段里实现的核心功能,我们可以这样编写测试用例:
@Component({ template: ` <input type="text" dobMask /> `, }) class TestdobMaskComponent {} describe('dobMask', () => { let component: TestdobMaskComponent; let fixture: ComponentFixture<TestdobMaskComponent>; let inputEl: HTMLInputElement; beforeEach(() => { TestBed.configureTestingModule({ declarations: [TestdobMaskComponent, dobMask], // 务必添加你的指令 }); fixture = TestBed.createComponent(TestdobMaskComponent); component = fixture.componentInstance; inputEl = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement; fixture.detectChanges(); // 触发变更检测,确保指令完成初始化 }); it('should remove all spaces from input value', () => { // 模拟用户输入带空格的内容 inputEl.value = '1990 01 01'; // 触发input事件,触发指令的onKeyDown方法 inputEl.dispatchEvent(new Event('input')); fixture.detectChanges(); // 验证处理后的值是否去掉了所有空格 expect(inputEl.value).toBe('19900101'); }); });
测试自动补全短横线的逻辑(针对你提到的核心需求)
假设你的mask.ts里补全短横线的完整逻辑类似这样(比如处理日期格式YYYY-MM-DD):
@HostListener('input', ['$event']) onKeyDown(event: KeyboardEvent) { const input = event.target as HTMLInputElement; let trimmed = input.value.replace(/\s+/g, '').replace(/-/g, ''); // 先清除空格和已有横线 // 补全短横线逻辑 if (trimmed.length >= 4) { trimmed = `${trimmed.slice(0,4)}-${trimmed.slice(4)}`; } if (trimmed.length >= 7) { trimmed = `${trimmed.slice(0,7)}-${trimmed.slice(7)}`; } input.value = trimmed.slice(0,10); // 限制总长度为10位 }
对应的测试用例可以这样写:
it('should auto add first dash when input reaches 4 characters', () => { inputEl.value = '1990'; inputEl.dispatchEvent(new Event('input')); fixture.detectChanges(); expect(inputEl.value).toBe('1990-'); }); it('should auto add second dash when input reaches 6 characters', () => { inputEl.value = '199001'; inputEl.dispatchEvent(new Event('input')); fixture.detectChanges(); expect(inputEl.value).toBe('1990-01-'); }); it('should format full date string correctly', () => { inputEl.value = '19900101'; inputEl.dispatchEvent(new Event('input')); fixture.detectChanges(); expect(inputEl.value).toBe('1990-01-01'); });
关键测试要点说明
- 必须把
dobMask指令加入测试模块的declarations,否则测试组件无法识别该指令 - 通过
dispatchEvent(new Event('input'))模拟用户输入行为,触发指令的监听方法 - 每次触发事件后调用
fixture.detectChanges(),确保Angular完成视图和数据更新 - 直接断言input元素的
value属性,验证处理结果是否符合预期
内容的提问来源于stack exchange,提问作者SKL
相关产品推荐
相关产品推荐

