在我的 Karma-Jasmine 测试中,我必须测试我的onPaste方法。
onPaste 方法:
onPaste(event: any): void {
const pastedText = event.clipboardData.getData('text/plain');
// some stuff
}
Run Code Online (Sandbox Code Playgroud)
我的单元测试:
it('should do something', () => {
const queryField = fixture.debugElement.query(By.css('input[type="search"]')).nativeElement;
queryField.dispatchEvent(new ClipboardEvent('paste', {
dataType: 'text/plain',
data: '325435956\r325435956',
}));
// some stuff
})
Run Code Online (Sandbox Code Playgroud)
我使用 Chrome 运行测试,但new ClipboardEvent()在 Chrome 中创建ClipboardEvent对象 where clipboardDataisnull并event.clipboardData.getData('text/plain')引发错误:
Uncaught TypeError: Cannot read property 'getData' of null
Run Code Online (Sandbox Code Playgroud)
它不会在 Firefox 中发生,所以如果我使用karma-firefox-launcher它可以正常工作,但我必须使用 Chrome。所以,我有一些想法如何解决它。
第一个想法是创建ClipboardEvent对象并覆盖 clipboardData 属性:
const pasteEvent …Run Code Online (Sandbox Code Playgroud)