【发布时间】:2018-03-25 15:36:16
【问题描述】:
我有一个 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 为行 input.value = {name: 'excel'}; 显示 SecurityError: The operation is insecure.。是否有另一种方法可以手动分配输入字段的值,或者至少让它发送由fileChange 处理的事件?
【问题讨论】:
-
你有没有想过这个?我也一直在到处搜索,似乎找不到可靠的解决方案。
-
不,我放弃了测试。我只是再次查看它(现在使用 Angular 5.0.1),现在我坚持将文件分配给输入,因为
Value being assigned to HTMLInputElement.files does not implement interface FileList.不过,没有时间进一步调试它。如果你愿意,我可以将我当前的代码添加到问题中。 -
我的库 ngx-material-file-input 也有类似的问题,使用单元测试重现清除字段(使用角度 v7)时出现的错误。似乎测试引擎仍然有局限性,并且没有实际的解决方案(据我所知)来确保文件在本机文件输入中,作为
FileList对象(我哭了)。我尝试使用fakeAsync/tick等待DOM 刷新,但没有运气。我还尝试多次添加fixture.detectChanges()来运行另一个生命周期检查,但再次没有运气。所以我最终哈维
标签: angular unit-testing typescript jasmine