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处理的事件? 解决方法
出于安全原因,您无法为输入[type =“file”]指定值.
您可以在spyOn之后触发更改事件: spyOn(component,'fileChange'); input.dispatchEvent(new Event('change')); expect(component.fileChange).toHaveBeenCalled(); Plunker Example (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |