加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:16:24 所属栏目:安全 来源:网络整理
导读:我有一个Angular 4组件,它有一个 input类型文件.我想创建一个Jasmine测试,用于验证在输入字段接收文件时是否调用事件处理程序. 这是组件: div input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".xls,.xlsx" style="padd
我有一个Angular 4组件,它有一个< 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上的各种答案拼凑而成(例如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:操作不安全.对于行input.value = {name:’excel’} ;.是否有另一种方法可以手动分配输入字段的值,或者至少让它发送由fileChange处理的事件?

解决方法

Is there another way to manually assign the value of the input field

出于安全原因,您无法为输入[type =“file”]指定值.

or at least get it to send an event that is handled by fileChange

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

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

Plunker Example

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读