How can I import Audio into My Create-React-App application? - javascript

I am building a music-player application, where basically the user clicks the song they want and it plays the assigned music. However I am getting this error:
ERROR in ./src/components/MusicPlayer.js 7:0-17
Module not found: Error: Can't resolve './music' in '/Users/zpotatlises/Desktop/spotifly/src/components'
I am assuming I am getting this error because i imported the audio incorrectly in my application. This image shows the audio folder in my src file.
(when you open the file) ->
This is my code on MusicPlayer.js:
import React, { Component,audio,useRef } from 'react';
import "./music";
import house1 from './music/house1';
import house2 from './music/house2';
import house3 from './music/house3';
import house4 from './music/house4';
const data = [
{ imgSrc: 'house1.png', audioSrc: house1 },
{ imgSrc: 'house2.png', audioSrc: house2 },
{ imgSrc: 'house3.png', audioSrc: house3 },
{ imgSrc: 'house4.png', audioSrc: house4 },
];
export default class MusicPlayer extends Component {
render() {
return (
<div>
<ol>
{data.map(({ imgSrc, audioSrc }) => (
<MediaComponent imgSrc={imgSrc} audioSrc={audioSrc} />
))}
</ol>
</div>
);
}
}
const MediaComponent = ({ imgSrc, audioSrc }) => {
const audioRef = useRef(null);
const toggleAudio = () =>
audio.ref.current.paused
? audioRef.current.play()
: audioRef.current.pause();
return (
<li>
<img src={imgSrc} onClick={toggleAudio}/>
<audio ref={audioRef} src={audioSrc} />
</li>
);
};
Any idea on how to import audio in my application? How did I do it incorrectly?
(P.s english is my second language, if you need any clarification please let me know)
Best,
-Zpo
Package.json :
{
"name": "spotifly",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^12.1.5",
"#testing-library/user-event": "^13.5.0",
"bootstrap": "^5.1.3",
"navbar": "^2.1.0",
"react": "^18.0.0",
"react-audio-player": "^0.17.0",
"react-bootstrap": "^2.2.3",
"react-bootstrap-icons": "^1.8.1",
"react-dom": "^18.0.0",
"react-is": "^18.0.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.0",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
New Error Messages:
ERROR in ./src/components/MusicPlayer.js 7:0-40
Module not found: Error: Can't resolve './music/house1.mp3' in '/Users/zpotatlises/Desktop/spotifly/src/components'
ERROR in ./src/components/MusicPlayer.js 8:0-40
Module not found: Error: Can't resolve '#/music/house2.mp3' in '/Users/zpotatlises/Desktop/spotifly/src/components'
ERROR in ./src/components/MusicPlayer.js 9:0-48
Module not found: Error: You attempted to import ../../../assets/house3.mp3 which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project's node_modules/.

Your syntax is correct, so you've likely got the path wrong.
Be sure to include the file's extension for media assets (.mp3)
Based on your error message, it is looking for ./music inside your components directory, which likely isn't correct.
Delete import "./music"; and then import the specific MP3 files you need
Can't resolve './music' in '/Users/zpotatlises/Desktop/spotifly/src/components'
Take a look at where your asset is in relation to the file that's importing it. If you're able to share more info about your projects directory structure, then I can help further.
Side note, I recommend setting up import aliases, so that you can import files from their absolute location. It will reduce confusion and be easier to manage.
How you do this depends on your type of project, but it's usually something like thin in your tsconfig.json or jsconfig.json
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
You'll then be able to import #/assets/my-tune.mp3 instead of ../../../assets/my-tune.mp3, much simpler :)

Usage:
Just create a file index.js in videos.
import videos from '~/assets/videos';
function App() {
return <video src={videos.video1} width={100} height={100} controls autoPlay/>
}

Related

Invalid hook call error when trying to use React-pro-sidebar

I'm trying to use the react-pro-sidebar package
https://github.com/azouaoui-med/react-pro-sidebar
However I keep on getting the invalid hook call error
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
For some context, I'm using react with react-router for navigation between pages. I wanted to create a sidebar and populate the menu items with react-router links, but that wasn't working out. Below is what I have:
import React from 'react'
import { ProSidebar, Menu, MenuItem, SubMenu } from 'react-pro-sidebar';
const fun = <ProSidebar>
<Menu iconShape="square">
<MenuItem>Dashboard</MenuItem>
<SubMenu title="Components">
<MenuItem>Component 1</MenuItem>
<MenuItem>Component 2</MenuItem>
</SubMenu>
</Menu>
</ProSidebar>;
const SideBarDashboard = () => {
return (
<div>
{fun}
</div>
)
}
export default SideBarDashboard;
And an alternative approach that didn't work out either:
const fun = () => { <ProSidebar>
<Menu iconShape="square">
<MenuItem>Dashboard</MenuItem>
<SubMenu title="Components">
<MenuItem>Component 1</MenuItem>
<MenuItem>Component 2</MenuItem>
</SubMenu>
</Menu>
</ProSidebar>; }
const SideBarDashboard = () => {
return (
<div>{fun}</div>
)
}
And here is my package.json file:
{
"name": "contact-router",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.4",
"#testing-library/user-event": "^13.5.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.2",
"react-scripts": "5.0.0",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
As a 'solved my own answer', my problem was that I installed the package into the wrong folder so it was never included in my package.json

Yarn workspaces with React and React Native

I'm working on creating a yarn workspace to share code between React and React Native (upcoming blog post once it's completely done!).
The most important part for us is sharing business logic between both platforms. In this case we are using react-query for network requests.
We've created a "Render prop" component for that
import { useAllDevices } from "../../queries/devices";
export interface DeviceListProps {
devices: any[];
isLoading: boolean,
onItemClick?: () => void;
}
export interface DeviceItemListProps {
name: string;
onItemClick?: () => void;
}
export const DeviceListContainer = ({ render }: { render: any }) => {
const { data, isLoading } = useAllDevices();
return (
<>
{render({ devices: data?.devices, isLoading })}
</>
)
}
where useAllDevices is something like this:
export const useAllDevices = () => useQuery('useAllDevices', async () => {
const devicesResponse = await get('/todos');
return {
devices: devicesResponse.data,
};
});
In web, it works like a charm, but I'm getting an error for mobile app. It seems like the problem is with react-query itself because once I put this:
const queryClient = new QueryClient();
const App = () => {
const isDarkMode = false;
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={THEME}>
<SafeAreaView style={backgroundStyle}>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<Button styleType="primary">hey</Button>
</ScrollView>
</SafeAreaView>
</ThemeProvider>
</QueryClientProvider>
);
};
I get this error
It is working properly and with no problems for React web version
my package.json on the App module is this
{
"name": "#sharecode/app",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest --updateSnapshot",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx"
},
"dependencies": {
"react": "17.0.2",
"react-native": "0.67.3",
"react-native-gesture-handler": "^2.3.0",
"styled-components": "^5.3.3"
},
"devDependencies": {
"#babel/core": "^7.12.9",
"#babel/runtime": "^7.12.5",
"#react-native-community/eslint-config": "^2.0.0",
"#sharecode/common": "1.0.0",
"#testing-library/jest-native": "^4.0.4",
"#testing-library/react-native": "^9.0.0",
"#types/jest": "^27.4.1",
"#types/react-native": "^0.66.15",
"#types/react-test-renderer": "^17.0.1",
"#types/styled-components-react-native": "^5.1.3",
"#typescript-eslint/eslint-plugin": "^5.7.0",
"#typescript-eslint/parser": "^5.7.0",
"babel-jest": "^26.6.3",
"eslint": "^7.14.0",
"get-yarn-workspaces": "^1.0.2",
"jest": "^26.6.3",
"metro-config": "^0.56.0",
"metro-react-native-babel-preset": "^0.66.2",
"nock": "^13.2.4",
"react-test-renderer": "17.0.2",
"ts-jest": "^27.1.3",
"typescript": "^4.4.4"
},
"workspaces": {
"nohoist": [
"react-native",
"react-native/**",
"react",
"react/**",
"react-query",
"react-query/**"
]
},
"resolutions": {
"#types/react": "^17"
},
"jest": {
"preset": "react-native",
"setupFilesAfterEnv": [
"#testing-library/jest-native/extend-expect"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
}
}
Main package
{
"name": "#sharecode/common",
"version": "1.0.0",
"main": "index.ts",
"license": "MIT",
"dependencies": {
"axios": "^0.26.0",
"react-query": "^3.34.16",
"styled-components": "^5.3.3"
},
"devDependencies": {
"#types/styled-components": "^5.1.24"
}
}
And web package (working perfectly)
{
"name": "#sharecode/web",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.3",
"#testing-library/user-event": "^13.5.0",
"#types/jest": "^27.4.1",
"#types/node": "^16.11.26",
"#types/react": "^17.0.39",
"#types/react-dom": "^17.0.13",
"react": "17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "^5.0.0",
"typescript": "^4.6.2",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"eslint-config-react-app": "^7.0.0",
"react-app-rewired": "^2.2.1"
}
}
The error seems to be pretty straightforward but I cannot see what's going on
ERROR Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This error is located at:
in QueryClientProvider (at App.tsx:31)
in App (at renderApplication.js:50)
in RCTView (at View.js:32)
in View (at AppContainer.js:92)
in RCTView (at View.js:32)
in View (at AppContainer.js:119)
in AppContainer (at renderApplication.js:43)
in NuoDoor(RootComponent) (at renderApplication.js:60)
✨ Done in 318.43s.
Also, here is the result of `yarn why react``
javiermanzano#Javiers-MBP app % yarn why react
yarn why v1.22.17
[1/4] 🤔 Why do we have the module "react"...?
[2/4] 🚚 Initialising dependency graph...
[3/4] 🔍 Finding dependency...
[4/4] 🚡 Calculating file sizes...
=> Found "#sharecode/app#react#17.0.2"
info Reasons this module exists
- "_project_##sharecode#app" depends on it
- in the nohoist list ["/_project_/#sharecode/app/react-native","/_project_/#sharecode/app/react-native/**","/_project_/#sharecode/app/react","/_project_/#sharecode/app/react/**","/_project_/#sharecode/app/react-query","/_project_/#sharecode/app/react-query/**"]
info Disk size without dependencies: "356KB"
info Disk size with unique dependencies: "404KB"
info Disk size with transitive dependencies: "432KB"
info Number of shared dependencies: 3
=> Found "react#17.0.2"
info Reasons this module exists
- "_project_##sharecode#web" depends on it
- Hoisted from "_project_##sharecode#web#react"
info Disk size without dependencies: "356KB"
info Disk size with unique dependencies: "404KB"
info Disk size with transitive dependencies: "432KB"
info Number of shared dependencies: 3
✨ Done in 1.17s.
I hope I explained the problem! Any help is appreciated :)
Thank you!
I don't think your problem is related to having mismatching versions of React and the renderer, so we end with 2 options.
Option 1:
3. You might have more than one copy of React in the same app
I'll start covering the 3rd since is the most probable, in this case your program is detecting two reacts.
In your yarn why react you got a react from "_project_##sharecode#app" and "_project_##sharecode#web" Hoisted from "_project_##sharecode#web#react", remember this Hoisted info cuz it's important for solve your problem.
Looking at your package.json you do have the react installed on both. And looking at your workspaces nohoist in "#sharecode/app" you say to don't hoist the react package, but as I said before it is be hoisting!.
So what is the problem?
Well, as I understood and are illustrated at the nohoist documentation you need to put the nohoist config at the package.json in your root "monorepo" (In your case the #sharecode/common).
It will look like this:
{
"name": "#sharecode/common",
...,
"devDependencies": {
...
},
"workspaces": {
"packages": ["packages/*"],
"nohoist": [
...,
"**/react",
"**/react/**",
...
]
}
}
Than, with your package.json working as expected when you run yarn why react you should get something like this:
...
=> Found "#sharecode/app#react#17.0.2"
info Reasons this module exists
- "_project_##sharecode#app" depends on it
- in the nohoist list ["/_project_/**/react-native","/_project_/**/react-native/**","/_project_/**/react","/_project_/**/react/**","/_project_/**/react-query","/_project_/**/react-query/**"]
...
Maybe a found in the "_project_##sharecode#web" too, with other nohoist probably. I didn't checked it myself, but with this correction said above you should be with everything running fine. You can check this and this for further explanation on how it works. But I'm pretty sure that the problem is the nohoist not being in the "root monorepo".
P.S.: I tryed to find what is the reason for using "packages": ["packages/*"], and didn't find out. But I'm deducing that it is to say that you're hoisting everything that aren't in nohoist.
Option 2:
2. You might be breaking the Rules of Hooks
Well, if you couldn't solve your problem with the first option, your problem is related to a hook.
I don't know if it's this your problem, but you're calling a bool in a const and probably trying to change it in some place. Can't you refactor to use a useState(false)?
Also check if you'd called some hook inside loops, conditions or nested funcitons in some of your children, probably the QueryClientProvider if I don't miss understood.
Searching for the Rules of Hooks I found this:
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)

Prime React css styles not applying in Reactjs application

I am working on an react js application, I had added reactbootstrap & primereact library for the styling.
the reactbootstrap library is working fine But primereact styling is not getting applied , I have followed all the steps present in getting started section, can anyone suggest me what is missing.
I am adding the Files for the refrence.
I used the below command to add files in node modules
npm install primereact --save
npm install primeicons --save
App.js File
import logo from './logo.svg';
import './App.css';
import Header from './MyComponents/Header'
import 'bootstrap/dist/css/bootstrap.min.css';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';
import {Todos} from './MyComponents/Todos'
import {TodoElements} from './MyComponents/TodoElements'
import {Footer} from './MyComponents/Footer'
function App() {
<script src="https://unpkg.com/primereact/primereact.all.min.js"></script>
return (
<><Header title='Code With Shiva' searchBar={true}/>
<Todos/>
<TodoElements/>
<Footer/>
</>
);
}
export default App;
Todos.js where I am adding primereact styled button
import React from 'react';
import { Button } from 'primereact/button';
export const Todos = () => {
return (
<div>
<Button label="Success" className="p-button-success" />
</div>
)
}
Adding package.json for refrence
{
"name": "todos-list",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"bootstrap": "^5.1.3",
"primeicons": "^5.0.0",
"primereact": "^7.1.0",
"prop-types": "^15.8.1",
"react": "^17.0.2",
"react-bootstrap": "^2.1.1",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"react-transition-group": "^4.4.2",
"style-loader": "^3.3.1",
"web-vitals": "^2.1.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Adding final result image
All PrimeReact components require a theme so just add...
import "primereact/resources/themes/lara-light-indigo/theme.css";

importing any component from react-bootstrap throws error

I have some weird error everytime when I'm trying to use some component from 'react-bootstrap'. Here is some small example where I'm importing "HelpBlock" component.
import PropTypes from 'prop-types';
import React from 'react';
import HelpBlock from 'react-bootstrap';
class RegisterFormDetails extends React.Component {
...
<HelpBlock>{validationErrorMessage}</HelpBlock>
}
</div>
</div>
);
};
export default RegisterFormDetails;
but then I'm getting this error
Attempted import error: 'react-bootstrap' does not contain a default export (imported as 'HelpBlock').
my package.json
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"bootstrap": "^4.3.1",
"lodash": "^4.17.11",
"prop-types": "^15.7.2",
"react": "^16.8.3",
"react-bootstrap": "^0.32.1",
"react-bootstrap-sweetalert": "^4.4.1",
"react-dom": "^16.8.3",
"react-scripts": "^2.1.5",
"react-select": "^2.4.1"
}
}
somebody can help me ? I have rechecked the react-bootstrap folder in node_modules and contains the component which I'm trying to import
You can import individual components like:
import HelpBlock from 'react-bootstrap/HelpBlock ';
The first one is importing component directly, The above is a default import. Default imports are exported with export default .... There can be only a single default export. Since 'react-bootstrap' does not contain a default export , you have to import directly.
or import { HelpBlock } from 'react-bootstrap';
Here, only HelpBlock will be imported. Hope it helps.
This article will help you to understand es6 modules.

Jest encountered an unexpected token

Not sure why it's complaining on this line:
const wrapper = shallow(<BitcoinWidget {...props} />);
/Users/leongaban/projects/match/bitcoin/src/components/bitcoinWidget.test.js: Unexpected token (17:26)
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:
15 |
16 | describe('when rendering', () => {
>17 | const wrapper = shallow(<BitcoinWidget {...props} />);
18 | ^
19 | it('should render a component matching the snapshot', () => {
20 | const tree = toJson(wrapper);
Entire test:
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
// Local components
import BitcoinWidget from './bitcoinWidget';
const props = {
logo: 'foobar',
coin: {
price: 0
},
refresh: jest.fn()
}
describe('when rendering', () => {
const wrapper = shallow(<BitcoinWidget {...props} />);
it('should render a component matching the snapshot', () => {
const tree = toJson(wrapper);
expect(tree).toMatchSnapshot();
expect(wrapper).toHaveLength(1);
});
});
The component
import React from 'react';
const BitcoinWidget = ({ logo, coin : { price }, refresh }) => {
return (
<div className="bitcoin-wrapper shadow">
<header>
<img src={logo} alt="Bitcoin Logo"/>
</header>
<div className="price">
Coinbase
${price}
</div>
<button className="btn striped-shadow white" onClick={refresh}>
<span>Refresh</span>
</button>
</div>
);
}
export default BitcoinWidget;
And my package.json
{
"name": "bitcoin",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-redux": "^5.0.7",
"react-scripts": "1.1.5",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "yarn run test-jest:update --verbose --maxWorkers=2",
"test-jest:update": "jest src --updateSnapshot",
"test-jest": "jest src"
},
"now": {
"name": "bitcoin",
"engines": {
"node": "8.11.3"
},
"alias": "leongaban.com"
},
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/client/assetsTransformer.js"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
]
},
"devDependencies": {
"enzyme": "^3.4.4",
"enzyme-to-json": "^3.3.4",
"jest": "^23.5.0"
}
}
Add this in your package.json jest config.
"transform": {
"\\.js$": "<rootDir>/node_modules/babel-jest"
},
Let me know if the issue still persists.
For anyone using create-react-app, only certain jest configurations can be changed in package.json when using create-react-app.
I have issues with Jest picking up an internal library, Jest would display 'unexpected token' errors wherever I had my imports from this library.
To solve this, you can change your test script to the below:
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",
For anyone who struggled with this issue and none of the above answers worked for them.
After a long time of searching, I reached for this solution:
edit your jest.config.js to add transformIgnorePatterns
//jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
testMatch: ["**/__tests__/**/*.ts?(x)", "**/?(*.)+(test).ts?(x)"],
transform: {
"^.+\\.(js|ts)$": "ts-jest",
},
transformIgnorePatterns: [
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.js$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.ts$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.tsx$",
],
}
put the packages that you want to ignore inside [] and separate them by |
in my case [#autofiy/autofiyable|#autofiy/property]
I also encountered the same error while setting up Jest in my React app created using Webpack. I had to add #babel/preset-env and it was fixed. I have also written a blog article about the same.
npm i -D #babel/preset-env
And then add this in "presets" in .babelrc file. E.g.
{
"presets": ["#babel/react", "#babel/env"]
}
https://medium.com/#shubhgupta147/how-i-solved-issues-while-setting-up-jest-and-enzyme-in-a-react-app-created-using-webpack-7e321647f080?sk=f3af93732228d60ccb24b47ef48d7062
I added the jest update to my package.json
"jest": {
"transformIgnorePatterns": [
"node_modules/(?!(<package-name>|<second-package-name>)/)"
]
},
Feel free to remove the |<second-package-name> if not required.
You can also do it as part of your script as mentioned #paulosullivan22
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<package-name>)/)'"
In my case, the issue was that I was importing the original module in the mocked module:
import urlExist from "url-exist";
async function stubbedUrlExist(): Promise<boolean> {
// do something
}
export default stubbedUrlExist;
The solution was to not import url-exist in the url-exist mock. This might have lead to a circular import. Jest was perhaps catching this error in a generic try<>catch block dealing with the loading of modules.
Below works for me.
Create babel.config.js file.
module.exports = {
presets: [
[ '#babel/preset-env', { targets: { esmodules: true } } ],
[ '#babel/preset-react', { runtime: 'automatic' } ],
],
};
I updated some dependencies (react, jest and others), and I also got the error:
Jest encountered an unexpected token - SyntaxError: Cannot use import statement outside a module
I had dev dependencies with needed to be transpiled.
What I did first was start all over:
$ jest --init
A jest.config.js is now generated (before I just had Jest configuration in my package.json).
In the error message under details you can see the reporting module, for me it looked like this:
Details: /<project_root>/node_modules/axios/index.js:1
Adding the following transform ignore in jest.config.js solved my problem:
transformIgnorePatterns: [
"node_modules/(?!axios.*)"
],
The axios module was now nicely transpiled and gave no more problems, hope this helps!
https://jestjs.io/docs/27.x/getting-started
Below works for me
module.exports = {
presets: [
["#babel/preset-env", { targets: { node: "current" } }],
"#babel/preset-typescript", "#babel/react"
]
};
could not get it working with transforms, I ended up mocking the dependency:
Create a file: <path>/react-markdown.js
import React from 'react';
function ReactMarkdown({ children }){
return <>{children}</>;
}
export default ReactMarkdown;
On jest.config.js file add:
module.exports = {
moduleNameMapper: {
'react-markdown': '<path>/mocks/react-markdown.js',
},
};
credits to juanmartinez on https://github.com/remarkjs/react-markdown/issues/635

Categories

Resources