angularfiletypescriptunit-testingjasmine

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?


Solution

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