Open swuecho opened 7 months ago
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FileUploadComponent } from './file-upload.component';
import { FileUploadService } from './file-upload.service';
import { of } from 'rxjs';
describe('FileUploadComponent', () => {
let component: FileUploadComponent;
let fixture: ComponentFixture<FileUploadComponent>;
let fileUploadService: jasmine.SpyObj<FileUploadService>;
beforeEach(() => {
const fileUploadServiceSpy = jasmine.createSpyObj('FileUploadService', ['uploadFile']);
TestBed.configureTestingModule({
declarations: [FileUploadComponent],
providers: [
{ provide: FileUploadService, useValue: fileUploadServiceSpy }
]
});
fixture = TestBed.createComponent(FileUploadComponent);
component = fixture.componentInstance;
fileUploadService = TestBed.inject(FileUploadService) as jasmine.SpyObj<FileUploadService>;
});
it('should create the component', () => {
expect(component).toBeTruthy();
});
it('should set the selectedFile when onFileChange is called', () => {
const mockFile = new File(['file content'], 'filename.txt');
const event = { target: { files: [mockFile] } };
component.onFileChange(event);
expect(component.selectedFile).toEqual(mockFile);
});
it('should call uploadFileService.uploadFile when uploadFile is called with a selected file', () => {
const mockFile = new File(['file content'], 'filename.txt');
component.selectedFile = mockFile;
fileUploadService.uploadFile.and.returnValue(of('mock response'));
component.uploadFile();
expect(fileUploadService.uploadFile).toHaveBeenCalledWith(mockFile);
});
it('should not call uploadFileService.uploadFile when uploadFile is called without a selected file', () => {
component.uploadFile();
expect(fileUploadService.uploadFile).not.toHaveBeenCalled();
});
// Add more test cases as needed
});
import { Observable, fromEvent } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
function uploadFile(file: File, uploadUrl: string, httpClient: HttpClient): Observable<any> {
const fileInput = file
return new Observable({
const reader = new FileReader();
return new Observable((observer) => {
// Use FileReader.onloadend to handle the load event and read the file content
reader.onloadend = () => {
const fileContent = reader.result as ArrayBuffer;
const formData = new FormData();
formData.append('file', new Blob([fileContent], { type: 'application/octet-stream' }));
httpClient.post(uploadUrl, formData).subscribe(
(data) => {
observer.next(data);
observer.complete();
},
(error) => observer.error(error)
);
};
// Start reading the file as an ArrayBuffer
reader.readAsArrayBuffer(file);
});
} else {
// If no file is selected, emit an error
return new Observable((observer) => {
observer.error('No file selected');
});
}
})
);
}