[英]jest : react-native-device-info: NativeModule.RNDeviceInfo is null
I am doing my very first jest test for a React Native 0.68, jest/29.0 and nodes 18. The test case is a unit test on a function:我正在对 React Native 0.68、jest/29.0 和节点 18 进行我的第一个玩笑测试。测试用例是对 function 的单元测试:
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);
})
Here is the function isHex in helper.js:这是 helper.js 中的 function isHex:
import DeviceInfo from 'react-native-device-info';
...
isHex : (num) => {
return Boolean(num.match(/^0x[0-9a-f]+$/i))
},
The yarn jest
throws error about DeviceInfo (not being used in function being tested) below: yarn jest
抛出关于 DeviceInfo 的错误(未在正在测试的 function 中使用)如下:
● Test suite failed to run
react-native-device-info: NativeModule.RNDeviceInfo is null. To fix this issue try these steps:
The app runs fine in emulator without error.该应用程序在模拟器中运行良好,没有错误。 The problem seems with
jest
only.这个问题似乎只是
jest
。
Here is part of package.json:这是 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": []
}
this is where you need to mock the package, after imports in your test file, do this这是您需要模拟 package 的地方,在您的测试文件中导入后,执行此操作
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(),
}));
hope it helps.希望能帮助到你。 feel free for doubts
随时怀疑
Do make sure that you close the Previous Bundle of App.请确保关闭上一个应用程序包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.