question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Jest transpiling from "jest/preprocessor.js" broken

See original GitHub issue

Environment

Run react-native info in your terminal and paste its contents here.

React Native Environment Info:
    System:
      OS: macOS High Sierra 10.13.6
      CPU: x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
      Memory: 178.39 MB / 16.00 GB
      Shell: 3.2.57 - /bin/bash
    Binaries:
      Node: 10.9.0 - ~/.nvm/versions/node/v10.9.0/bin/node
      npm: 6.2.0 - ~/.nvm/versions/node/v10.9.0/bin/npm
      Watchman: 4.7.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
      Android SDK:
        Build Tools: 23.0.1, 25.0.0, 25.0.1, 25.0.2, 25.0.3, 26.0.1, 26.0.2, 27.0.3, 28.0.1, 28.0.3
        API Levels: 19, 23, 25, 26, 27, 28
    IDEs:
      Android Studio: 3.1 AI-173.4907809
      Xcode: 10.0/10A255 - /usr/bin/xcodebuild
    npmPackages:
      react: ^16.6.0-alpha.8af6728 => 16.6.0-alpha.8af6728
      react-native: ^0.57.4 => 0.57.4
    npmGlobalPackages:
      create-react-native-app: 1.0.0
      react-native-cli: 2.0.1

Description

We have recently upgraded from v0.55.4 to v0.57.4 using react-native-git-upgrade. As part of this upgrade the majority of our jest tests have broken due to transpiling errors.

Full jest config

  "jest": {
    "preset": "react-native",
    "setupTestFrameworkScriptFile": "<rootDir>/jestSetup.js",
    "moduleNameMapper": {
      "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
      "^[@./a-zA-Z0-9$_-]+\\.(png|gif|jpg|ttf)$": "RelativeImageStub"
    },
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
    },
    "testMatch": [
      "<rootDir>/src/**/*.test.js?(x)"
    ],
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "collectCoverageFrom": [
      "**/src/**/*.js"
    ],
    "coveragePathIgnorePatterns": [
      "src/helpers/networkDebugger",
      "/node_modules/"
    ],
    "coverageThreshold": {
      "global": {
        "branches": 90,
        "functions": 90,
        "lines": 90,
        "statements": 90
      }
    }
  },

Jest setup file

import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import fetch from 'jest-fetch-mock'

global.fetch = fetch

const mockedDate = new Date('2018-01-01T12:13:14')
const _Date = Date
global.Date = jest.fn(() => mockedDate)
global.Date.UTC = _Date.UTC
global.Date.parse = _Date.parse
global.Date.now = _Date.now
global.WebSocket = jest.fn(() => ({ addEventListener: jest.fn(), send: jest.fn() }))
global.FileReader = jest.fn(() => ({ addEventListener: jest.fn(), readAsText: jest.fn() }))
global.requestAnimationFrame = jest.fn()

configure({ adapter: new Adapter() })

Some of the errors we are seeing are related to imports/exports and class arrow methods. e.g.

export class MyComponent extends Component {
  static propType = { optionalProp: PropTypes.bool },
  doSomething = () => { ... }
  render () { ... }
}

Fails with the error TypeError: Cannot read property 'default' of undefined. Once changed to

export class MyComponent extends Component {
  static propType = { optionalProp: PropTypes.bool },
  doSomething () { ... }
  render () { ... }
}

It is fine.

Reproducible Demo

Let us know how to reproduce the issue. Include a code sample, share a project, or share an app that reproduces the issue using https://snack.expo.io/. Please follow the guidelines for providing a MCVE: https://stackoverflow.com/help/mcve

I’ve setup a public repo which contains some example broken tests and how those tests can be fixed temporarily. However the underlying issue is the transpiling. https://github.com/lewnelson/react-native-jest-example

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:16
  • Comments:35 (10 by maintainers)

github_iconTop GitHub Comments

20reactions
letsgojunocommented, Nov 8, 2018

We have also ran into this issue on 0.57.3. From an initial investigation I can make it work by disabling inlineRequires in the jest preprocessor https://github.com/facebook/react-native/blob/master/jest/preprocessor.js#L58

This is as far as I got. To get around the issue for now we are binding the methods in the constructor.

14reactions
adamu-saikocommented, Mar 27, 2019
transform: {
  '^.+\\.js$': '<rootDir>/jest/preprocessor.js',
},
/**
 * Your own [temporary?] transform for React Native
 */
const generate = require('@babel/generator').default
const transformer = require('metro-react-native-babel-transformer')
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction')
const metroBabelRegister = require('metro-babel-register')

metroBabelRegister([])

module.exports = {
  process(src, file) {
    const { ast } = transformer.transform({
      filename: file,
      options: {
        ast: true,
        dev: true,
        enableBabelRuntime: false,
        experimentalImportSupport: false,
        hot: false,
        inlineRequires: false,
        minify: false,
        platform: '',
        projectRoot: '',
        retainLines: true,
        sourceType: 'unambiguous',
      },
      src,
      plugins: metroBabelRegister.config.plugins,
    })

    return generate(
      ast,
      {
        code: true,
        comments: false,
        compact: false,
        filename: file,
        retainLines: true,
        sourceFileName: file,
        sourceMaps: true,
      },
      src,
    ).code
  },

  getCacheKey: createCacheKeyFunction([
    __filename,
    require.resolve('metro-react-native-babel-transformer'),
    require.resolve('@babel/core/package.json'),
  ]),
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Code Transformation
Jest passes files through code transformation on demand (for instance when a require or import is evaluated). This process, also known as "transpilation", ......
Read more >
Can not run unit tests through jest framework because of ...
Core problem is that ts-jest (jest-preset-angular is based on ts-jest) does not transpile JS files. So I need something to do that work....
Read more >
jest-environment-node | Yarn - Package Manager
Fixes for global built in objects in jest-environment-node . Create mock objects in the vm context instead of the parent context. .babelrc is...
Read more >
cannot find module 'elasticsearch' from 'setup-jest.js'
I'm trying to downgrade "@elastic/elasticsearch" to from "8.4.2" to version "7.6.0", but the app is not able to start, and seem the listEntities...
Read more >
[Solved]-React Native with Typescript and Jest is broken after ...
If I use "presets": ["react-native"] then production/development is broken but tests are working.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found