Mock React Native Dimensions

Habib Ridho
Aug 29, 2017 · 2 min read

React Native (RN) is a great tool for developing mobile application and Jest to me is a really straightforward testing tool for it. If you are yet to use Jest to test your RN app, I recommend you to read this article to get a picture of how good it is.


Everything is good with Jest and me, testing my component’s functions, testing actions and reducer, taking snapshots, etc. Until I test a component that use RN’s Dimensions API.

// MyComponent.js
import React, { Component } from "react"
import { Dimensions, Text, View } from "react-native"
...
const { width, height } = Dimensions.get("screen")
class MyComponent extends Component {
...
render() {
//use the width and height somewhere here
...
}
}
export default MyComponent// MyComponent.test.js
import React from "react"
import MyComponent from "./MyComponent"
test("MyComponent default render", () => {
const component = renderer.create(<MyComponent/>)
let tree = component.toJSON()
expect(tree).toMatchSnapshot()
})

I run the test and it failed because:

Invariant Violation: No dimension set for key screen

However, if I change the dimensions type from screen to window the test would succeed. So it seems theDimensions API is not mocked entirely in the RN version that I used.

Manual Mock

Here is where manual mock comes into play. The first thing to do is defining the mock itself. I create a folder named __mocks__ which adjacent to my node_modules folder and make a mock file Dimensions.js .

// Dimensions.js inside __mocks__ folder
"use strict";
const Dimensions = {
get: jest.fn().mockReturnValue({width: 100, height:100})
}
module.exports = Dimensions

And in my test file:

// MyComponent.test.js
...
jest.mock("Dimensions")
import MyComponent from "./MyComponent"
...

What I do here is telling jest module system to use mockedDimensions that I created instead of the one from the react-native module. By doing this, we can test our component without touching the real implementation of Dimensions API. This method could also be useful if we got another API or Component inside our tested component that need to be mocked.

)

Habib Ridho

Written by

Tech Enthusiast. Product Engineer at GoPay.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade