测试文件输入接收数据时调用事件处理程序

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?处理的事件?

yur*_*zui 9

是否有另一种手动分配输入字段值的方法

input[type="file"]由于安全原因,您无法分配值.

或者至少让它发送一个由fileChange处理的事件

您可以change在以下后触发事件spyOn:

spyOn(component, 'fileChange');
input.dispatchEvent(new Event('change'));
expect(component.fileChange).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

Plunker示例

  • 我可以做这么多,但它没有解决如何测试 fileChange 函数中的所有逻辑,例如 `const reader = new FileReader();` `const target = &lt;HTMLInputElement&gt;evt.target;` `if (target .files &amp;&amp; target.files.length) {const file = target.files[0]; reader.readAsDataURL(文件);reader.onload = () =&gt; { this.getUploadFormGroup(index, isReq).patchValue({...}); `fileChange` 中的这些行是我发现最难测试的东西,并且监视 `fileChange` 不允许我们在那里测试它们。如果你能展示如何测试这些,你就会得到赏金。 (2认同)