TL;DR;
If you want to mock Platform.Version in Jest (or any other class where you need to mock the result of getter), you can write the code below to override the getter
const Platform = jest.requireActual('Platform')
Object.defineProperty(Platform, 'Version', {
get: () => 13,
})
Overview
I wanted to write a unit test written in jest for my react-native app that stores Platform.Version for analytics purposes.
Issue
According to @types/react-native, Platform.Version returns a number | string type. Since I want to store it in string format, I've written the code below to always get the string.
const platformVersion = Platform.Version.toString()
The Problem is, in Jest, with react-native preset, Platform.Version returns undefined.
That means, when I run the unit test for my method, it fails because I'm trying to call toString() of undefined.
First Attempt
I thought to myself, "well, that's easy. I just need to mock the value of Platform.Version"
So I wrote a code like this in my jest code.
beforeEach(() => {
jest.mock('Platform', () => {
const Platform = jest.requireActual('Platform')
Platform.Version = 13
return Platform
})
})
But when I run the test code, I get the following error.
TypeError: Cannot set property Version of #<Object> which has only a getter
It seems that I can't just replace a result of getter with a value.
Second (and Final) Attempt
After hours of googling, I've found that only reliable way of mocking getter is by actually mocking a getter (duh!).
So, I went back to my javascript 101, and overwritten the getter method of the Platform.Version
const Platform = jest.requireActual('Platform')
Object.defineProperty(Platform, 'Version', {
get: () => 13,
})
After that, all my tests has passed. I've grabbed my evening tea and went to sleep peacefully.
Top comments (1)
This does not work.
Platformis not a module. Its an export fromreact-native