react-nativebabeljsts-jestreact-native-testing-library

babel config setup for testing


I have setup testing in my react native app with typescript using React-native-testing-library. I have configured my babel,config.js as below. There is an odd issue though.

module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    '@babel/preset-react',
    '@babel/preset-typescript',
  ],
  sourceMaps: true,
  plugins: [
    [
      'module:react-native-dotenv',
      {
        moduleName: '@env',
        path: '.env',
        blacklist: null,
        whitelist: null,
        safe: false,
        allowUndefined: true,
      },
    ],
    // ['@babel/plugin-transform-private-methods', {loose: true}],
  ],
};

When I uncomment ['@babel/plugin-transform-private-methods', {loose: true}], The tests do not work and the FlatList does but when I do comment it out the FlatList gives me the below error and the tests do not work?

ERROR TypeError: Cannot read property 'getItem' of undefined

My FLatList works fine on my main branch where I have not added the testing.


Solution

  • I was running into the same issue. I was able to run my tests and use a FlatList in my code without issues thanks to this thread and comment:

    https://github.com/facebook/react-native/issues/29084#issuecomment-1463493342

    I updated my babel.config.js to this (stripped of some irrelevant plugins):

    module.exports = {
      presets: [
        'babel-preset-expo',
        '@babel/preset-typescript',
        'module:metro-react-native-babel-preset',
      ],
      plugins: [
        ['@babel/plugin-transform-flow-strip-types', { loose: true }],
        ['@babel/plugin-proposal-class-properties', { loose: true }],
        ['@babel/plugin-proposal-private-methods', { loose: true }],
      ],
    };