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:
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:
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:
● 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.
Here is part of 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": []
}
CodePudding user response:
this is where you need to mock the package , after imports in your test file, do this
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