My app works perfectly in local, without errors, but when I try to deploy it on netlify or github pages, when I open it, the page is blank and many errors are displayed in the console.
The error says
TypeError: can't access property "length", e is undefined
where e corresponds to items (which is a state).
If I remove these lines of code, I get another error that always concerns items: the problem this time is with items.some, where items is null again.
Whatever I try to do items always result null.
I tried console.log(items) in many component files and in all of them the result is null.
This is the netlify link where you can see the error:
https://celadon-otter-917b4e.netlify.app/
Navbar.js, where the error is located:
import { Link } from 'react-router-dom';
import Searchbar from './Searchbar';
import { useContext } from 'react';
import FavoritesContext from '../FavoritesContext';
function Navbar() {
const { items } = useContext(FavoritesContext);
return (
<div className='navbar'>
<Link to={'/'} style={{ textDecoration: 'none' }}>
<div className='logo-container'>
<img src="/foglia.png" alt="logo" className='logo'/>
<h3>just<span>vegetables</span></h3>
</div>
</Link>
<Searchbar />
<Link to={'/favorites/'} style={{ textDecoration: 'none' }}>
<h4 className='favor'>Favorites: <span>{items.length}</span></h4>
</Link>
</div>
)
}
export default Navbar;
FavoriteContext.js:
import React, { createContext, useState, useEffect } from "react";
const FavoritesContext = createContext();
export function FavoritesProvider({ children }) {
const [ items, setItems ] = useState([]);
useEffect(() => {
const recipesFavorites = JSON.parse(localStorage.getItem('favorites-recipes'));
setItems(recipesFavorites);
}, []);
const saveToLocalStorage = (item) => {
localStorage.setItem('favorites-recipes', JSON.stringify(item))
}
const addToFavorites = (title, image, id, favorite) => {
if (!favorite) {
const newFavoriteList = [...items, { title, image, id }]
setItems(newFavoriteList);
saveToLocalStorage(newFavoriteList);
};
};
const removeFromFavorites = (title, image, id, favorite) => {
if (favorite) {
const newFavoriteList = items.filter((fav) => fav.id !== id);
setItems(newFavoriteList);
saveToLocalStorage(newFavoriteList);
};
};
return (
<FavoritesContext.Provider value={{ items, setItems, addToFavorites, removeFromFavorites }}>
{children}
</FavoritesContext.Provider>
)
}
export default FavoritesContext;
Card.js:
import { Link } from 'react-router-dom';
import FavoritesContext from '../FavoritesContext';
function Card({ title, image, id }) {
const { addToFavorites } = useContext(FavoritesContext);
const { removeFromFavorites } = useContext(FavoritesContext);
const { items } = useContext(FavoritesContext);
const checkIsAdd = () => {
if(items.some((val) => val.id === id)) {
return true;
}};
const [favorite, setFavorite] = useState(checkIsAdd);
const isInFavorites = (id) => {
return (
<img src='../cuore-pieno.png' alt="like" className='favorite blue' onClick={() => {removeFromFavorites(title, image, id, favorite); toggle()}}/>
)
}
const toggle = () => {
isInFavorites(id);
setFavorite(!favorite);
}
return (
<div className='card'>
{!favorite ? <img src='../cuore-vuoto.png' alt="like" className='favorite' onClick={() => {addToFavorites(title, image, id, favorite); toggle()}}/> : isInFavorites(id)}
<Link to={'/recipe/' + id}>
<img src={image} alt='' className='card-image'/>
<div className='card-info-cnt'>
<p className='card-title'>{title}</p>
</div>
</Link>
</div>
)
}
export default Card;
package.json
{
"name": "projetto-react",
"version": "0.1.0",
"homepage": "https://michela-z.github.io/justVegetables",
"main": "index.js",
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"lodash": "^4.17.21",
"node-env-webpack-plugin": "^1.1.0",
"process": "^0.11.10",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-icons": "^4.4.0",
"react-router-dom": "^6.3.0",
"react-scripts": "^5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d dist",
"serve": "webpack-dev-server --mode development --open --hot",
"start": "webpack-dev-server",
"build": "webpack --mode production",
"test": "react-scripts test",
"eject": "react-scripts eject",
"webpack": "webpack",
"webpack-dev-server": "webpack-dev-server",
"dev": "npm run webpack-dev-server -- --env mode=development",
"prod": "npm run webpack -- --env mode=production"
},
"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": {
"#babel/core": "^7.18.13",
"#babel/preset-env": "^7.18.10",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5",
"css-loader": "^6.7.1",
"file-loader": "^6.2.0",
"gh-pages": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"source-map-loader": "^4.0.0",
"url-loader": "^4.1.1",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.10.0"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const port = process.env.PORT || 3000;
module.exports = {
mode: 'development',
entry: {
index: {
import: './src/index.js',
dependOn: 'shared',
},
another: {
import: './src/another-module.js',
dependOn: 'shared',
},
shared: 'lodash',
},
output: {
filename: '[name].bundle.js',
path: path.join(__dirname, '/dist')
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
}
}
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource'
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
new webpack.ProvidePlugin({
process: 'process/browser',
}),
],
devServer: {
host: 'localhost',
port: port,
historyApiFallback: true,
open: true
},
optimization: {
runtimeChunk: 'single',
},
};
I'm new to programming, this is my first react app, I tried everything that was in my ability.
Check if there item present before checking its length {items.length}
you can achieve this by
{item && item.length} or
{items?.length}
this will get rid of the errors displayed in live deploy
Related
I've been working in this app for weeks and now I'm trying to packit to distribute. When I'm in dev it works just fine, but in production I only get a blank page. I've been lookig for solution in every post here but I can't get it.
This is my package.json
{
"name": "triviapp",
"author": "trivify",
"version": "1.0.0",
"private": true,
"main": "public/electron.js",
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^6.2.0",
"#fortawesome/free-solid-svg-icons": "^6.2.0",
"#fortawesome/react-fontawesome": "^0.2.0",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"docxtemplater": "^3.31.6",
"electron-is-dev": "^2.0.0",
"jimp": "^0.16.2",
"lodash": "^4.17.21",
"mongoose": "^6.7.0",
"nodejs-pptx": "^1.0.1",
"pizzip": "^3.1.3",
"ppt-template": "^1.0.9",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.2",
"react-scripts": "5.0.1",
"translate": "^1.4.1",
"web-vitals": "^2.1.4",
"xlsx-template": "^1.3.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"electron-dev": "concurrently \"set BROWSER=none&& npm start\" \"wait-on
http://localhost:3000 && electron .\"",
"hotel-dev": "concurrently \"set BROWSER=none&& npm start\" \" electron .\"",
"dist": "electron-builder"
},
"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": {
"babel-polyfill": "^6.26.0",
"concurrently": "^7.5.0",
"electron": "^21.2.0",
"electron-builder": "^23.6.0",
"wait-on": "^6.0.1"
},
"build": {
"appId": "com.trivify.triviapp",
"productName": "TriviApp",
"target": "NSIS",
"extends": null,
"nsis": {
"allowToChangeInstallationDirectory": true,
"oneClick": false
},
"directories": {
"buildResources": "resources",
"output": "release"
}
}
}
This is my electron.js
const electron = require('electron');
const app = electron.app;
const { BrowserWindow, ipcMain } = electron;
const path = require('path');
const isDev = require('electron-is-dev');
const { generateTrivia, createFolderWithImgs } = require('../src/logic/func');
const { createDoc } = require('../src/logic/createDoc');
const { createPPT } = require('../src/logic/createPPT');
const { getPreguntas, getRascas, addQuestionToBD, getBaresIsla, newIslandInDB, getIslaCodes }
= require('../src/logic/dbfuncs');
const { connectDB } = require('../src/db');
const {createRascas} = require('../src/logic/createRascas');
const { createTicketIsla } = require('../src/logic/createTicketsIsla');
const url = require('url');
connectDB();
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1300,
height: 900,
center: true,
useContentSize: true,
minHeight: 600,
minWidth: 1000,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
webSecurity: false
}
});
mainWindow.loadURL(isDev ? 'http://localhost:3000' : url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
if (isDev) {
// Open the DevTools.
//BrowserWindow.addDevToolsExtension('<location to your react chrome extension>');
// mainWindow.webContents.openDevTools();
}
mainWindow.on('closed', () => mainWindow = null);
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
This is my index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { HashRouter } from "react-router-dom"
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<HashRouter >
<App />
</HashRouter>
</React.StrictMode>
);
and my app.js
import './stylesheets/App.css';
import { Route, Routes } from "react-router-dom";
import Home from './views/Home';
import Trivial from './views/Trivial';
import DataBases from './views/Databases';
import Rascas from './views/Rascas';
import IslaMisterio from './views/IslaMisterio';
import Facturas from './views/Facturas';
function App() {
return (
<div className='App'>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/trivial' element={<Trivial />} />
<Route path='/pasapalabra' element={<Home />} />
<Route path='/isla' element={<IslaMisterio />} />
<Route path='/rasca' element={<Rascas />} />
<Route path='/facturas' element={<Facturas />} />
<Route path='/databases' element={<DataBases />} />
</Routes>
</div>
);
}
export default App;
If you have any idea of why is this happening, please help!
With CRA, you need to add homepage to your package.json or your app will not work correctly in production. For an Electron app, you can use:
"homepage": "./"
If you have routing, you also need to check that you are using <HashRouter> and not <BrowserRouter>. For reference, here is a question about this.
I want to fetch my data from port 8000,but it still get error 404.
Because it uses port 3000 ,I set proxy in package.json.
I don't know the reason why it goes wrong.
Error below:
GET http://localhost:3000/hotels/countByCity?cities=berlin,madrid,lodon 404 (Not Found)
Here are my relative codes:
pacakge.json
{
"name": "booking",
"version": "0.1.0",
"private": true,
"dependencies": {
"#fortawesome/free-regular-svg-icons": "^6.2.0",
"#fortawesome/free-solid-svg-icons": "^6.2.0",
"#fortawesome/react-fontawesome": "^0.2.0",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^1.1.3",
"date-fns": "^2.29.3",
"react": "^18.2.0",
"react-date-range": "^1.4.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.2",
"react-scripts": "5.0.1",
"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"
]
},
"proxy":"http://localhost:8000/api"
}
useFetch.js
import { useEffect, useState } from "react";
import axios from "axios";
const useFetch = (url) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const res = await axios.get(url);
setData(res.data);
} catch (err) {
setError(err);
}
setLoading(false);
};
fetchData();
}, [url]);
const reFetch = async () => {
setLoading(true);
try {
const res = await axios.get(url);
setData(res.data);
} catch (err) {
setError(err);
}
setLoading(false);
};
return { data, loading, error, reFetch };
};
export default useFetch;
featured.jsx
import React from 'react'
import "./featured.css"
import useFetch from "../../hooks/useFetch"
const Featured = () => {
const{ data,loading,error}=useFetch("/hotels/countByCity?cities=berlin,madrid,lodon")
console.log(data);
return (
<div className='featured'>
<div className="featuredItem">
<img className='featuredImg' src="https://i.pinimg.com/564x/53/47/6a/53476a9ce987dcc41b19385744f09ab3.jpg" />
<div className="featureTitle">
<h1>AmazĂ´nia.</h1>
<h3>189 properties</h3>
</div>
</div>
<div className="featuredItem">
<img className='featuredImg' src="https://i.pinimg.com/564x/cf/fb/34/cffb34899bc7e9262f4f91270d51677d.jpg" />
<div className="featureTitle">
<h1>Avignon’s historic center.</h1>
<h3>259 properties</h3>
</div>
</div>
<div className="featuredItem">
<img className='featuredImg' src="https://i.pinimg.com/564x/7f/6f/0a/7f6f0a8668aa2da61d9025859406e2f1.jpg" />
<div className="featureTitle">
<h1>Naz City Hotel Taksim</h1>
<h3>345 properties</h3>
</div>
</div>
</div>
)
}
export default Featured
I am using the following packages and have installed tailwindcss in the following project folder /home/admin/Desktop/Code/main_project/client/package.json:
{
"name": "react-app",
"version": "1.0",
"private": true,
"dependencies": {
"babel-eslint": "10.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.4",
"react-router": "^6.3.0",
"react-scripts": "3.2.0",
"redux": "^4.1.1",
"redux-thunk": "^2.3.0",
"web-vitals": "^1.0.1",
"web3": "^1.6.1",
"web3-eth-contract": "^1.5.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.7",
"postcss": "^8.4.14",
"tailwindcss": "^3.0.24"
}
}
My tailwind.config.js looks like the following:
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
As you can see my react-project lies in a subfolder.
My postcss.config.js looks like the following:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
This is my index.css:
#tailwind base;
#tailwind components;
#tailwind utilities;
In my index.js I am loading my index.css:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from "./redux/store";
import { Provider } from "react-redux";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
My App.js looks like the following:
import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { connect } from "./redux/blockchain/blockchainActions";
import { fetchData } from "./redux/data/dataActions";
import "./App.css";
function App() {
const dispatch = useDispatch();
const blockchain = useSelector((state) => state.blockchain);
const data = useSelector((state) => state.data);
const [CONFIG, SET_CONFIG] = useState({
CONTRACT_ADDRESS: "",
SCAN_LINK: "",
NETWORK: {
NAME: "",
SYMBOL: "",
ID: 0,
},
NFT_NAME: "",
SYMBOL: "",
MAX_SUPPLY: 1,
WEI_COST: 0,
DISPLAY_COST: 0,
GAS_LIMIT: 0,
MARKETPLACE: "",
MARKETPLACE_LINK: "",
SHOW_BACKGROUND: false,
});
const getData = () => {
if (blockchain.account !== "" && blockchain.smartContract !== null) {
dispatch(fetchData(blockchain.account));
}
};
const getConfig = async () => {
const configResponse = await fetch("/config/config.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const config = await configResponse.json();
SET_CONFIG(config);
};
useEffect(() => {
getConfig();
}, []);
useEffect(() => {
getData();
}, [blockchain.account]);
return (
<>
<h1 className="text-3xl font-bold underline">Welcome</h1>
<>
);
}
export default App;
However, the components in my App.js do not get rendered with tailwindcss.
Any suggestions what I am doing wrong?
I appreciate your replies!
I started a new React.js project in Visual Studio Pro 22 without CRA.
My react component renders accurately (minus a local .mp4 file).
The .mp4 file is contained inside a video element, inside a div, within my main component.
Edge developer tools shows the video element, and the .mp4 file (bundled by webpack).
However, the .mp4 file will not play or show in the browser.
I get this error.
localhost/:1
GET http://localhost:8080/preview net::ERR_ABORTED 404 (Not Found)
Here is my webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
resolve: {
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: { react: path.join(__dirname, 'node_modules', 'react') }
},
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })],
module: {
rules: [
{
test: /\.css/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.js$/,
exclude: /node_modules/,
use:
{
loader: "babel-loader",
options:
{
presets: ['#babel/preset-env', '#babel/preset-react']
}
}
},
{
test: /\.(png|mp4)$/i,
type: "asset/resource"
},
{
test: /\.txt$/i,
type: 'asset/source'
},
{
test: /\.(woff|woff2|ttf)$/i,
type: "asset/resource"
},
{
test: /\.html$/,
use: ["html-loader"]
}
]
}
}
here is my package.json
{
"name": "tascticnodes",
"version": "0.0.0",
"description": "tascticnodes",
"main": "index.js",
"author": "",
"presets":
[
"#babel/preset-env",
"#babel/preset-react"
],
"scripts":
{
"build": "webpack --watch",
"start": "webpack serve"
},
"keywords": [],
"license": "ISC",
"devDependencies":
{
"#babel/core": "^7.16.5",
"#babel/preset-env": "^7.16.5",
"#babel/preset-react": "^7.16.5",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"file-loader": "^6.2.0",
"html-loader": "^3.1.0",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0"
},
"dependencies":
{
"#aws-amplify/ui-react": "^2.1.5",
"aws-amplify": "^4.3.11",
"bootstrap": "^5.1.3",
"react": "^17.0.2",
"react-bootstrap": "^2.0.4",
"react-dom": "^17.0.2",
"typewriter-effect": "^2.18.2"
}
}
here is my config.babelrc
{
"presets": ["#babel/preset-env, "#babel/preset-react"]
}
here is my SRC directory
screen shot of my directory
here is my passIt.js(the standard app.js)
import React from 'react';
import Typewriter from 'typewriter-effect';
import './index.css';
import Amplify from 'aws-amplify';
import { API } from 'aws-amplify';
import { Button, Form } from 'react-bootstrap';
import preview from './preview.mp4';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
async function addContact()
{
const data =
{
body:
{
name: formState.name,
email: formState.email,
message: formState.message
}
}
console.log(data);
const apiData = await API.post('formapi', '/items', data);
console.log({ apiData });
alert('Mail sent');
};
const formState = { name: '', email: '', message: '' };
function updateFormState(key, value)
{
formState[key] = value;
};
const Hello = () => {
return (
<div>
<div>
<div>
<form>
<Typewriter
onInit={(typewriter) =>
typewriter
.typeString('Welcome to Anvil')
.start()} />
</form>
<Form>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control placeholder="Name" onChange={e =>
updateFormState('name', e.target.value)} />
</Form.Group>
<Form.Group>
<Form.Label>Email</Form.Label>
<Form.Control placeholder="Email" onChange={e =>
updateFormState('email', e.target.value)} />
</Form.Group>
<Form.Group>
<Form.Label>Message</Form.Label>
<Form.Control placeholder="Message" onChange={e =>
updateFormState('message', e.target.value)} />
</Form.Group>
<Button onClick={addContact}>Send a message</Button>
</Form>
</div>
</div>
<video autoPlay muted loop>
<source src="preview" type="video/mp4" />
</video>
</div>
)
};
export default Hello;
here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Check my divs</title>
<link href="index.css" rel="stylesheet" type="text/css">
<link C:\Users\zack\source\repos\tascticnodes\src\preview.mp4 />
</head>
<body id="body">
<div id="root"></div>
</body>
</html>
here is my index.js
import React from 'react';
import { render } from 'react-dom';
import Hello from './passIt';
render(<Hello />, document.getElementById('root'));
Specify output file name in webpack.config.js
View the Wepback Documentation: file-loader
Here is what your loader should look like:
`
{
test: /\.(mov|mp4)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
]
}
`
Take a look at this thread:
Webpack 3 locates .mp4 file but video is not playable
I have some img tag which I fill it with dynamic address with require, it works as expected in the component but when I write a test for it throws this error
console.error
Error: Configuration error:
Could not locate module ~/assets/images/flags/undefined.png mapped as:
/home/user/Desktop/Workspace/porject/$1.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^~\/(.*)$/": "/home/user/Desktop/Workspace/porject/$1"
},
"resolver": undefined
}
at createNoMappedModuleFoundError (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:579:17)
at Resolver.resolveStubModuleName (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:541:19)
at Resolver.getMockModule (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:380:31)
at Resolver._isModuleResolved (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:477:42)
at Resolver._getAbsolutePath (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:455:17)
at Resolver.getModuleID (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:424:31)
at Runtime._shouldMock (/home/user/Desktop/Workspace/porject/node_modules/jest-runtime/build/index.js:1917:37)
at Runtime.requireModuleOrMock (/home/user/Desktop/Workspace/porject/node_modules/jest-runtime/build/index.js:1204:14)
at Proxy.render (/home/user/Desktop/Workspace/porject/components/newComponents/global/ChangeLanguage/index.vue:2903:14)
at /home/user/Desktop/Workspace/porject/node_modules/#vue/composition-api/dist/vue-composition-api.common.js:1891:35
at logError (node_modules/vue/dist/vue.common.dev.js:1902:13)
at globalHandleError (node_modules/vue/dist/vue.common.dev.js:1893:3)
at handleError (node_modules/vue/dist/vue.common.dev.js:1853:5)
at VueComponent.Vue._render (node_modules/vue/dist/vue.common.dev.js:3570:7)
at VueComponent.updateComponent (node_modules/vue/dist/vue.common.dev.js:4078:21)
at Watcher.get (node_modules/vue/dist/vue.common.dev.js:4490:25)
at Watcher.run (node_modules/vue/dist/vue.common.dev.js:4565:22)
here is a test file:
import { createLocalVue, shallowMount } from '#vue/test-utils'
import Vuex from 'vuex'
import { $axios } from '~/test/unit/__mocks__/util'
import storeConfig from '~/test/unit/__mocks__/store'
import ChangeLanguage from '~/components/global/ChangeLanguage/index.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
// eslint-disable-next-line import/no-named-as-default-member
const store = new Vuex.Store({
modules: {
index: {
state: storeConfig().modules.index.state,
getters: storeConfig().modules.index.getters,
mutations: storeConfig().modules.index.mutations,
actions: storeConfig().modules.index.actions,
namespaced: false,
},
},
})
describe('global/changeLanguage.vue', () => {
beforeEach(() => {
console.error = jest.fn()
})
const wrapper = shallowMount(ChangeLanguage, {
store,
localVue,
props: {
visibility: { default: false },
},
mocks: {
$axios,
},
})
test('checks if visibility changes and event emit', async () => {
await wrapper.setData({ isLanguagesVisible: true })
await wrapper.find('[data-test="change-visibility"]').trigger('click')
expect(wrapper.emitted()).toHaveProperty('changeVisibility')
})
})
and here is the component codes:
<template>
<div>
<img
:src="require(`~/assets/images/flags/${selectedLanguage.flagCode}.png`)"
:alt="selectedLanguage.name"
class="rounded-md w-8 h-6"
/>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "#nuxtjs/composition-api";
import { Language } from "~/types/components/layouts";
export default defineComponent({
setup() {
const selectedLanguage = ref<Language>({
code: "en",
name: "English",
link: "/",
flagCode: "us",
});
return {
selectedLanguage,
};
},
});
</script>
and here is the jest.config.js file:
module.exports = {
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'/^components/(.*)$/': '<rootDir>/components/$1',
'^vue$': 'vue/dist/vue.common.js',
},
moduleFileExtensions: ['ts', 'js', 'vue', 'json'],
transform: {
'^.+\\.ts$': 'ts-jest',
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/test/unit/fileTransformer.js',
},
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue',
],
testEnvironment: 'jsdom',
setupFiles: ['<rootDir>/test/unit/setup.js'],
}
and setup.js file:
import Vue from 'vue'
import { config } from '#vue/test-utils'
import * as CompositionApi from '#nuxtjs/composition-api'
Vue.use(CompositionApi)
Vue.config.silent = true
// Mock some of global components
config.stubs['nuxt-link'] = true
config.stubs['client-only'] = true
config.stubs.fa = true
// Mock some of global methods
config.mocks.$t = (i) => i
config.mocks.t = (i) => i
config.mocks.localePath = (i) => i
config.mocks.switchLocalePath = (i) => i
and fileTransformer.js file:
const path = require('path');
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};
and package.json file
{
"name": "project",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate",
"lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",
"lint": "npm run lint:js",
"test": "jest --watch"
},
"dependencies": {
"#fortawesome/free-brands-svg-icons": "^5.15.4",
"#fortawesome/free-solid-svg-icons": "^5.15.4",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/composition-api": "^0.30.0",
"#nuxtjs/i18n": "^7.0.3",
"#nuxtjs/pwa": "^3.3.5",
"cookie-universal-nuxt": "^2.1.5",
"core-js": "^3.15.1",
"gsap": "^3.8.0",
"nuxt": "^2.15.7",
"nuxt-fontawesome": "^0.4.0",
"vue": "^2.6.14",
},
"devDependencies": {
"#babel/eslint-parser": "^7.14.7",
"#nuxt/types": "^2.15.7",
"#nuxt/typescript-build": "^2.1.0",
"#nuxtjs/eslint-config-typescript": "^6.0.1",
"#nuxtjs/eslint-module": "^3.0.2",
"#nuxtjs/tailwindcss": "^4.2.0",
"#types/jest": "^27.0.2",
"#vue/test-utils": "^1.2.1",
"babel-core": "7.0.0-bridge.0",
"babel-jest": "^27.0.5",
"eslint": "^7.29.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-nuxt": "^2.0.0",
"eslint-plugin-vue": "^7.12.1",
"fibers": "^5.0.0",
"jest": "^27.0.5",
"postcss": "^8.3.5",
"prettier": "^2.3.2",
"sass": "^1.42.1",
"sass-loader": "^10.2.0",
"ts-jest": "^27.0.3",
"vue-jest": "^3.0.4",
"vuex": "^3.6.2"
}
}
I'm using nuxt 2 with typescript and composition API
how can i fix this?
Problem solved with ternary if:
<img
:src="
selectedLanguage.flagCode
? require(`~/assets/images/flags/${selectedLanguage.flagCode}.png`)
: ''
"
class="rounded-md w-8 h-6"
/>