Javier Olivieri
Javier Olivieri

Reputation: 61

TypeError: Cannot read properties of undefined (reading 'get')

Hi I'm trying to mock react-native modules, for example Dimensions.get, Stylesheet.create, Platform.OS, etc. I tried all the ways I found but none of them work, it seems like it doesn't detect the mocks for react-native, but the mocks from other libs work fine, like react-native-device-info. For example this and its variants don't work:

const Dimensions = {
  get: jest.fn().mockReturnValue({width: 100, height:100})
}

Upvotes: 2

Views: 3788

Answers (1)

Alexis G
Alexis G

Reputation: 17

I had the same problem. Here is how i resolved it (credit to my senior developer).

Problem :

My console was displaying this error :

Error Message

Solution 1:

I added the code below into my test file.

    jest.mock("react-native-status-bar-height", () => "height");
    jest.mock("react-native-status-bar-height", () => ({
        getStatusBarHeight: jest.fn().mockReturnValue(54),
    }));

    it("renders correctly", () => {
        const elem = renderer.create(<MyComponent />).toJSON();
        expect(elem).toMatchSnapshot();
    });

Solution 2:

I added the code below in my jest.config.js, this code can be also placed into the packages.json under "Jest" according where you decided to write your configuration.

    transformIgnorePatterns: [
        "<rootDir>/node_modules/(?!(@?react-native|react-native-status-bar- 
          height)",
    ]

I would say the solution 2 is cleaner, and no need to repeat it for each test, but solution 1, you can choose the value of the Status Bar.

Hope this helped !

Upvotes: 0

Related Questions