React-native-screens: How to use with the jest preset "react-native"?

Created on 12 Sep 2020  路  3Comments  路  Source: software-mansion/react-native-screens

The jest preset from React Native mocks the UIIManager.getViewManagerConfig method:

jest.mock('../Libraries/ReactNative/UIManager', () => ({
  getViewManagerConfig: jest.fn(name => {
    if (name === 'AndroidDrawerLayout') {
      return {
        Constants: {
          DrawerPosition: {
            Left: 10,
          }
        }
      }
    }
  })
})

And so this creates an error when calling enableScreen, since UIManager.getViewManagerConfig(name) will fail like when name is RNScreen. If name is RNScreen, the method will return undefined and then an error will appear in the tests:

console.error
    Screen native module hasn't been linked. Please check the react-native-screens README for more details

The tests do pass and work, although this error is not ideal. Is there a way to use the preset without this warning? I was imaging just patching the preset and extending it to be:

getViewManagerConfig: jest.fn(name => {
  if (name === 'AndroidDrawerLayout') {
    return {
      Constants: {
        DrawerPosition: {
          Left: 10,
        }
      }
    }
  }
  if (name === 'RNScreen') {
    return {}
  }
})

Although I don't know if this is ideal!

Most helpful comment

@bitttttten You can remove the error by mocking the enableScreens() method.

// __mocks__/react-native-screens.js
export const enableScreens = jest.fn();

All 3 comments

@bitttttten You can remove the error by mocking the enableScreens() method.

// __mocks__/react-native-screens.js
export const enableScreens = jest.fn();

Oh okay great! I didn't know if it was safe to mock or not. Thanks @codecog !

Another way, directly inside the unit test:

jest.mock('react-native-screens', () => ({
  ...jest.requireActual('react-native-screens'),
  enableScreens: jest.fn(),
}));
Was this page helpful?
0 / 5 - 0 ratings