Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine unit test for file size with TypeScript in Angular

Searching for best practice how to test File size on input type="file" change event.

Right now my test spec looks like this:

it('attach file with too large size', () => {
  const file: File = {
    name: 'filename',
    type: 'image/png',
    size: 8242880,
    lastModified: 1,
    lastModifiedDate: new Date(),
    webkitRelativePath: '',
    msClose: () => {},
    msDetachStream: () => {},
    slice: (): Blob => null,
  };
  const event = { target: { files: [file] } };

  component.onFileChange(event); // file validation happens into it too

  const error = control.getError('file_size');
  expect(error).toBeTruthy();
});

Is there better way how to set File size property with TypeScript? When I am trying to setting size property directly to File object, it's not allowed because size property is read-only.

const file = new File([''], 'filename', { type: 'image/png' });
file.size = 8242880; // TS error

Current way how I am mocking File object where I need to define all File object properties for me isn't looking very beautiful, but can't find any better way. Any ideas?

like image 385
Toms Tumshais Avatar asked Aug 08 '18 10:08

Toms Tumshais


2 Answers

You can use Object.defineProperty to overwrite the size property.

/** Creates a "1TB" file given the file name. */
function getHugeFile(name: string) : File {
  const file = new File([''], name);
  Object.defineProperty(
      file, 'size', {value: Math.pow(1024, 4), writable: false});
  return file;
}
like image 129
E. Sun Avatar answered Sep 20 '22 07:09

E. Sun


If you wanted to resolve the TS error, here is the ways,

interface IFile extends File {
    size: number;
}

const file: IFile = new File([''], 'filename', { type: 'image/png' });
file.size = 8242880; // Works..
like image 33
Thaadikkaaran Avatar answered Sep 22 '22 07:09

Thaadikkaaran