I am trying to get jest to work with a new react-native project. However, when I run npm run test, I get the following error ReferenceError: __DEV__ is not defined. I've looked through countless Github issues and Stack Overflow posts regarding this but none of the suggestions have worked in my case.
Here is my jest.config.js file:
module.exports = {
transformIgnorePatterns: [
"node_modules/(?!(react-native|react-native-button|react-native-video)/)"
],
setupFiles: ['<rootDir>/__tests__/setup.json'],
}
package.json (notice I added DEV = true inside "jest")
{
"name": "DigitalSignagePlayer",
"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.15.5",
"axios": "^0.21.1",
"react": "^17.0.1",
"react-native": "0.64.2",
"react-native-fs": "^2.18.0",
"react-native-splash-screen": "^3.2.0",
"react-native-video": "^5.1.1"
},
"devDependencies": {
"#babel/core": "^7.14.5",
"#babel/preset-env": "^7.14.7",
"#babel/runtime": "^7.14.5",
"#react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^27.0.2",
"eslint": "^7.28.0",
"jest": "^27.0.5",
"metro-react-native-babel-preset": "^0.66.0",
"react-test-renderer": "17.0.1"
},
"jest": {
"preset": "react-native",
}
}
bable.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset', '#babel/preset-env'],
};
metro.config.js
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* #format
*/
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
I have tried setting globals.DEV = true and global.DEV = true at the top of my test files. I have tried adding setupFiles to jest.config.js which loads a setup.js file that contains global.DEV = true too. I have tried updating jest also. My current version of react-native is:
react-native-cli: 2.0.1
react-native: 0.64.2
I'm also using Metro, not Expo and I initially created the app with react-native-cli.
UPDATE:
setup.json
{
"globals": { "__DEV__": true }
}
UPDATE 2:
I changed setup.json to setup.js but I am still getting the same error:
global.__DEV__ = true
The variable is called __DEV__, so using DEV by trial and error doesn't make sense. Setting it in tests won't help because it won't affect the usage of the variable on import. In order to do this, this should have been done before tests in setupFiles* files.
Jes globals configuration option is supposed to do this. There should be "globals": { "__DEV__": true }. The configuration in package.json overridden by the configuration in jest.config.js. There should be only one of them (likely the latter), the other one needs to be removed.
Related
I'm trying to run expo on a turborepo.
Running pnpm dev gives me the following error:
Unable to resolve "expo" from "index.ts"
And the simulator the following screen with the following error:
Unable to resolve module expo from /Users/xx/main/apps/expo/index.ts: expo could not be found within the project or in these directories:
node_modules
../../node_modules
> 1 | import { registerRootComponent } from "expo";
| ^
2 |
3 | import { App } from "./src/_app";
4 |
I have tried to delete all my node_modules.
I have tried to clean my entire project.
I have no idea what to do next.
Here is my metro.config.js:
// Learn more: https://docs.expo.dev/guides/monorepos/
const { getDefaultConfig } = require("expo/metro-config");
const path = require("path");
const projectRoot = __dirname;
const workspaceRoot = path.resolve(projectRoot, "../..");
// Create the default Metro config
const config = getDefaultConfig(projectRoot);
// Add the additional `cjs` extension to the resolver
config.resolver.sourceExts.push("cjs");
// 1. Watch all files within the monorepo
config.watchFolders = [workspaceRoot];
// 2. Let Metro know where to resolve packages and in what order
config.resolver.nodeModulesPaths = [
path.resolve(projectRoot, "node_modules"),
path.resolve(workspaceRoot, "node_modules"),
];
// 3. Force Metro to resolve (sub)dependencies only from the `nodeModulesPaths`
config.resolver.disableHierarchicalLookup = true;
module.exports = config;
Here is my package.json:
{
"name": "#acme/expo",
"version": "0.1.0",
"main": "index.ts",
"scripts": {
"clean": "rm -rf .expo .turbo node_modules",
"dev": "expo start --ios",
"dev:android": "expo start --android",
"dev:ios": "expo start --ios",
"lint": "eslint",
"type-check": "tsc --noEmit"
},
"dependencies": {
"expo": "~47.0.12",
"expo-status-bar": "~1.4.2",
"react": "18.1.0",
"react-dom": "18.1.0",
"react-native": "0.70.5",
"react-native-safe-area-context": "4.4.1",
"expo-splash-screen": "~0.17.5"
},
"devDependencies": {
"#babel/core": "^7.19.3",
"#babel/preset-env": "^7.19.3",
"#babel/runtime": "^7.19.0",
"#expo/config-plugins": "^5.0.4",
"#types/react": "^18.0.25",
"#types/react-native": "~0.70.8",
"eslint": "^8.30.0",
"typescript": "^4.9.4"
},
"private": true
}
Thanks you for helping.
I couldn't get it working with pnpm (I tried for way too long), so I switched over to yarn 1 (classic) workspaces and it worked. Yarn 1 workspaces are the only workspace solution that Expo supports, so I recommend going with that.
I am trying to run a test in next.js using jest, but i keep getting an error:
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.
I have tried following the link and addding the docblock:
/**
* #jest-environment jsdom
*/
to my code with no success.
I have also tried configuring my jest.config.js based on the next.js testing page. This does not work I have tried both the solution with and without the rust compiler. Neither works:
Package.JSON:
{
"name": "chat",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"test": "jest --env=node --forceExit --watchAll --coverage"
},
"dependencies": {
"#firebase/testing": "^0.20.11",
"firebase": "^9.9.4",
"kill-port": "^2.0.1",
"next": "12.2.5",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-firebase-hooks": "^5.0.3",
"react-hot-toast": "^2.3.0",
"uuid": "^8.3.2"
},
"devDependencies": {
"#babel/plugin-syntax-jsx": "^7.18.6",
"#babel/preset-react": "^7.18.6",
"#firebase/rules-unit-testing": "^2.0.4",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#types/jest": "^29.0.2",
"eslint": "8.23.0",
"eslint-config-next": "12.2.5",
"firebase-admin": "^11.0.1",
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3"
}
}
Jest.config.js:
// jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
/** #type {import('jest').Config} */
const customJestConfig = {
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
//moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
test/page.test.js
import { render, screen } from '#testing-library/react';
import Home from '../pages/index';
describe('Home', () => {
it('renders a heading', () => {
render(<Home />);
expect(2 + 2).toBe(4);
});
});
You're overriding the env in your npm test script, remove --env=node:
"test": "jest --forceExit --watchAll --coverage"
I tried a lot to search for a solution to my problem all over the internet, however I couldn't find anything that could help me.
I have a JS utility file that allows me to test values.
Here is one of the functions that compose it :
const colorIsValid = (color) => {
if (!color || typeof color !== 'string') {
return false
}
if (CSS !== undefined) {
if (CSS.supports('color', color)) {
return true
}
throw new Error(`The provided color : "${color}" is not valid`)
}
throw new Error('Your navigator do not support CSS Api')
}
export { colorIsValid }
Everything works fine when I do a manual test on different browsers.
However when I run my tests with Jest I get the following error:
ReferenceError: CSS is not defined
here is my current environment.
// package.json
{
"name": "vue-polygon-grid",
"version": "1.0.0",
"description": "Interactive polygon structure for Vue.js",
"author": {
"name": "Guyomar Alexis",
"email": "contact#ag-dev.fr",
"url": "https://ag-dev.fr/"
},
"main": "dist/data-tables.min.js",
"homepage": "https://github.com/ga-devfront/vue-polygon-grid-private",
"keywords": [
"vue3",
"vuejs",
"vue",
"grid",
"polygon",
"composition"
],
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test": "jest"
},
"dependencies": {
"core-js": "^3.20.2",
"vue": "^3.0.0"
},
"devDependencies": {
"#babel/core": "^7.16.7",
"#babel/preset-env": "^7.16.8",
"#vue/cli-plugin-babel": "~4.5.15",
"#vue/cli-plugin-eslint": "~4.5.15",
"#vue/cli-service": "~4.5.15",
"#vue/compiler-sfc": "^3.2.26",
"#vue/eslint-config-airbnb": "^6.0.0",
"babel-eslint": "^10.1.0",
"babel-jest": "^27.4.6F",
"eslint": "^7.32.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jest": "^25.3.4",
"eslint-plugin-vue": "^8.2.0",
"jest": "27.4.7",
"jest-junit": "13.0.0",
"jest-transform-stub": "^2.0.0",
"sass": "^1.38.0",
"sass-loader": "^10"
}
}
// jest.config.js
module.exports = {
clearMocks: true,
collectCoverage: true,
coverageDirectory: 'coverage',
"collectCoverageFrom": [
"**/utility/*.{js,jsx}",
],
coverageReporters: ['html', 'text', 'text-summary', 'cobertura'],
transform: {
'^.+\\.js$': 'babel-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|jpeg|svg|ttf|woff|woff2)$': 'jest-transform-stub',
},
reporters: [
'default',
['jest-junit', { outputDirectory: 'coverage' }],
],
};
Does anyone have a solution so I can test my methods?
Thank you in advance for taking the time to read me.
jest runs via Node runtime, meaning there are no browser APIs. You will need to mock it. Look into jest setupFiles.
Create a setup file:
global.CSS = {
supports: (k, v) => false,
}
Then use that setup file to add CSS object onto global object.
This answer might also be helpful.
If you really must have DOM APIs you can include package JSDOM that can help. In my opinion in most cases it’s unnecessary dependency.
From your question it sounds like you just need your tests to run. Do you really need to set up global CSS object? Are you sure you’re not testing implementation details?
I'm trying to build a React Native app with some navigation, and i got this error whenever i build it, i'm using expo to build the app :
Android Bundling failed 6098ms
While trying to resolve module `#react-navigation/core` from file `/Users/laurent/Documents/Delivery/Tek3/DEV/B-DEV-501-LYN-5-1-redditech-laurent.cazette/node_modules/#react-navigation/native/src/ResourceSavingSceneView.js`, the package `/Users/laurent/Documents/Delivery/Tek3/DEV/B-DEV-501-LYN-5-1-redditech-laurent.cazette/node_modules/#react-navigation/core/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/laurent/Documents/Delivery/Tek3/DEV/B-DEV-501-LYN-5-1-redditech-laurent.cazette/node_modules/#react-navigation/core/lib/module/index.js`. Indeed, none of these files exist:
* /Users/laurent/Documents/Delivery/Tek3/DEV/B-DEV-501-LYN-5-1-redditech-laurent.cazette/node_modules/#react-navigation/core/lib/module/index.js(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
* /Users/laurent/Documents/Delivery/Tek3/DEV/B-DEV-501-LYN-5-1-redditech-laurent.cazette/node_modules/#react-navigation/core/lib/module/index.js/index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
I think I've already installed all dependencies, but here is my package.json in case I forgot anything :
{
"main": "index.js",
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"web": "expo start --web",
"start": "react-native start"
},
"dependencies": {
"#react-native-community/masked-view": "^0.1.11",
"#react-navigation/core": "react-navigation/core",
"#react-navigation/native": "react-navigation/native",
"#react-navigation/stack": "5.9.0",
"expo": "~42.0.1",
"expo-splash-screen": "~0.11.2",
"expo-status-bar": "~1.0.4",
"expo-updates": "~0.8.1",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "0.63.4",
"react-native-gesture-handler": "~1.10.2",
"react-native-paper": "^4.9.2",
"react-native-reanimated": "~2.2.0",
"react-native-safe-area-context": "^3.3.2",
"react-native-screens": "~3.4.0",
"react-native-svg": "^12.1.1",
"react-native-unimodules": "0.14.10",
"react-native-vector-icons": "^8.1.0",
"react-native-web": "^0.17.5",
"react-navigation": "^4.4.4",
"react-navigation-stack": "^2.10.4",
"styled-components": "^5.3.1",
"styled-system": "^5.1.5"
},
"devDependencies": {
"#babel/core": "^7.9.0"
},
"private": true
}
I've already tried to update metro.config.js :
const { getDefaultConfig } = require('expo/metro-config');
module.exports = {
resolver: {
/* resolver options */
sourceExts: ['jsx', 'js', 'ts', 'tsx'],
},
maxWorkers: 2,
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
};
module.exports = getDefaultConfig(__dirname);
Do you guys have any idea on what's wrong ?
Why do you have it like this?
"#react-navigation/core": "react-navigation/core",
"#react-navigation/native": "react-navigation/native",
They need to be correct version numbers. Follow the documentation on official website to install the packages:
https://reactnavigation.org/docs/getting-started
https://reactnavigation.org/docs/stack-navigator/
expo install react-native-screens react-native-safe-area-context react-native-gesture-handler
yarn add #react-navigation/native #react-navigation/stack
And remove "#react-navigation/core": "react-navigation/core" from your package.json.
Try this:
Install react-navigation module.
Re-build your project.
Restart the packager by stopping the current
packager and then starting the packager again with react-native
start.
Unable to resolve module 'react-navigation'
I have the following Jest test:
import React from 'react';
import IndexSign from '../IndexSign';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<IndexSign index={1}/>
).toJSON();
expect(tree).toMatchSnapshot();
});
The IndexSign component that I am calling calls this StyleSheet component:
import {StyleSheet} from 'react-native';
export default StyleSheet.create({
//some styles
});
For testing, I am using Gulp:
gulp.task('tests', () => {
process.env.NODE_ENV = 'test';
return gulp.src('src').pipe(jest({
}));
});
The problem is that when I run this test, I get:
● Test suite failed to run
Cannot find module 'StyleSheet' from 'react-native-implementation.js'
at Resolver.resolveModule (../node_modules/jest-resolve/build/index.js:142:17)
at Object.StyleSheet (../node_modules/react-native/Libraries/react-native/react-native-implementation.js:98:25)
at Object.<anonymous> (styles/Styles.js:5:13)
Any idea why this is happening?
Why is it searching for StyleSheet in react-native-implementation.js rather than react-native, which I imported?
And why can it not find StyleSheet?
I ran into the same issue. Adding
"jest": {
"preset": "react-native"
},
in the package.json fixed the error for me.
Incase you are keeping separate config file like jest.config.js. Add preset in it. Checkout the sample config file
module.exports = {
preset: 'react-native',
setupFiles: ['<rootDir>/__test__/setup.js'],
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy',
'^.+\\.(jpg|jpeg|gif|png|mp4|mkv|avi|webm|swf|wav|mid)$': 'jest-static-stubs/$1'
},
globals: {
__DEV__: true
},
collectCoverageFrom: [
'**/src/**/*.{js,jsx}',
'!**/src/**/style.js',
'!**/src/**/index.js',
'!**/src/theme/**',
'!**/android/**',
'!**/ios/**',
'!**/node_modules/**',
'!**/scripts/**',
'!**/__test__/**'
],
verbose: true,
testPathIgnorePatterns: ['/node_modules/'],
testResultsProcessor: 'jest-sonar-reporter',
testURL: 'http://localhost/'
}
There are two ways of fixing this issue.
1. Make sure you don't have or delete any file called jest.config.js in your root folder.
2. If you want to have a custom jest.config.js file, make sure you have a preset node in it.
Like so:
module.exports = {
preset: "react-native",
verbose: true,
};
I was facing the same problem. Now it is resolved.
My package.json looks like this :
{
"name": "ReactNativeTDDStarterKit",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.8.3",
"react-native": "0.59.5"
},
"devDependencies": {
"#babel/core": "7.4.4",
"#babel/runtime": "7.4.4",
"babel-jest": "24.8.0",
"babel-preset-flow": "^6.23.0",
"babel-preset-react-native": "4.0.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"enzyme-to-json": "^3.3.1",
"jest": "24.8.0",
"metro-react-native-babel-preset": "0.54.0",
"react-dom": "^16.8.6",
"react-test-renderer": "16.8.3"
},
"jest": {
"preset": "react-native",
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"setupFiles": [
"<rootDir>/jest/setup.js"
]
}
}
I am using react-native 0.59.5, I did not reset .babelrc or jest.config.js manually, I just installed the dependencies. It automatically generated presets for me after the installation is completed. My babel.config.js looks like :
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
I followed instructions from this Link