Mock React Native Dimensions

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.