How to mock read-only property in jest

kozo yamagata
2 min readMay 27, 2020

--

When we write JavaScript/TypeScript testing, jest is the de facto standard testing library. Jest allows us to write a good testing code with a simple and modern mocking system.

Like an API call, when we don’t want to use an actual system, we can write the code like:

But I assume that the mocking target is not always reassignable such as File.prototype.size
I’m going to explain this problem with a function that validates an image file size.

The function checks if that the size is lower than 10,000 bytes, and returns boolean. Therefore, in the test case, we have to change the size property forcefully, but it’s a read-only property. TypeScript compiler throws an error for the violation and testing won’t be finished successfully.

Fortunately, jest has functionality that solves the problem with the jest.spyOn().

jest.spyOn() is mainly a function that will observe if the property has been accessed or not. But you can mock the returning value of it too even it’s a read-only property!

I forgot the existence of mockReturnValue() 😭 Where have you been!?

--

--