Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
)
like image 332
Vadim Shvetsov Avatar asked May 12 '20 23:05

Vadim Shvetsov


People also ask

How do you mock a blob file?

fake File: var blob = new Blob([""], { type: 'text/html' }); blob["lastModifiedDate"] = ""; blob["name"] = "filename"; var fakeF = blob; You can fill in the values as you see fit. You can fill the blob with whatever you need.

How do you mock a file in jest?

In Jest, Node. js modules are automatically mocked in your tests when you place the mock files in a __mocks__ folder that's next to the node_modules folder. For example, if you a file called __mock__/fs. js , then every time the fs module is called in your test, Jest will automatically use the mocks.

What is mocking in unit testing Javascript?

Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.


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
like image 69
Kaiido Avatar answered Oct 01 '22 20:10

Kaiido