Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test uploader #34

Open
swuecho opened this issue Nov 24, 2023 · 2 comments
Open

test uploader #34

swuecho opened this issue Nov 24, 2023 · 2 comments

Comments

@swuecho
Copy link
Owner

swuecho commented Nov 24, 2023

import { TestBed, inject } from '@angular/core/testing';
import {
  HttpClientTestingModule,
  HttpTestingController,
} from '@angular/common/http/testing';
import { FileUploadService } from './file-upload.service';

describe('FileUploadService', () => {
  let service: FileUploadService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [FileUploadService],
    });

    service = TestBed.inject(FileUploadService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should upload a file', () => {
    const fileInputId = 'fileInput';
    const uploadUrl = 'your-upload-url';
    const mockFile = new File(['file content'], 'test-file.txt', {
      type: 'text/plain',
    });

    const resultData = { success: true };

    service.uploadFile(fileInputId, uploadUrl).subscribe((data) => {
      expect(data).toEqual(resultData);
    });

    const req = httpMock.expectOne(uploadUrl);

    // Assert that the request is a POST request with the correct headers
    expect(req.request.method).toBe('POST');
    expect(req.request.headers.get('Content-Type')).toBe(
      'application/octet-stream'
    );

    // Respond to the request with mock data
    req.flush(resultData);
  });

  it('should handle an error when no file is selected', () => {
    const fileInputId = 'fileInput';
    const uploadUrl = 'your-upload-url';

    service.uploadFile(fileInputId, uploadUrl).subscribe(
      () => {},
      (error) => {
        expect(error.message).toEqual('No file selected');
      }
    );

    // No HTTP request should be made in this case
    httpMock.expectNone(uploadUrl);
  });
});

@swuecho
Copy link
Owner Author

swuecho commented Nov 24, 2023

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
});

@swuecho
Copy link
Owner Author

swuecho commented Nov 24, 2023

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');
        });
      }
    })
  );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant