React Native Jest Test Suite Fails: TypeError: Cannot read property 'propTypes' of undefined - react-native

I am trying to use the Jest test suite that comes with the app created with react-native init but I am getting this error when I run npm test:
TypeError: Cannot read property 'propTypes' of undefined
at propTypes (node_modules/react-native/Libraries/Animated/src/createAnimatedComponent.js:178:31)
at Object.oldCreate [as createAnimatedComponent] (node_modules/react-native/jest/setup.js:79:23)
at Object.Animated (node_modules/react-navigation-stack/lib/commonjs/views/BorderlessButton.tsx:5:28)
at Object.<anonymous> (node_modules/react-navigation-stack/lib/commonjs/views/TouchableItem.tsx:19:1)
This is the code of the test that is failing...
import 'react-native';
import React from 'react';
import App from '../App';
import renderer from 'react-test-renderer';
beforeAll(() => {
jest.mock('#react-native-community/async-storage');
});
it('renders correctly', () => {
renderer.create(<App />);
});
Not sure how to resolve it, several errors I was getting i managed to fix by either mocking the module (like AsyncStorage, geolocation, NetInfo) or adding their package name to the jest object in package.json like so:
"jest": {
"preset": "react-native",
"transformIgnorePatterns": [
"node_modules/(?!(react-native|react-native-barcode-builder|react-native-maps|react-native-android-open-settings|react-native-qrcode-scanner|react-native-permissions|react-native-camera|react-native-google-maps-directions|jsbarcode|react-native-picker-select|react-native-datepicker|react-native-touch-id|react-native-screens|react-native-gesture-handler|react-navigation|react-navigation-stack)/)"
]
}
My babel.config file just has...
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
Am I missing some step in the configuration? Not sure if it helps but I am using React Native v0.60.5. Thanks in advance.

Adding the right mocks for react-native-gesture-handler fixed it for me. I had to add:
"setupFiles": [
"./node_modules/react-native-gesture-handler/jestSetup.js"
],
You can find more documentation here:
https://kmagiera.github.io/react-native-gesture-handler/docs/getting-started.html#testing

You should define jest config like this in your package.json.
"jest": {
"preset": "react-native",
"collectCoverage": true,
"testEnvironment": "jsdom",
"moduleDirectories": [
"node_modules",
"components"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
"setupFiles": [
"<rootDir>/jest/setup.js"
],
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native)"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"/jest",
"assets",
"lib"
],
"modulePathIgnorePatterns": [
"package",
"assets",
"lib"
]
},

Related

React Native - How to enable jsx syntax in js files

I tried use react-navigation (6.5.8) drawer navigator in a react-native web application, but I get 3 error messages. It seams the jsx syntax not allowed in js files. How should I enable it?
I tried tsconfig.json
{
"extends": "#tsconfig/react-native/tsconfig.json",
"include": [
"src",
"/node_modules/**/*"
],
"compilerOptions": {
"jsx": "react",
"allowJs": true,
},
}
And babel.config.js
module.exports = {
presets: ['#babel/preset-env', '#babel/preset-react', 'module:metro-react-native-babel-preset'],
plugins: ['react-native-reanimated/plugin']
};
But not helped yet.
Here is my git repo:
https://github.com/pzoli/WebDemoProject-drawer

How to properly import ES6+ React Native components with Jest ESM

Using Jest w/ESM for a React Native project, and can't figure out how to properly import modules that have ESM in them. Importing the react-native-phone-number-input module, I get Jest encountered an unexpected token:
/repo/node_modules/react-native-phone-number-input/lib/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import React, { PureComponent } from "react";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
So far the only way I have been able to get it running is mocking:
jest.unstable_mockModule('react-native-phone-number-input', () => ({
default: jest.fn(),
}));
Here is my Jest config (in package.json):
{
"haste": {
"defaultPlatform": "ios",
"platforms": [
"android",
"ios",
"native"
]
},
"resetMocks": true,
"testEnvironment": "node",
"testMatch": [
"**/src/**/*.(spec|test).[tj]s?(x)"
],
"preset": "ts-jest/presets/default-esm",
"transform": {
"^.+\\.js$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!((jest-)?react-native|#?react-native(-community)?)/)"
],
"extensionsToTreatAsEsm": [
".ts",
".tsx"
],
"globals": {
"ts-jest": {
"useESM": true
}
},
"setupFiles": [
"<rootDir>/node_modules/react-native/jest/setup.js"
],
"setupFilesAfterEnv": [
"#testing-library/jest-native/extend-expect"
]
}

(JEST/VueJS) Cannot use import statement outside a module

I'm using windows10 and when I run Jest on VUEJS project for tests i've got this :
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { shallowMount } from '#vue/test-utils';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1086:14)
Itried a lot of soltions, but still not working Here is my jest.config.js file:
module.exports = {
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
transform: {
"^.+\\.js$": "babel-jest",
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
},
moduleNameMapper: {
"^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
},
snapshotSerializers: [
"<rootDir>/node_modules/jest-serializer-vue"
],
testMatch: [
'<rootDir>/tests/**/*.spec.(js|jsx|ts|tsx)|<rootDir>/**/__tests__/*.(js|jsx|ts|tsx)'
],
transformIgnorePatterns: ['<rootDir>/node_modules/']
};

Vue Jest test suite failed to run: SyntaxError: Unexpected identifier

I've set up my Jest, and it runs properly. But when I create a test for a file that contains a spreadoperator the test suite fails.
I'm using Vue configured from the CLI with Jest.
What I have tried
I've tried adding the babel-plugin-transform-object-rest-spread as a plugin to the babel.config.js but this had no result.
I also tried adding the #babel/plugin-proposal-object-rest-spread as a plugin to the babel.config.js but this also had no result.
babel.config.js:
module.exports = {
presets: ["#babel/preset-env", "#vue/app"]
};
package.json (jest part):
"jest": {
"collectCoverage": true,
"collectCoverageFrom": [
"**/*.{js,vue}",
"!**/node_modules/**"
],
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"moduleNameMapper": {
"^#/(.*)$": "<rootDir>/src/$1"
},
"transform": {
"^.+\\.js?$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
}
}
component.spec.js:
import { shallowMount } from '#vue/test-utils';
import Component from '#/views/xx/x/Component.vue';
import Vue from 'vue';
import BootstrapVue from 'bootstrap-vue';
Vue.use(BootstrapVue);
describe('About component', () => {
let wrapper;
beforeEach(() => {
wrapper = shallowMount(Component);
});
test('is a Vue instance', () => {
expect(wrapper.isVueInstance()).toBeTruthy();
});
});
Error:
FAIL src/__tests__/views/x/Component.spec.js
● Test suite failed to run
D:\projects\project\project-frontend\node_modules\#babel\runtime-corejs2\helpers\esm\objectSpread.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _Object$getOwnPropertyDescriptor from "../../core-js/object/get-own-property-descriptor";
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
at src/views/xx/x/Component.vue:670:49
at Object.<anonymous> (src/views/xx/x/Component.vue:810:3)
In package.json
make sure this pluging"babel-core" version up to ^7.0.0-0 that like under.
"devDependencies": {
"babel-core": "^7.0.0-0"
}
The final step for me was to provide correct env variables in jest config an explanation why it needs it may be found here.Also make sure babel packages installed
Sharing whole config
// jest
process.env.VUE_CLI_BABEL_TARGET_NODE = true;
process.env.VUE_CLI_BABEL_TRANSPILE_MODULES = true;
module.exports = {
verbose: true,
roots: ["<rootDir>/src/", "<rootDir>/spec/"],
moduleFileExtensions: ['js', 'vue','json'],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
},
transform: {
"^.+\\.js$": "babel-jest",
"^.+\\.vue$": "vue-jest",
},
snapshotSerializers: [
"jest-serializer-vue"
]
}
// in package json
"#babel/core": "^7.9.6",
"#babel/plugin-transform-runtime": "^7.9.6",
"#babel/preset-env": "^7.9.5",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^25.4.0",

How to solve Jest + React Native error ReferenceError?

I have been trying to run yarn test in React Native project
Here is my jest in package.json
"jest": {
"preset": "react-native"
},
Here is my .babelrc
{
"presets": [
"es2015",
"stage-0",
"react-native"
],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs","transform-class-properties"]
}
}
}
The error is
ReferenceError: styleObject is not defined
at Object.<anonymous> (node_modules/react-native-camera-kit/src/CameraScreen/CameraKitCameraScreenStyleObject.ios.js:1:16)
at Object.<anonymous> (node_modules/react-native-camera-kit/src/CameraScreen/CameraKitCameraScreenBase.js:317:1)
at Object.<anonymous> (node_modules/react-native-camera-kit/src/CameraScreen/CameraKitCameraScreen.ios.js:3:1)
Any idea how to solve this? I have been searching everywhere still not found a correct solution.