Jef*_*ell 5 javascript unit-testing event-handling karma-jasmine angular
使用 karma 和 jasmine 执行测试脚本时,我在命令窗口中遇到错误问题,我也使用 Angular 7。我已经为监听粘贴事件的电话指令编写了单元测试。我的代码中没有错误,但当我运行测试时,我收到此错误。测试将成功运行并通过,我也得到了我想要的代码覆盖率,但每次运行单元测试时都会继续弹出此错误。
ERROR in /phone/phone-mask.directive.
spec.ts(124,7): error TS2345: Argument of type '{
clipboardData: DataTransfer;
}'
is not assignable to parameter of type 'ClipboardEventInit'.
Object literal may only specify known properties, and 'clipboardData' does not exist in type 'ClipboardEventInit'.
Run Code Online (Sandbox Code Playgroud)
我尝试在测试中创建一个事件以将数据复制到剪贴板并可能填充 ClipboardData 变量,但这不起作用。它首先看到该值不存在,然后构建它并成功运行。
电话指令打字稿
@HostListener('paste', ['$event'])
onPaste($event: ClipboardEvent) {
$event.preventDefault();
let pastedInput: string = $event.clipboardData
.getData('text/plain')
.replace(/\D/g, ''); // get a digit-only string
if (pastedInput.length === 0) {
pastedInput = '';
} else if (pastedInput.length <= 3) {
pastedInput = pastedInput.replace(/^(\d{0,3})/, '($1)');
} else if (pastedInput.length <= 6) {
pastedInput = pastedInput.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
} else {
pastedInput = pastedInput.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');
}
this._phoneControl.control.setValue(pastedInput.substring(0, 14), {emitEvent: false});
}
Run Code Online (Sandbox Code Playgroud)
电话测试规格
it('should test that paste event triggers and sets value to empty string if value is empty', () => {
fixture.detectChanges();
const dt1 = new DataTransfer();
const event1 = new ClipboardEvent('paste', {clipboardData: dt1});
event1.clipboardData.setData('text/plain', '');
inputEl.nativeElement.dispatchEvent(event1);
fixture.whenStable().then(() => {
expect(component.demForm.controls.PHONE.value).toEqual('');
});
});
Run Code Online (Sandbox Code Playgroud)
我正在寻求帮助来解决此错误以及如何阻止该错误在测试运行器 cli 中显示。先感谢您。
小智 2
您可以在规范文件中手动调用 onPaste 函数,并可以操作“事件”。像下面这样;
const event = {
target : {
value: null
},
clipboardData : {
types: ['text/plain'],
getData(a: string) {
return 'test';
}
}
};
comp.onPaste(event);
expect(event.target.value).toEqual('test');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7379 次 |
| 最近记录: |