我有一个 Angular 4 组件,它有一个 <input>
类型 file
.我想创建一个 Jasmine 测试来验证事件处理程序在输入字段接收到文件时被调用。
这是组件:
<div>
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".xls, .xlsx" style="padding-left: 5px">
</div>
这是事件处理程序:
fileChange(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
// save the file to the backend - this behaviour is tested in a different test
}
}
这是我到目前为止的测试用例,从 Stackoverflow 上的各种答案(例如 these answers 中的一些答案)拼凑而成,这些答案似乎在 Angular 2 中有效,但在 Angular 4 中无效:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('file change event should arrive in handler', () => {
let input = fixture.debugElement.query(By.css('input[type=file]')).nativeElement;
input.value = {name: 'excel'};
input.dispatchEvent(new Event('input'));
// check that the event handler has been called
spyOn(component, 'fileChange');
expect(component.fileChange).toHaveBeenCalled();
});
问题是 Karma 显示 SecurityError: The operation is insecure.
对于 input.value = {name: 'excel'};
行.有没有另一种方法可以手动分配输入字段的值,或者至少让它发送一个由 fileChange
处理的事件? ?
最佳答案
Is there another way to manually assign the value of the input field
出于安全原因,您不能为 input[type="file"]
赋值。
or at least get it to send an event that is handled by fileChange
您可以在 spyOn
之后触发 change
事件:
spyOn(component, 'fileChange');
input.dispatchEvent(new Event('change'));
expect(component.fileChange).toHaveBeenCalled();
关于angular - 测试当文件输入接收到数据时调用事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46730935/