Learning Objectives
By the end of this article, you'll learn how to:
Create a file upload component in Angular
Handle file selection using the
changeeventStore the selected file in the component
Write unit tests for file input controls
Simulate file selection in Angular unit tests
HTML Template
<input
id="myFile"
type="file"
(change)="onFileSelected()"
#fileInput
/>
Whenever the user selects a file, the change event calls the onFileSelected() method.
Component
import { Component } from '@angular/core';
@Component({
selector: 'app-input-file',
templateUrl: './input-file.component.html'
})
export class InputFileComponent {
uploadedFile!: File;
onFileSelected(): void {
const inputNode = document.querySelector('#myFile') as HTMLInputElement;
if (inputNode.files && inputNode.files.length > 0) {
this.uploadedFile = inputNode.files[0];
console.log(this.uploadedFile);
}
}
}
How It Works
When the user selects a file:
The component locates the file input element.
The browser stores the selected file(s) in the
filescollection.The first file is assigned to the
uploadedFileproperty.
Although this works, Angular recommends avoiding direct DOM access where possible.
Writing the Unit Test
The browser normally populates the files property, so during unit testing we need to mock it ourselves.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { InputFileComponent } from './input-file.component';
describe('InputFileComponent', () => {
let component: InputFileComponent;
let fixture: ComponentFixture<InputFileComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [InputFileComponent]
}).compileComponents();
fixture = TestBed.createComponent(InputFileComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should store the selected file', () => {
const file = new File(
['Dummy Content'],
'sample.txt',
{
type: 'text/plain'
}
);
const input = fixture.nativeElement.querySelector('#myFile');
Object.defineProperty(input, 'files', {
value: [file]
});
input.dispatchEvent(new Event('change'));
expect(component.uploadedFile).toEqual(file);
});
});
Understanding the Test
Step 1: Create a Mock File
const file = new File(
['Dummy Content'],
'sample.txt',
{
type: 'text/plain'
}
);

Join the conversation! Your thoughts help the community grow.