DEV Community

Jesse Katsumata
Jesse Katsumata

Posted on

Mocking Platform.Version with Jest

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,
  })
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
  })
})
Enter fullscreen mode Exit fullscreen mode

But when I run the test code, I get the following error.

TypeError: Cannot set property Version of #<Object> which has only a getter
Enter fullscreen mode Exit fullscreen mode

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,
  })
Enter fullscreen mode Exit fullscreen mode

After that, all my tests has passed. I've grabbed my evening tea and went to sleep peacefully.

Top comments (1)

Collapse
 
pke profile image
Philipp Kursawe

This does not work. Platform is not a module. Its an export from react-native