Jest Encountered Unexpected token with import statement - react-native

I've tried many fixes based on SO and GH answers but none have worked.
I'm trying to set up Jest and Enzyme for my React Native project but I can't get tests to run. Here's my current test file:
import React from "react";
import { shallow, mount } from "enzyme";
// import MapScreen from "../src/screens/MapView";
describe("MapScreen", () => {
it("should render tab bar icons", () => {
expect(true).toEqual(true); // just to get tests working at all!
});
});
The error:
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:
/Users/TuzMacbookPro2017/Development/QMG-local/APPS/ELECTRO/node_modules/expo/build/environment/validate.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import {
^
SyntaxError: Unexpected token {
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 Object.<anonymous> (node_modules/expo/build/Expo.js:278:1)
My config files:
// jest.config.js
module.exports = {
setupFilesAfterEnv: ["<rootDir>setup-tests.js"],
transformIgnorePatterns: [
"node_modules/(?!(jest-)?react-native|#react-native-community|react-native-elements)"
]
};
// babel.config.js
module.exports = function(api) {
api.cache(true);
return {
presets: ["babel-preset-expo"]
};
};
// setup-tests.js
import Adapter from "enzyme-adapter-react-16";
import { configure } from "enzyme";
import jsdom from "jsdom";
import "react-native";
import "jest-enzyme";
function setUpDomEnvironment() {
const { JSDOM } = jsdom;
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
url: "http://localhost/"
});
const { window } = dom;
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: "node.js"
};
copyProps(window, global);
}
function copyProps(src, target) {
const props = Object.getOwnPropertyNames(src)
.filter(prop => typeof target[prop] === "undefined")
.map(prop => Object.getOwnPropertyDescriptor(src, prop));
Object.defineProperties(target, props);
}
setUpDomEnvironment();
configure({ adapter: new Adapter() });
// package.json
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"eject": "expo eject",
"test": "node ./node_modules/jest/bin/jest.js --watchAll"
},
"jest": {
"preset": "jest-expo",
"testEnvironment": "node",
"globals": {
"__DEV__": true
}
},
"dependencies": {
"#expo/samples": "2.1.1",
"#react-native-community/async-storage": "^1.3.4",
"expo": "^32.0.0",
"native-base": "^2.12.1",
"react": "16.5.0",
"react-dom": "^16.8.6",
"react-native": "0.57",
"react-native-elements": "^1.1.0",
"react-native-geocoding": "^0.3.0",
"react-native-global-font": "^1.0.2",
"react-native-indicators": "^0.13.0",
"react-native-keyboard-aware-scrollview": "^2.0.0",
"react-native-material-dropdown": "^0.11.1",
"react-native-render-html": "^4.1.2",
"react-native-uuid": "^1.4.9",
"react-navigation": "^3.9.1",
"react-redux": "^6.0.1",
"redux": "^4.0.1",
"redux-test-utils": "^0.3.0",
"redux-thunk": "^2.3.0",
"sugar": "^2.0.6"
},
"devDependencies": {
"#babel/preset-react": "^7.0.0",
"babel-preset-expo": "^5.0.0",
"babel-preset-react-native": "^4.0.1",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.12.1",
"fetch-mock": "^7.3.3",
"jest": "^24.8.0",
"jest-enzyme": "^7.0.2",
"jest-expo": "^32.0.0",
"jsdom": "^14.1.0",
"mock-async-storage": "^2.1.0",
"react-test-renderer": "^16.8.6",
"redux-mock-store": "^1.5.3"
},
"private": true,
"rnpm": {
"assets": [
"./assets/fonts"
]
}
}
I can't get even this simple test to run. I have actually been able to get that test to run on a different branch, and copied all the test-related config files from that branch to this one, but I'm still getting this error.
I know there are many posts about this around but none seem to help me. I hope someone can help me get this working! Thanks!

Related

Export namespace should be first transformed by `#babel/plugin-proposal-export-namespace-from`

I get the following error when I want to build my APK.
Export namespace should be first transformed by
#babel/plugin-proposal-export-namespace-from
I need to say that I have imported react-native-gesture-handler in the index.js
and this is my index.js
import 'react-native-gesture-handler';
import {AppRegistry} from 'react-native';
import App from './app/App';
import {name as appName} from './app.json';
import { LogBox } from 'react-native';
LogBox.ignoreAllLogs();
AppRegistry.registerComponent(appName, () => App);
during development mode, I did not get that error.
this is my package.json
{
"name": "blackout",
"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-native-async-storage/async-storage": "^1.17.6",
"#react-native-community/geolocation": "^2.1.0",
"#react-native-community/netinfo": "^9.0.0",
"#react-native-community/viewpager": "^5.0.11",
"#react-navigation/bottom-tabs": "^6.3.1",
"#react-navigation/native": "^6.0.10",
"#react-navigation/native-stack": "^6.6.2",
"#react-navigation/stack": "^6.2.1",
"axios": "^0.27.2",
"es6-template-strings": "^2.0.1",
"jalali-moment": "^3.3.11",
"jwt-decode": "^3.1.2",
"react": "17.0.2",
"react-hook-form": "^7.32.2",
"react-native": "0.68.2",
"react-native-android-open-settings": "^1.3.0",
"react-native-audio-recorder-player": "^3.5.1",
"react-native-device-info": "^9.0.2",
"react-native-element-dropdown": "^2.0.0",
"react-native-fs": "^2.20.0",
"react-native-gesture-handler": "^2.4.2",
"react-native-image-crop-picker": "^0.37.3",
"react-native-image-picker": "^4.8.4",
"react-native-modal": "^13.0.1",
"react-native-reanimated": "^2.9.1",
"react-native-safe-area-context": "^4.3.1",
"react-native-screens": "^3.13.1",
"react-native-size-matters": "^0.4.0",
"react-native-snackbar": "^2.4.0",
"react-native-tab-view": "^3.1.1",
"react-native-vector-icons": "^9.1.0",
"react-native-video": "^5.2.0",
"react-native-webview": "^11.22.2",
"react-redux": "^8.0.2",
"realm": "10.19.5",
"redux": "^4.2.0",
"redux-thunk": "^2.4.1",
"rn-fetch-blob": "^0.12.0"
},
"devDependencies": {
"#babel/code-frame": "^7.16.7",
"#babel/core": "^7.12.9",
"#babel/runtime": "^7.12.5",
"#react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^26.6.3",
"eslint": "^7.32.0",
"jest": "^26.6.3",
"metro-react-native-babel-preset": "^0.67.0",
"react-test-renderer": "17.0.2"
},
"jest": {
"preset": "react-native"
}
}
I really appreciate any help you can provide.
You have to add the 'react-native-reanimated/plugin' to the plugins array.
make sure this Plugin should be the last.
open the babel.config.js in the root of your project and modify it as follow:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
...
'react-native-reanimated/plugin', // This line.
],
};
NOTE: After adding the react-native-reanimated/plugin to your project you may encounter a false-positive "Reanimated 2 failed to create a worklet" error. In most cases, this can be fixed by cleaning the application's cache. Depending on your workflow or favourite package manager that could be done by:
yarn start --reset-cache
npm start -- --reset-cache
expo start -c
For more information
Your babel.config.js should look like
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: ['react-native-reanimated/plugin'],
};
If you have an Expo managed project, your babel.config.js should be looking like this:
module.exports = function (api) {
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
"react-native-reanimated/plugin", // This line.
],
};
};
It seems like there was a breaking change between react-native-reanimated 2.9 and 2.12. The latest version doesn't have a reference to #babel/plugin-proposal-export-namespace-from anymore. To solve this I followed examples I found in this commit.
Add this to babel.config.js:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
...
'react-native-reanimated/plugin',
'#babel/plugin-proposal-export-namespace-from',
],
};
Then run these commands:
yarn add #babel/plugin-proposal-export-namespace-from
yarn start -c
Another possible way is to change ts version to "ES2020" in tsconfig.json.
https://babeljs.io/docs/en/babel-plugin-proposal-export-namespace-from
Run these command
yarn add #babel/plugin-proposal-export-namespace-from -D
Then add the item "'#babel/plugin-proposal-export-namespace-from'" in the plugins array of your babel.config.js file
Example of my babel.config.js:
module.exports = function (api) {
api.cache(true)
return {
presets: ['babel-preset-expo'],
plugins: [
'#babel/plugin-proposal-export-namespace-from',
'react-native-reanimated/plugin'
]
}
}

Jest Testing in React Native (EXPO) .jsx extension not working "React.createElement: type is invalid"

Issue
I'm trying to test using jest, but it looks like my compiler is not handling .jsx files. If I change both of the files extension to js: (App.jsx and App.test.jsx) to (App.JS and App.test.JS), it does work. But I want to be able to use jsx files.
Files
App.jsx
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
</View>
);
}
App.test.jsx
import React from 'react';
// import { render } from '#testing-library/react-native';
import renderer from 'react-test-renderer';
import App from './App';
it('renders correctly', () => {
const tree = renderer.create(<App />).toJSON();
expect(tree.children.length).toBe(1);
// const { toJSON } = render(<App />); // ** THIS DOESN'T WORK EITHER **
// expect(toJSON()).toMatchSnapshot();
});
Console Error
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
package.json
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"eject": "expo eject",
"test": "jest --watch",
"test:debug": "jest",
"test:coverage": "npm test -- --coverage --watchAll",
"test:pr": "npm test -- coverage --ci --silent --changedSince=origin/development --coverageReporters='text' --coverageReporters='lcov'",
"test:all": "npm test -- --coverage --ci --silent --watchAll=false",
"linter": "eslint src",
"linter:fix": "eslint src --fix"
},
"dependencies": {
"#react-native-async-storage/async-storage": "^1.13.0",
"#react-navigation/native": "^5.9.4",
"#reduxjs/toolkit": "^1.5.1",
"babel-jest": "^26.6.3",
"expo": "~41.0.1",
"expo-status-bar": "~1.0.4",
"i18next": "^20.2.2",
"moment": "^2.29.1",
"msw": "^0.28.2",
"node-fetch": "^2.6.1",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-41.0.0.tar.gz",
"react-native-web": "~0.13.12",
"redux": "^4.1.0",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"#babel/core": "^7.9.0",
"#babel/eslint-parser": "^7.14.2",
"#babel/eslint-plugin": "^7.13.16",
"#babel/plugin-proposal-class-properties": "^7.13.0",
"#testing-library/react-native": "^7.2.0",
"#types/jest": "^26.0.23",
"eslint": "^7.26.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.23.0",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0",
"identity-obj-proxy": "^3.0.0",
"jest-expo": "^41.0.0",
"react-test-renderer": "^17.0.2"
},
"jest": {
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(js|jsx)$",
"moduleFileExtensions": [
"js",
"json",
"jsx"
],
"preset": "jest-expo",
"setupFiles": [
"./jestSetup.js"
],
"transform": {
"^.+\\.(js|jsx|mjs)$": "babel-jest"
},
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
}
},
"private": true
}
You need to configure Jest to accept jsx extensions. This is done in the jest section of your package.json file or in your jest.config.js file (if you have both Jest seems to ignore the package.json contents).
Take a look at this: https://levelup.gitconnected.com/setting-up-jest-under-expo-to-work-with-jsx-files-ba35a51bc25a
Here's what worked for me:
$ yarn add --dev babel-jest#latest
then in package.json:
"jest": {
"preset": "jest-expo",
"transformIgnorePatterns": [
"node_modules/(?!((jest-)?react-native|#react-native(-community)?)|expo(nent)?|#expo(nent)?/.*|#expo-google-fonts/.*|react-navigation|#react-navigation/.*|#unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)"
],
"transform": {
"^.+\\.[jt]sx?$": "babel-jest"
}
}

"SyntaxError: Cannot use import statement outside a module" error while testing React Native project with Jest and #testing-library/react-native?

Error I'm getting Anytime I run npm test:
FAIL ./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:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• 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:
/Users/bestes/Desktop/react-native-training/node_modules/react-native-status-bar-height/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Dimensions, Platform, StatusBar } from 'react-native';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/react-native-elements/src/config/index.js:1:1)
My Test:
import 'react-native';
import React from 'react';
import { render } from '#/../testing/test-utils'
import App from './App'
test('should render app component', () => {
const result = render(<App />)
expect(result).toMatchSnapshot()
})
My test-utils.js file:
import React from 'react'
import { render } from '#testing-library/react-native'
import { store } from '#/bootstrap/redux'
import { Provider } from 'react-redux'
const AllTheProviders = ({ children }) => {
return (
<Provider store={store}>
{children}
</Provider>
)
}
const customRender = (ui, options) =>
render(ui, { wrapper: AllTheProviders, ...options })
// re-export everything
export * from '#testing-library/react-native'
// override render method
export { customRender as render }
My package.json file:
{
"name": "ReactNativeTraining",
"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-native-community/geolocation": "2.0.2",
"#react-native-community/masked-view": "0.1.10",
"#react-native-picker/picker": "1.9.10",
"#reduxjs/toolkit": "1.5.0",
"axios": "0.21.1",
"dayjs": "1.10.4",
"lodash": "4.17.20",
"react": "16.13.1",
"react-native": "0.63.2",
"react-native-config": "1.4.2",
"react-native-elements": "3.0.0-alpha.1",
"react-native-geocoding": "0.5.0",
"react-native-gesture-handler": "1.9.0",
"react-native-permissions": "3.0.0",
"react-native-picker-select": "8.0.4",
"react-native-reanimated": "1.13.2",
"react-native-safe-area-context": "3.1.9",
"react-native-screens": "2.17.0",
"react-native-size-matters": "0.4.0",
"react-native-vector-icons": "8.0.0",
"react-navigation": "4.0.2",
"react-navigation-stack": "1.5.4",
"react-navigation-tabs": "2.4.1",
"react-redux": "7.2.2"
},
"devDependencies": {
"#babel/core": "7.12.10",
"#babel/runtime": "7.12.5",
"#react-native-community/eslint-config": "2.0.0",
"#testing-library/jest-native": "4.0.1",
"#testing-library/react-native": "7.2.0",
"babel-jest": "^26.6.3",
"babel-plugin-module-resolver": "4.0.0",
"eslint": "7.18.0",
"jest": "26.6.3",
"metro-react-native-babel-preset": "0.64.0",
"react-test-renderer": "16.13.1"
},
"type": "module",
"jest": {
"verbose": true,
"preset": "react-native",
"setupFilesAfterEnv": ["#testing-library/jest-native/extend-expect"],
"transformIgnorePatterns": [
"node_modules/(?!(react-native",
"#react-native-community/geolocation",
"#react-native-community/masked-view",
"|#react-native-picker/picker",
"|#reduxjs/toolkit",
"|axios",
"|dayjs",
"|lodash",
"|react",
"|react-native",
"|react-native-config",
"|react-native-elements",
"|react-native-geocoding",
"|react-native-gesture-handler",
"|react-native-permissions",
"|react-native-picker-select",
"|react-native-reanimated",
"|react-native-safe-area-context",
"|react-native-screens",
"|react-native-size-matters",
"|react-native-vector-icons",
"|react-navigation",
"|react-navigation-stack",
"|react-navigation-tabs",
"|react-redux",
")/)"
]
}
}
My babel.config.js file:
module.exports = function (api) {
api.cache(true)
const presets = [
'module:metro-react-native-babel-preset'
]
const plugins = [
[
'module-resolver', {
'root': ['./src/'],
'extensions': ['.js', '.ios.js', '.android.js'],
'alias': {
'#': './src/'
}
}
]
]
return {
presets,
plugins
}
}
What I've tried:
Adding "type": "module" to my root level package.json file, which fixed a similar error with exporting,
Adding Transform Ignore Patterns to the Jest key in the package.json file.
I'd added ALL of my dependencies to the transformIgnorePatterns as it kept throwing errors on each one, until I added all and now it throws on react-native modules imports.
[Solved] Work for me
Install below
npm install --save-dev #babel/core
npm install --save-dev #babel/preset-env
after that create the "babel.config.js" file in the root and that content should be as below
module.exports = {
presets: ['#babel/preset-env', '#babel/preset-react'],
env: {
test: {
plugins: ["#babel/plugin-transform-runtime"]
}
}
};

Environment variable not being set in Axios configuration on Expo React Native project

I am trying to use a .env file inside my Expo project root directory with an API URL for Axios requests in a file called axios.ts.
import axios from 'axios';
const Axios = axios.create({
baseURL: process.env.REACT_APP_API_URL
});
Axios.defaults.headers.common['Content-Type'] = 'application/json';
export default Axios;
In order to make it work, I installed the dot-env library as suggested by the official Expo documentation
Here is my package.json
{
"main": "index.js",
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"start-expo": "expo start",
"test": "jest"
},
"dependencies": {
"#react-native-community/masked-view": "^0.1.10",
"#react-native-community/picker": "1.6.0",
"#react-navigation/drawer": "^5.9.0",
"#react-navigation/material-top-tabs": "^5.2.13",
"#react-navigation/native": "^5.7.0",
"#react-navigation/native-stack": "^5.0.5",
"#react-navigation/stack": "^5.9.0",
"axios": "^0.20.0",
"dotenv": "^8.2.0",
"events": "^3.1.0",
"react": "~16.11.0",
"react-dom": "~16.11.0",
"react-native": "~0.62.2",
"react-native-gesture-handler": "~1.6.0",
"react-native-paper": "^3.10.1",
"react-native-reanimated": "~1.9.0",
"react-native-screens": "~2.9.0",
"react-native-tab-view": "^2.14.4",
"react-native-table-component": "^1.2.1",
"react-native-unimodules": "~0.10.0",
"react-native-vector-icons": "^7.0.0",
"react-native-web": "~0.11.7",
"react-native-webview": "9.4.0",
"react-redux": "^7.2.0",
"redux-saga": "^1.1.3"
},
"devDependencies": {
"#babel/core": "~7.9.0",
"#types/react": "~16.9.23",
"#types/react-dom": "~16.9.8",
"#types/react-native": "~0.61.23",
"#types/react-native-vector-icons": "^6.4.5",
"babel-plugin-inline-dotenv": "^1.6.0",
"babel-preset-expo": "~8.2.0",
"expo": "~38.0.1",
"expo-updates": "~0.2.8",
"jest-expo": "~38.0.0",
"typescript": "~4.0.2"
},
"jest": {
"preset": "react-native"
},
"private": true
}
Of course, I also set the babel.config.js file
module.exports = function(api) {
api.cache(true);
return {
plugins: ['inline-dotenv'],
presets: ['babel-preset-expo'],
};
};
The problem occurs when I an making an API call to some endpoint.
import Axios from "../../api/axios";
const login = async () => {
console.log(process.env.REACT_APP_API_URL);
try{
const response = await Axios.post(ENDPOINTS.login,{
email,
password,
device_id
});
console.log(response);
}catch(e){ //TODO : deal with errors
console.log(e);
}
};
The request is getting a 404 error when using the .env file and working normally if I just set the string directly.
import axios from 'axios';
const Axios = axios.create({
baseURL: 'http://myurl..." // This is working as expected!
});
Axios.defaults.headers.common['Content-Type'] = 'application/json';
export default Axios;
It seems that the .env file is not being set correctly but according to the console.log(), it has the correct value. I suspect the reason is that the environment variable is set after the Axios function is called, so at first it's null but then when the log appears it is already set.
Is my explanation plausible or what other setting might be causing this problem?
After testing it out the next day, I was surprised that it was working fine so I am assuming there was some problem with the cache. For anyone facing this problem, I suggest deleting the cache in Expo and try again

Jest: How to fix - TypeError: Cannot assign to read only property 'name' of function 'function ()

Im using react-native-paper within my own functional component.
I want to write Jest tests for my component.
Problem:
When I import my component to the Jest test file I receive this error:
TypeError: Cannot assign to read only property 'name' of function 'function () {for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {ar...<omitted>... }'
at node_modules/react-native-paper/src/core/withTheme.js:136:46
at Array.forEach (<anonymous>)
at withTheme (node_modules/react-native-paper/src/core/withTheme.js:124:5)
at Object.<anonymous> (node_modules/react-native-paper/src/components/Typography/Text.js:46:24)
at Object.<anonymous> (node_modules/react-native-paper/src/components/BottomNavigation.js:16:48)`
Trying to narrow the error I found out that even this simple Jest file will cause the error.
Reproducer
import React from 'react';
import { Provider as PaperProvider } from 'react-native-paper';
describe('Unit Tests - Component:', () => {
it('s a test', () => {});
});
My package.json:
{
"name": "TodoList",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"prettier": "prettier --write '*.js'",
"format-code": "yarn run prettier && yarn run lint:fix",
"precommit": "lint-staged",
"test:coverage": "jest --coverage && open coverage/lcov-report/index.html"
},
"lint-staged": {
"*.js": ["yarn run format-code", "git add"]
},
"dependencies": {
"firebase": "^5.5.3",
"prop-types": "^15.6.0",
"react": "16.4.1",
"react-native": "0.56.0",
"react-native-image-picker": "^0.26.7",
"react-native-keychain": "^3.0.0",
"react-native-paper": "^1.0.1",
"react-native-vector-icons": "^5.0.0",
"react-navigation": "^1.5.12",
"react-redux": "^5.0.7",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"yarn": "^1.9.4"
},
"devDependencies": {
"babel-eslint": "^8.2.2",
"babel-jest": "22.4.1",
"babel-preset-react-native": "^5.0.2",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.6.0",
"eslint": "^4.18.1",
"eslint-config-airbnb": "^16.1.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.7.0",
"husky": "^0.14.3",
"jest": "22.4.2",
"jest-fetch-mock": "^2.1.0",
"lint-staged": "^7.2.2",
"prettier": "1.10.2",
"react-dom": "^16.7.0",
"react-test-renderer": "16.4.1",
"redux-mock-store": "^1.5.3"
},
"jest": {
"preset": "react-native",
"setupFiles": ["<rootDir>/tests/setup.js"],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
"collectCoverageFrom": ["app/**/*.js", "!app/components/index.js"]
}
}
I faced the same issue for window.location.reload:
TypeError: Cannot assign to read only property 'reload' of object '[object Location]'
I did the following to make it work:
const reload = window.location.reload;
beforeAll(() => {
Object.defineProperty(window, 'location', {
value: { reload: jest.fn() }
});
});
afterAll(() => {
window.location.reload = reload;
});
it('my test case', () => {
// code to test the call to reload
expect(window.location.reload).toHaveBeenCalled();
});
Jest version: 26.6.3
react-scripts version: 4.0.1
Note
The issue appeared after upgrading to react-scripts version 4.0.1.
Solution:
import { DefaultTheme, Provider as PaperProvider } from 'react-native-paper';
describe('Unit Test', () => {
const theme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
},
};
const props = {};
beforeEach(() => {
renderedComponent = renderer
.create(<PaperProvider theme={theme}>
<MyCompoment {...props} />
</PaperProvider>)
.toJSON();
// basic tests
it(`${componentName} renders successfully`, () => {
expect(renderedComponent).toBeTruthy();
});
}