How to use Jest with React Native

后端 未结 3 1648
情书的邮戳
情书的邮戳 2020-12-14 08:17

The testing section of the docs for React Native suggest that Jest is the official way to do unit tests. However, they don\'t explain how to get it setup. Running Jest witho

相关标签:
3条回答
  • 2020-12-14 08:57

    For newer versions of jest, setting it up for react-native is very easy.

    Install jest using

    npm install --save-dev jest-cli babel-jest
    

    In package.json, add this

    "scripts": {
      "start": "babel-node ./server/server.js",
      "import-data": "babel-node ./scripts/import-data-from-parse.js",
      "update-schema": "babel-node ./server/schema/updateSchema.js",
      "test": "jest",
      "lint": "eslint ."
    },
    "jest": {
      "haste": {
        "defaultPlatform": "ios",
        "platforms": [
          "ios",
          "android"
        ],
        "providesModuleNodeModules": [
          "react-native"
        ]
      }
    },
    

    You might only need to add lines related to jest

    Now you can use

    npm test
    

    to run jest.

    Refer to f8app's github repo to find more about this.

    0 讨论(0)
  • 2020-12-14 09:06

    I got Jest to work for my React Native application, and it is running tests without any problem on files with ES6 and ES7 transforms.

    To get Jest to work, I followed these steps:

    1. Copied the jestSupport folder from the React Native master repo to my react-native folder in node_modules.

    2. Edited the "jest" line in my packages.json to points to the files in the jestSupport folder

    The "jest" line in my packages.json now looks lke this:

    "jest": {
      "scriptPreprocessor": "<rootDir>/node_modules/react-native/jestSupport/scriptPreprocess.js",
      "setupEnvScriptFile": "<rootDir>/node_modules/react-native/jestSupport/env.js",
      "testFileExtensions": [
        "js"
      ],
      "unmockedModulePathPatterns": [
        "source-map"
      ]
    },
    
    0 讨论(0)
  • 2020-12-14 09:06

    As of React Native v0.37.0, Jest is part of the new app template.

    In a new app you can run tests right away:

    $ react-native init MyAwesomeApp
    $ cd MyAwesomeApp
    $ npm test
    ...
    Tests:       2 passed
    
    0 讨论(0)
提交回复
热议问题