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



我有一个 Angular 4 组件,它有一个 file 类型的<input>。我想创建一个 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 上的各种答案(例如其中一些答案)拼凑而成,这些答案似乎在 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();
});

问题是业力显示线路input.value = {name: 'excel'};SecurityError: The operation is insecure.。有没有另一种方法可以手动分配输入字段的值或至少让它发送由fileChange处理的事件?

有没有其他方法可以手动分配输入字段的值

由于安全原因,无法为input[type="file"]赋值。

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

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

spyOn(component, 'fileChange');
input.dispatchEvent(new Event('change'));
expect(component.fileChange).toHaveBeenCalled();

普伦克示例

describe("A suite is just a function", function() {
  var a;
  it("and so is a spec", function() {
    a = true;
    expect(a).toBe(true);
  });
});

最新更新