我有一个简单的组件,可以将粘贴事件处理为表单输入。
表格:
float
现在我正在尝试测试它,它看起来像这样:
this.searchForm = this.formBuilder.group({
query: [ null, [Validators.required] ]
});
onPaste(event) {
event.preventDefault();
const formattedQuery = event.clipboardData.getData('text/plain')
.split(/,?[\r\n\t]+\s?/)
.join(', ')
.replace(/,\s?$/g, '');
this.searchForm.get('query').setValue(formattedQuery);
}
但结果我得到了
it('should reformat pasted data', () => {
const queryField = fixture.debugElement.query(By.css('input[type="search"]'));
queryField.nativeElement.dispatchEvent(new ClipboardEvent('paste', {
dataType: 'text/plain',
data: '123\r123'
}));
fixture.detectChanges();
expect(queryField.nativeElement.value).toBe('123, 123');
// also tried expect(component.searchForm.get('query').value).toBe('123, 123');
});
如果我Expected '' to be '123, 123'
它显示输入,但为什么它不处理console.log(queryField.nativeElement)
事件?
new ClipboardEvent('paste')
您可以在此处找到完整的组件https://stackblitz.com/edit/angular-cp9yhx?file=app%2Fhello.component.ts
我的单元测试出了什么问题?
答案 0 :(得分:2)
试试这个:
it('should reformat pasted data', () => {
component.onPaste(new ClipboardEvent('paste', {
dataType: 'text/plain',
data: '123\r123'
}));
expect(queryField.nativeElement.value).toBe('123, 123');
});
甚至
it('should reformat pasted data', () => {
component.onPaste(new ClipboardEvent('paste', {
dataType: 'text/plain',
data: '123\r123'
}));
expect(component.searchForm.get('query').value).toBe('123, 123');
});
答案 1 :(得分:1)
这对我有用:
it('should trim pasted data', () => {
const initialValue = 'test ';
fixture.detectChanges();
// Setting initial value
const el = inputElement.nativeElement;
el.value = initialValue;
// Setting up event data
const pasteData = new DataTransfer();
pasteData.setData('text', initialValue);
// Creating event
const pasteEvent = new ClipboardEvent('paste', {
clipboardData: pasteData
} as any);
// Dispatching event
el.dispatchEvent(pasteEvent);
expect(el.value).toEqual('test');
});