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

标签 angular unit-testing typescript jasmine

我有一个 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();

Plunker Example

关于angular - 测试当文件输入接收到数据时调用事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46730935/

相关文章:

angular - 如何将表单放入单独的文件中 Angular 4

unit-testing - Angular2 : Can't test component with templateUrl using TestBed. compileComponent()

typescript - 将 Typescript 接口(interface)中的所有属性设为可选

带有路由选项卡的 Angular Material Routed 对话框

angular - 错误 : Initializers are not allowed in ambient contexts

angular - 如何重命名 Angular 项目?

unit-testing - 纽约市报道显示不正确的行号

unit-testing - 可以为普遍使用的依赖项使用服务定位器吗?

angular - eslint 缩进错误 "Expected indentation of 2 spaces but found 4.", Angular 14

angular - 在加载未登录的组件时卡住