jest:React Native设备信息:本机模块.RNDeviceInfo为空

7lrncoxx  于 2022-11-25  发布在  React
关注(0)|答案(2)|浏览(171)

我正在对React Native 0.68、jest/29.0和节点18进行第一次jest测试。测试用例是对函数进行的单元测试:

import helper from "./helper";

it ('describe isHex ', () => {
    const num = "13ad";
    expect(helper.isHex(num)).toBe(true);
    const num1 = "12z";
    expect(helper.isHex(num1)).toBe(false);
})

下面是help.js中的函数isHex:

import DeviceInfo from 'react-native-device-info';
...
isHex : (num) => {
    return Boolean(num.match(/^0x[0-9a-f]+$/i))
  },

yarn jest抛出以下有关DeviceInfo(未在被测函数中使用)的错误:

● Test suite failed to run

    react-native-device-info: NativeModule.RNDeviceInfo is null. To fix this issue try these steps:

应用程序在模拟器中运行良好,没有错误。问题似乎只与jest有关。
下面是package.json的一部分:

"devDependencies": {
    "@babel/core": "^7.18.9",
    "@babel/plugin-proposal-private-methods": "^7.18.6",
    "@babel/plugin-transform-flow-strip-types": "^7.18.9",
    "@babel/runtime": "^7.18.9",
    "@react-native-community/eslint-config": "^3.0.3",
    "babel-jest": "^28.1.3",
    "eslint": "^8.20.0",
    "jest": "^29.0.0",
    "metro-react-native-babel-preset": "^0.71.3",
    "react-test-renderer": "17.0.2"
  },
  "jest": {
    "preset": "react-native",
    "cacheDirectory": "./cache",
    "setupFiles": [
      "<rootDir>/jest.setup.js"
    ],
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "transform": {
      "^.+\\.(js|jsx)$": "babel-jest"
    },
    "transformIgnorePatterns": []
  }
kiz8lqtg

kiz8lqtg1#

这是你需要模拟软件包的地方,在你的测试文件中导入之后,这样做

jest.useFakeTimers();

    // this should work
    jest.mock('react-native-device-info', () => () => jest.fn());

    // or you can try this
     jest.mock('react-native-device-info', () => ({
  
  default: jest.fn(),

}));

希望能有所帮助,尽管怀疑吧

uidvcgyl

uidvcgyl2#

请务必关闭以前的应用程序捆绑包。

相关问题