How to mock a File with a big size in JavaScript for testing purposes?

Viewed 7380

I've implemented a test case for my upload component which shows error if file.size more than 1 mb.

Is there a way to monkeypatch file size with jest or just js for getting test failing without creating the file like this?

const file = new File(
  [new Blob(['1'.repeat(1024 * 1024 + 1)], { type: 'image/png' })],
  'darthvader.png'
)
1 Answers

You can simply use Object.defineProperty to override the original getter, it's configurable:

const file = new File([""], 'darthvader.png');
Object.defineProperty(file, 'size', { value: 1024 * 1024 + 1 })
console.log( file.size ); // 1048577

Related