Cec*_*lya 6 unit-testing jasmine typescript angular
我有一个<input>类型的Angular 4组件file.我想创建一个Jasmine测试,用于验证在输入字段接收文件时是否调用事件处理程序.
这是组件:
<div>
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".xls, .xlsx" style="padding-left: 5px">
</div>
Run Code Online (Sandbox Code Playgroud)
这是事件处理程序:
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
}
}
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止的测试案例,从Stackoverflow上的各种答案(例如其中一些答案)拼凑而成,似乎在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();
});
Run Code Online (Sandbox Code Playgroud)
问题在于Karma显示SecurityError: The operation is insecure.该线input.value = {name: 'excel'};.是否有另一种方法可以手动分配输入字段的值,或者至少让它发送一个由fileChange?处理的事件?
是否有另一种手动分配输入字段值的方法
input[type="file"]由于安全原因,您无法分配值.
或者至少让它发送一个由fileChange处理的事件
您可以change在以下后触发事件spyOn:
spyOn(component, 'fileChange');
input.dispatchEvent(new Event('change'));
expect(component.fileChange).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2987 次 |
| 最近记录: |