mercredi 7 août 2019

How to load a file into an Angular Test?

i'm trying to test an extension validator using Karma and Jasmine with latest Angular version. I have a service that receives a File and checks its extension and MIME type, this is the method signature:

public validateFileType(file: File, validTypes: string[]): Observable<boolean>

As you can see the method receives a File, so i want to either load some files i have in a /testing folder or create a file with '.doc'/'.xls'/'.pdf' extension (i would like to use the first approach, already tried creating a .doc, .xls file and the signature numbers does not match any real file). But its impossible to load any File as the HttpClient can not be instantiated in a Karma test, i have tried everything i know and searched a lot, any help is really appreciated.

Example

import { TestBed } from '@angular/core/testing';
import { FileValidatorService } from './file-validator.service';


describe('FileValidatorService', () => {
  let service: FileValidatorService;

  beforeEach(() => {
    TestBed.configureTestingModule({ providers: [FileValidatorService] });
    service = TestBed.get(FileValidatorService);
  });

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

  describe('Types', () => {

    it('should be false', () => {
      const content = 'Hello test';
      const data = new Blob([content], { type: 'application/zip' });
      const arrayOfBlob = new Array<Blob>();
      arrayOfBlob.push(data);
      const applicationZip = new File(arrayOfBlob, 'Mock.zip', { type: 'application/zip' });
      service.validateFileType(applicationZip, ['.doc', '.xls']).subscribe((result: boolean) => {
        expect(result).toBeFalsy();
      });
    });
  });

});

This test only works because the file i created generates some random signature code that i don't use so its not recognized and it doesn't match the expected types but is not working as it should.

Aucun commentaire:

Enregistrer un commentaire