I'm very new to Angular. What I am trying to acheive is write a test for an onChange() event of a file uploader component. I do not know how programmatically simulate the change event. Can I create an event (e), associate it with a DOM element and file and call onChange(e)? How do I programmatically associate a file and DOM element with an event? Or maybe I'm approaching this all wrong and I should be doing something else. Maybe the code below will make it clearer. Any help/insights would be greatly appreciated. cheers!
file-upload.html // file uploader component
<div class="input-group input-group-sm mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" id="inputGroupFile01"
(change)="onChange($event)" formControlName="file" accept=".csv,.xlsx">
<label #chooseFileText class="custom-file-label" for="inputGroupFile01"></label>
</div>
</div>
file-upload.ts // code to be tested
onChange(event) {
this.file = event.target.files[0];
if (this.file != null) {
this.chooseFileText.nativeElement.innerHTML = this.file.name;
} else {
this.chooseFileText.nativeElement.innerHTML = "";
}
}
file-upload.spec.ts // test fixture
it('should call onChange', () => {
const e = new Event('');
// How d I associate e with the DOM element?
component.file = new File(['foo', 'bar'], 'foobar.csv');
// how do I set the file above with e?
component.onChange(e);
// Expect the following conditions below:
// component.chooseFileText.nativeElement.innerHTML = component.file.name; (if component.file is null)
// component.chooseFileText.nativeElement.innerHTML = ""; (if component.file is null)
});