How to solve Jest + React Native error ReferenceError? - react-native

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.

Related

vue preset.json vue create message

I am creating a vue project with :
vue create --preset ./ my-app
preset.json is
{
"useTaobaoRegistry": true,
"packageManager": "npm",
"presets": {
"preset1": {
"useConfigFiles": true,
"plugins": {
"#vue/cli-plugin-babel": {},
"#vue/cli-plugin-pwa": {},
"#vue/cli-plugin-router": {
"historyMode": true
},
"#vue/cli-plugin-vuex": {},
"#vue/cli-plugin-eslint": {
"config": "base",
"lintOn": [
"save"
]
},
"#vue/cli-plugin-unit-mocha": {},
"#vue/cli-plugin-e2e-cypress": {}
},
"cssPreprocessor": "dart-sass"
}
}
}
When I execute this command, I get the following error
ERROR TypeError: Cannot set property '#vue/cli-service' of undefined
TypeError: Cannot set property '#vue/cli-service' of undefined
at Creator.create (/usr/local/lib/node_modules/#vue/cli/lib/Creator.js:97:40)
at async create (/usr/local/lib/node_modules/#vue/cli/lib/create.js:72:3)
Is it an error of preset json?
Try to install all dependencies with one of this commands:
yarn install
or
npm install
looks like you did not install all dependencies of your project so '#vue/cli-service' is not found.

React Native tests failing, missing babel transforms

I want to test a React Native application that I've created based on the default guides, so it's very simple and has not had any changes w.r.t. the initial test configuration. The only difference seems to be that it's using npm instead of yarn (so it has a package-lock.json).
Here is the package.json:
{
"name": "foo",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.5.2",
"react-navigation": "^4.0.10",
"react-navigation-stack": "^1.10.3"
},
"devDependencies": {
"#babel/core": "^7.7.4",
"#babel/runtime": "^7.7.4",
"#react-native-community/eslint-config": "^0.0.5",
"babel-jest": "^24.9.0",
"eslint": "^6.7.1",
"jest": "^24.9.0",
"license-checker": "^25.0.1",
"metro-react-native-babel-preset": "^0.57.0",
"react-test-renderer": "16.9.0"
},
"jest": {
"preset": "react-native"
}
}
The test file __tests__/App-test.js is very simple (and auto-generated):
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
I get this error:
➜ npm test
> jest
FAIL __tests__/App-test.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/node_modules/#foo/bar/src/main.js:24
export function milliseconds(timeoutInMilliseconds) {
^^^^^^
SyntaxError: Unexpected token 'export'
Now, I don't really understand why it wouldn't work "out of the box". Other guides mention the same steps, too.
Adding a .babelrc with:
{
"presets": ["react-native"]
}
produces the error:
Cannot find module 'babel-preset-react-native' from '/'
- If you want to resolve "react-native", use "module:react-native"
at Function.module.exports [as sync] (node_modules/resolve/lib/sync.js:74:15)
at resolveStandardizedName (node_modules/#babel/core/lib/config/files/plugins.js:101:31)
at resolvePreset (node_modules/#babel/core/lib/config/files/plugins.js:58:10)
at loadPreset (node_modules/#babel/core/lib/config/files/plugins.js:77:20)
at createDescriptor (node_modules/#babel/core/lib/config/config-descriptors.js:154:9)
at node_modules/#babel/core/lib/config/config-descriptors.js:109:50
at Array.map (<anonymous>)
at createDescriptors (node_modules/#babel/core/lib/config/config-descriptors.js:109:29)
at createPresetDescriptors (node_modules/#babel/core/lib/config/config-descriptors.js:101:10)
at presets (node_modules/#babel/core/lib/config/config-descriptors.js:47:19)
There is already a babel.config.js file with the following contents (as suggested here):
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
What should I do? I've seen this question but the React App has not been upgraded and is not missing anything, AFAICT. Note that when I create a completely new app with the init script, the tests run fine.
You are using "react-navigation": "^4.0.10" which uses react-native-gesture-handler. Jest does not know about it. You have to mock react-native-gesture-handler and add react-navigation to transformIgnorePatterns or use react-native-jest-mocks.
Some examples of mocking react-native-gesture-handler can be found here: https://github.com/software-mansion/react-native-gesture-handler/issues/344
Add "files": ["jest/setup.js"]," inside package.json. Also transformIgnorePatterns must include react-navigation-stack, #react-native-community, react-native-gesture-handler and react-navigation.
package.json:
"files": [
"jest/setup.js"
],
"jest": {
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
"setupFiles": ["./jest/setup.js"],
"testPathIgnorePatterns": [
"/node_modules/"
],
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-navigation-stack|#react-native-community|react-native-gesture-handler|react-navigation|#react-navigation/.*)"
]
}
jest/setup.js:
import { NativeModules as RNNativeModules } from "react-native";
RNNativeModules.UIManager = RNNativeModules.UIManager || {};
RNNativeModules.UIManager.RCTView = RNNativeModules.UIManager.RCTView || {};
RNNativeModules.RNGestureHandlerModule = RNNativeModules.RNGestureHandlerModule || {
State: { BEGAN: "BEGAN", FAILED: "FAILED", ACTIVE: "ACTIVE", END: "END" },
attachGestureHandler: jest.fn(),
createGestureHandler: jest.fn(),
dropGestureHandler: jest.fn(),
updateGestureHandler: jest.fn(),
};
RNNativeModules.PlatformConstants = RNNativeModules.PlatformConstants || {
forceTouchAvailable: false
};
jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper');
Now run jest and it should pass the test. I have created a repo with an example RN 0.61 app using react-navigation that has jest test passing: https://github.com/clytras/RNJestTest
Or you can try react-native-jest-mocks but I haven't tried it with RN 0.61 yet.

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

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"
]
},

Changes to Vue components do not trigger Jest to rerun

Here is a snippet of my package.json file:
{
...
"scripts": {
"test:unit": "jest --no-cache",
...
},
"jest": {
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.vue$": "vue-jest"
}
}
}
Then I started unit test in the watch mode:
npm run test:unit -- --watchAll
When I make any change to my test file ProgressBar.spec.js, I can see that the test has been rerun.
import { shallowMount } from '#vue/test-utils'
import ProgressBar from '../ProgressBar.vue'
describe('ProgressBar', () => {
...
}
The problem is, when I make changes to my Vue component ProgressBar.vue, Jest does not rerun my test as expected.
The fix I figured out is to do with Jest's configuration. Here is the addition of moduleFileExtensions to the Jest configuration in my package.json file:
{
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.vue$": "vue-jest"
}
}
}
Then I started unit test in the watch mode:
npm run test:unit -- --watchAll
Now whenever I make any change to my Vue components, Jest will rerun the unit tests as expected.
Hope it helps.

react-native cannot read property 'bindings' of null

I tried to run a react-native simulator.
However, this error came out in the simulator:
Failed to load bundle(http://localhost:8081/index.bundle?
platform=ios&dev=true&minify=false)
with error:(/Users/sugawarasyuta/Desktop/albums/index.js:
Cannot read property 'bindings' of null(null))
I double‐checked my code syntax. But I feel like this is not about that. Do you know how to solve this error?
Here are my files:
index.js
import React from 'react';
import { AppRegistry,View } from 'react-native';
import Header from './src/components/header';
import AlbumList from './src/components/AlbumList';
//Create a component
const App = () => (
<View>
<Header headerText= {'albums'} />
<AlbumList />
</View>
);
AppRegistry.registerComponent('albums', () => App );
AlbumList.js
import React,{Component}from 'react';
import {View, Text} from 'react-native';
import axios from 'axios';
class AlbumList extends Component {
componentWillMount(){
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => console.log(response));
}
render(){
return(
<View>
<Text>AlbumList!!!</Text>
</View>
);
}
}
export default AlbumList;
These are terminal statements:
/usr/bin/codesign --force --sign - --entitlements /Users/sugawarasyuta/Desktop/albums/ios/build/Build/Intermediates.noindex/albums.build/Debug-iphonesimulator/albums.build/albums.app.xcent --timestamp=none /Users/sugawarasyuta/Desktop/albums/ios/build/Build/Products/Debug-iphonesimulator/albums.app
/Users/sugawarasyuta/Desktop/albums/ios/build/Build/Products/Debug-iphonesimulator/albums.app: resource fork, Finder information, or similar detritus not allowed
Command /usr/bin/codesign failed with exit code 1
** BUILD FAILED **
The following build commands failed:
CodeSign build/Build/Products/Debug-iphonesimulator/albums.app
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/albums.app
Launching org.reactjs.native.example.albums
org.reactjs.native.example.albums: 8385
This is my package.json. Are those dependencies correct?
{
"name": "albums",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"axios": "^0.18.0",
"babel-plugin-transform-es2015-arrow-functions": "^6.22.0",
"react": "16.3.1",
"react-native": "^0.56.0"
},
"devDependencies": {
"#babel/preset-env": "^7.0.0-beta.53",
"babel-jest": "23.0.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react-native": "4.0.0",
"eslint-config-rallycoding": "^3.2.0",
"jest": "23.1.0",
"react-test-renderer": "16.3.1"
},
"jest": {
"preset": "react-native"
}
}
I upgraded "babel-preset-react-native" from "4.0.0" to "^5.0.1" and another error came out:
error: bundling failed: SyntaxError:
/Users/sugawarasyuta/Desktop/albums/index.js: Unexpected token (11:3)
10 | const App = () => {
> 11 | <Header headerText= {'albums'} />
| ^
12 |
13 | };
at Parser.raise
(/Users/sugawarasyuta/Desktop/albums/node_modules
/#babel/core/node_modules/babylon/lib/index.js:776:15)
at Parser.unexpected
(/Users/sugawarasyuta/Desktop/albums/node_modules/
#babel/core/node_modules/babylon/lib/index.js:2079:16)
at Parser.parseExprAtom (/Users/sugawarasyuta/Desktop/albums/node_modules/#babel/core/node_modules/babylon/lib/index.js:3157:20)
at Parser.parseExprSubscripts (/Users/sugawarasyuta/Desktop/albums/node_modules/#babel/core/node_modules/babylon/lib/index.js:2757:21)
at Parser.parseMaybeUnary (/Users/sugawarasyuta/Desktop/albums/node_modules/#babel/core/node_modules/babylon/lib/index.js:2736:21)
at Parser.parseExprOps (/Users/sugawarasyuta/Desktop/albums/node_modules/#babel/core/node_modules/babylon/lib/index.js:2643:21)
at Parser.parseMaybeConditional (/Users/sugawarasyuta/Desktop/albums/node_modules/#babel/core/node_modules/babylon/lib/index.js:2615:21)
at Parser.parseMaybeAssign (/Users/sugawarasyuta/Desktop/albums/node_modules/#babel/core/node_modules/babylon/lib/index.js:2562:21)
at Parser.parseExpression (/Users/sugawarasyuta/Desktop/albums/node_modules/#babel/core/node_modules/babylon/lib/index.js:2515:21)
at Parser.parseStatementContent (/Users/sugawarasyuta/Desktop/albums/node_modules/#babel/core/node_modules/babylon/lib/index.js:4076:21)
BUNDLE [ios, dev] ../../index.js ░░░░░░░░░░░░░░░░ 0.0% (0/1), failed.
I feel like this is not because of syntax error simply, but cause of dependencies. Do you know how can I fix it?
Without any further information, I suspect you need to update babel-preset-react-native.
When upgrading to 0.56, make sure to bump your
babel-preset-react-native package.json dependency to ^5.0.1 or newer.
https://github.com/facebook/react-native/releases
For React Native 0.57
When upgrading to React Native 0.57, follow these steps to fix this issue:
Upgrade the version of React in the package.json to 16.5
Change the babel-preset dependency from "babel-preset-react-native": "^5" to "metro-react-native-babel-preset": "^0.45.0"
Change the .babelrc configuration to:
{
"presets": ["module:metro-react-native-babel-preset"]
}
Run rm -rf node_modules/ to remove your old modules
Run npm install to get a fresh node_modules/
Run react-native upgrade to upgrade your config files
Run rm -rf android/build/ ios/build/ to get rid of your old compiled apps
Run your app again, it should work!
Source for the first steps
REACT NATIVE 0.57 FRESH INSTALLS iOS ANDROID
I did a fresh install of react native from react-native init projectName
The package.json
{
"name": "JesteeTestee",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "^16.5.2",
"react-native": "0.57.4"
},
devDependencies": {
"babel-jest": "23.6.0",
"jest": "23.6.0",
"metro-react-native-babel-preset": "^0.47.0",
"react-test-renderer": "16.6.0-alpha.8af6728"
},
"jest": {
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
}
}
}
As you can see it is the latest, current version of RN#0.57.4 and metro-react-native-babel-preset#0.47.0.
Also the default .babelrc
{
"presets": ["module:metro-react-native-babel-preset"]
}
Simply added the following to the Jest part of the package.json;
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
}
Given the hours I spent finding this today, if you are doing a fresh install and hit a snag just delete the project, start again and try this simple step only.
Tested for react-native run-ios and run-android.
FOR REACT-NATIVE VERSION 0.57 OR MORE
On babel.config.js, simply change presets as below
"presets": ["module:metro-react-native-babel-preset"]
This worked for me after trying many different solutions