Cannot find module from 'react-native-implementation.js' - javascript

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

Related

Getting Error When Using Next.js With Jest

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"

Jest - ReferenceError: __DEV__ is not defined (React Native)

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.

How to add Sapper to existing Svelte project?

I have extensive applications in svelte, later I need to attach a sapper to it for further work, it is possibly? I try do it via:
npm i #sapper
but when I try to import something from this package e.q.:
import { goto } from '#sapper/app';
compiler throw me that i have no dependency to this sapper methods :(
I have no idea how to attach sapper to my project
my rollup
import svelte from "rollup-plugin-svelte";
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import livereload from "rollup-plugin-livereload";
import { terser } from "rollup-plugin-terser";
// library that helps you import in svelte with
// absolute paths, instead of
// import Component from "../../../../components/Component.svelte";
// we will be able to say
// import Component from "components/Component.svelte";
import alias from "#rollup/plugin-alias";
const production = !process.env.ROLLUP_WATCH;
// configure aliases for absolute imports
const aliases = alias({
resolve: [".svelte", ".js"], //optional, by default this will just look for .js files or folders
entries: [
{ find: "components", replacement: "src/components" },
{ find: "views", replacement: "src/views" },
{ find: "assets", replacement: "src/assets" },
],
});
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require("child_process").spawn(
"npm",
["run", "start", "--", "--dev"],
{
stdio: ["ignore", "inherit", "inherit"],
shell: true,
}
);
process.on("SIGTERM", toExit);
process.on("exit", toExit);
},
};
}
export default {
input: "src/main.js",
output: {
sourcemap: true,
format: "iife",
name: "app",
file: "public/build/bundle.js",
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: (css) => {
css.write("bundle.css");
},
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ["svelte"],
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload("public"),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
// for absolut imports
// i.e., instead of
// import Component from "../../../../components/Component.svelte";
// we will be able to say
// import Component from "components/Component.svelte";
aliases,
],
watch: {
clearScreen: false,
},
};
my package.json:
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public -s",
"build:tailwind": "tailwind build public/assets/styles/index.css -o public/assets/styles/tailwind.css",
"build:fontawesome": "mkdir -p public/assets/vendor/#fortawesome/fontawesome-free/webfonts && mkdir -p public/assets/vendor/#fortawesome/fontawesome-free/css && cp -a ./node_modules/#fortawesome/fontawesome-free/webfonts public/assets/vendor/#fortawesome/fontawesome-free/ && cp ./node_modules/#fortawesome/fontawesome-free/css/all.min.css public/assets/vendor/#fortawesome/fontawesome-free/css/all.min.css",
"install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && rm -rf public/build && npm install && npm run build:tailwind && npm run build:fontawesome && npm run dev"
},
"devDependencies": {
"#rollup/plugin-commonjs": "^16.0.0",
"#rollup/plugin-node-resolve": "^10.0.0",
"rollup": "^2.3.4",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-node-polyfills": "^0.2.1",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
"svelte": "^3.0.0",
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1"
},
"dependencies": {
"#fortawesome/fontawesome-free": "5.14.0",
"#popperjs/core": "2.5.1",
"#rollup/plugin-alias": "3.1.1",
"#rollup/plugin-replace": "^2.3.4",
"#tailwindcss/custom-forms": "0.2.1",
"body-parser": "^1.19.0",
"chart.js": "2.9.3",
"compression": "^1.7.4",
"express": "^4.17.1",
"express-session": "^1.17.1",
"fontawesome-svelte": "^2.0.1",
"node-fetch": "^2.6.1",
"node-sass": "^5.0.0",
"page": "^1.11.6",
"polka": "^0.5.2",
"rollup-plugin-scss": "^2.6.1",
"session-file-store": "^1.5.0",
"sirv": "^1.0.10",
"sirv-cli": "1.0.6",
"svelte-routing": "1.4.2",
"tailwindcss": "1.8.10"
}
}
I was looking for this answer, I think the #Romain Durand answer is the closest, I don't think we can add ssaper to an existing svelte project. I would have to initialize project in ssaper and use svelte.

Svelte 3: Could not import modules when unit testing

I'm trying to test a Svelte component with Jest. This component works fine in the browser, but unit test fails with importing modules.
For example, when running Jest, import uuid from 'uuid' compiled as const { default: uuid } = require("uuid");, and calling uuid.v4() causes TypeError: Cannot read property 'v4' of undefined. When I use import * as uuid from 'uuid' or const uuid = require('uuid'), Jest unit test passes, but it doesn't work in the browser.
How can I deal with this issue? Any information would greatly help. Thank you.
package.json:
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "firebase serve --only hosting"
},
"devDependencies": {
"#rollup/plugin-json": "^4.0.0",
"#testing-library/jest-dom": "^5.1.1",
"#testing-library/svelte": "^1.11.0",
"bulma": "^0.8.0",
"eslint": "^6.7.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jest": "^23.0.4",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"eslint-plugin-svelte3": "^2.7.3",
"jest-transform-svelte": "^2.1.1",
"node-sass": "^4.13.1",
"rollup": "^1.12.0",
"rollup-jest": "0.0.2",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-livereload": "^1.0.0",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-globals": "^1.4.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-svelte": "^5.0.3",
"rollup-plugin-terser": "^5.1.2",
"sirv-cli": "^0.4.5",
"svelma": "^0.3.2",
"svelte": "^3.18.2",
"svelte-preprocess": "^3.4.0"
},
"dependencies": {
"firebase": "^7.8.2"
},
"private": true
}
rollup.config.js
import json from '#rollup/plugin-json'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'rollup-plugin-node-builtins'
import globals from 'rollup-plugin-node-globals'
import livereload from 'rollup-plugin-livereload'
import resolve from 'rollup-plugin-node-resolve'
import svelte from 'rollup-plugin-svelte'
import { terser } from 'rollup-plugin-terser'
import preprocess from 'svelte-preprocess'
const production = !process.env.ROLLUP_WATCH
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
// https://github.com/rollup/plugins/tree/master/packages/json
json(),
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file — better for performance
css: css => {
css.write('public/build/bundle.css')
},
preprocess: preprocess(),
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration —
// consult the documentation for details:
// https://github.com/rollup/rollup-plugin-commonjs
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/'),
}),
commonjs(),
globals(),
builtins(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
],
watch: {
clearScreen: false,
},
}
function serve () {
let started = false
return {
writeBundle () {
if (!started) {
started = true
require('child_process').spawn('npm', ['run', 'start'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true,
})
}
},
}
}
jest.config.js
const sveltePreprocess = require('svelte-preprocess')
module.exports = {
displayName: { name: 'web', color: 'magentaBright' },
moduleFileExtensions: [
'js',
'json',
'svelte',
],
preset: 'rollup-jest',
transform: {
'\\.js$': 'rollup-jest',
'\\.svelte$': ['jest-transform-svelte', { preprocess: sveltePreprocess(), debug: true }],
},
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
}
It worked for me.
The issue seems like jest unable to resolve uuid while building the code at runtime.
Which is quite obvious because by default jest ignore node_modules packages.
I faced similar issues and resolved it. The approach is by configuration inform JEST that it has to include node_modules packages as well. In my project i used rollup-plugin-babel.
This is the babel plugin configuration
...
...
babel({
extensions: [ '.js', '.mjs', '.html', '.svelte' ],
runtimeHelpers: true,
exclude: [ 'node_modules/#babel/**', 'node_modules/core-js/**' ],
presets: [
[
'#babel/preset-env',
{
targets: '> 0.25%, not dead',
useBuiltIns: 'usage',
corejs: 3
}
]
]
})
And I've added babel-jest for transforming the jest.config.js
module.exports = {
preset: 'jest-puppeteer', //ignore the preset part, I used for puppeteer
transform: {
'^.+\\.js?$': require.resolve('babel-jest'),
"^.+\\.ts?$": "ts-jest" // this part is only required if you have typescript project
}
};
DO Not forget to install this packages like babel-jest, rollup-plugin-babel before using it.
I have been facing this same issue and have a work around by mocking the module in the test file and giving it a default key.
jest.mock('uuid', () => ({
default: {
v4: jest.fn(),
},
}))
Another way that seems to work is to destructure the import in the component file.
import { v4 as uuidv4 } from 'uuid'
Self answer:
Finally, I wrote a little preprocessor to replace import foo from 'foo' -> import * as foo from 'foo'
svelteJestPreprocessor.js
const svelteJestPreprocessor = () => ({
// replace `import foo from 'foo'` -> `import * as foo from 'foo'`
script: ({ content }) => ({
// process each line of code
code: content.split('\n').map(line =>
// pass: no import, import with {}, import svelte component
(!line.match(/\s*import/)) || (line.match(/{/)) || (line.match(/\.svelte/)) ? line
: line.replace(/import/, 'import * as'),
).join('\n'),
}),
})
module.exports = svelteJestPreprocessor
jest.config.js
const svelteJestPreprocessor = require('./svelteJestPreprocessor')
const sveltePreprocess = require('svelte-preprocess')
module.exports = {
moduleFileExtensions: [
'js',
'json',
'svelte',
],
preset: 'rollup-jest',
transform: {
'\\.js$': 'rollup-jest',
'\\.svelte$': ['jest-transform-svelte', {
preprocess: [
svelteJestPreprocessor(),
sveltePreprocess(),
],
}],
},
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
}
This is an unwanted workaround, but it works for now.

Jest Enzyme test throws unexpected token error

When I run the test, it thorws "unexpected token error at the code:
const wrapper = shallow(<WelcomeMessage/>");
The error is thrown at "(<". I have looked at a number of answers from stackoverflow and github but somehow I still cannot get it to work.
I have written jest tests. This is my first time writing a test case using enzyme and react. So I am not familar with the setup. I have installed: babel jest, react-dom, babel-plugin-transform-export-extensions, enzyme-adapter-react-16, react-test-renderer, #babel/preset-env, and #babel/core
package.json:
{
"private": true,
"version": "0.0.0",
"name": "example-jquery",
"devDependencies": {
"#babel/core": "*",
"#babel/preset-env": "^7.4.4",
"babel-jest": "^24.8.0",
"babel-plugin-transform-export-extensions": "^6.22.0",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.12.1",
"jest": "^24.8.0",
"jest-dom": "^3.1.4",
"jest-useragent-mock": "0.0.3"
},
"dependencies": {
"jest-puppeteer": "^4.1.1",
"jquery": "^3.4.1",
"jsdom": "^15.0.0",
"puppeteer": "^1.15.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.8.6"
},
"scripts": {
"test": "jest --verbose"
},
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
}
jest.config.js:
module.exports = {
preset: 'jest-puppeteer',
"bail": 0,
setupFiles: ['<rootDir>/enzyme.config.js'],
moduleFileExtensions: ['js', 'json', 'jsx'],
transformIgnorePatterns: ['<rootDir>/node_modules/']
}
enzyme.config.js:
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new Adapter() });
.babelrc:
{
"presets": ["#babel/preset-env"],
"plugins": ["transform-export-extensions"],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
}
WelcomeMessage.test.js:
import React from 'react';
import { shallow } from 'enzyme';
// Components
import WelcomeMessage from './WelcomeMessage';
function setup() {
const props = {
imgPath: 'some/image/path/to/a/mock/image',
};
const wrapper = shallow(<WelcomeMessage />);
return { wrapper, props };
}
describe('WelcomeMessage Test Suite', () => {
it('Should have an image', () => {
const { wrapper } = setup();
expect(wrapper.find('img').exists()).toBe(true);
});
});
This line:
<WelcomeMessage />
is JSX which "just provides syntactic sugar for the React.createElement function".
Since JSX isn't actually valid JavaScript code it must be compiled into React.createElement calls.
This is done by the Babel plugin #babel/plugin-transform-react-jsx which is included as part of #babel/preset-react.
Add #babel/preset-react to your Babel config and that should resolve the issue.

Categories

Resources