product component (Ecommerce project) gets deleted after refreshing the productDetails page... React js project - javascript

So I'm a beginner in MERN stack and have been following a tutorial to build an e-commerce website. But I'm having some trouble with productDetails page in the frontend. So when I click on the product it shows its detail page but after refreshing the page goes blank, and again after going back to home page the product just gets deleted or disappears...Does anyone have an idea about how to solve this?
This is the productDetails.js code
import Carousel from "react-material-ui-carousel";
import "./ProductDetails.css";
import { useSelector, useDispatch } from "react-redux";
import { getProductDetails } from '../../actions/productAction';
import { useEffect } from 'react';
const ProductDetails = ({match}) => {
const dispatch = useDispatch();
const { product, loading, error} = useSelector(
(state) => state.productDetails);
useEffect( () => {
dispatch(getProductDetails(match.params.id));
}, [dispatch, match.params.id]);
return (
<Fragment>
<div className="ProductDetails">
<div>
<Carousel>
{
product.images &&
product.images.map((item, i) => (
<img
className="CarouselImage"
key={item.url}
src={item.url}
alt={`${i} Slide`}
/>
))
}
</Carousel>
</div>
</div>
</Fragment>
);
};
export default ProductDetails
This the Home.js code
import { CgMouse } from "react-icons/cg";
import "./Home.css";
import Product from "./Product.js"
import MetaData from "../layout/MetaData";
import { getProduct } from "../../actions/productAction";
import { useSelector, useDispatch} from "react-redux";
import Loader from "../layout/Loader/Loader";
import { useAlert } from "react-alert";
const Home = () => {
const alert = useAlert();
const dispatch = useDispatch();
const { loading, error, products, productsCount } = useSelector(
(state) => state.products);
useEffect (() => {
if (error) {
return alert.error(error);
}
dispatch(getProduct());
}, [dispatch, error, alert]);
return (
<Fragment>
{loading ? (
<Loader />
) : (
<Fragment>
<MetaData title="ECOMMERCE" />
<div className="banner">
<p>Welcome to Ecommerce</p>
<h1>FIND AMAZING PRODUCTS BELOW</h1>
<a href="#container">
<button>
Scroll <CgMouse />
</button>
</a>
</div>
<h2 className="homeHeading">Featured Products</h2>
<div className="container" id="container">
{products &&
products.map(product => (
<Product product={product} />
))}
</div>
</Fragment>
)}
</Fragment>
);
};
export default Home;
Also the product.js file
import React from 'react';
import { Link } from 'react-router-dom';
import ReactStars from "react-rating-stars-component";
const Product = ({ product }) => {
const options = {
edit: false,
color: "rgba (20,20,20,0.1)",
activeColor: "tomato",
size: window.innerWidth < 600 ? 20 : 25,
value:product.ratings,
isHalf:true
};
return (
<Link className='productCard' to={`/product/${product._id}`}>
<img src={product.images[0].url} alt={product.name} />
<p>{product.name}</p>
<div>
<ReactStars {...options} /> <span> ({product.numOfReviews} Reviews) </span>
</div>
<span>{`₹${product.price}`}</span>
</Link>
);
};
export default Product
These are the error I'm getting
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
at Carousel (http://localhost:3000/static/js/vendors~main.chunk.js:254237:5)
at WithStyles (http://localhost:3000/static/js/vendors~main.chunk.js:7092:31)
at div
at div
at ProductDetails (http://localhost:3000/static/js/main.chunk.js:1188:5)
at Route (http://localhost:3000/static/js/vendors~main.chunk.js:259420:29)
at Switch (http://localhost:3000/static/js/vendors~main.chunk.js:259622:29)
at Router (http://localhost:3000/static/js/vendors~main.chunk.js:259039:30)
at BrowserRouter (http://localhost:3000/static/js/vendors~main.chunk.js:257794:35)
at App (http://localhost:3000/static/js/main.chunk.js:277:48)
at Provider (http://localhost:3000/static/js/vendors~main.chunk.js:19626:23)
at Provider (http://localhost:3000/static/js/vendors~main.chunk.js:255302:20)
console.<computed> # index.js:1
printWarning # react-dom.development.js:67
error # react-dom.development.js:43
warnAboutUpdateOnUnmountedFiberInDEV # react-dom.development.js:23914
scheduleUpdateOnFiber # react-dom.development.js:21840
enqueueSetState # react-dom.development.js:12467
push../node_modules/react/cjs/react.development.js.Component.setState # react.development.js:365
(anonymous) # Carousel.js:313
setTimeout (async)
setActive # Carousel.js:312
componentDidMount # Carousel.js:217
commitLifeCycles # react-dom.development.js:20663
commitLayoutEffects # react-dom.development.js:23426
callCallback # react-dom.development.js:3945
invokeGuardedCallbackDev # react-dom.development.js:3994
invokeGuardedCallback # react-dom.development.js:4056
commitRootImpl # react-dom.development.js:23151
unstable_runWithPriority # scheduler.development.js:468
runWithPriority$1 # react-dom.development.js:11276
commitRoot # react-dom.development.js:22990
performSyncWorkOnRoot # react-dom.development.js:22329
scheduleUpdateOnFiber # react-dom.development.js:21881
updateContainer # react-dom.development.js:25482
(anonymous) # react-dom.development.js:26021
unbatchedUpdates # react-dom.development.js:22431
legacyRenderSubtreeIntoContainer # react-dom.development.js:26020
render # react-dom.development.js:26103
(anonymous) # index.js:16
./src/index.js # index.js:18
__webpack_require__ # bootstrap:851
fn # bootstrap:150
1 # store.js:23
__webpack_require__ # bootstrap:851
checkDeferredModules # bootstrap:45
webpackJsonpCallback # bootstrap:32
(anonymous) # main.chunk.js:1
index.js:1
GET http://localhost:3000/product/%3Canonymous%3E 404 (Not Found)

the Warning: Can't perform a React state update on an unmounted component is coming from any useEffect but i am not sure that it's in ProductDetails.js try the below code
const { id } = useParams();
useEffect( () => {
dispatch(getProductDetails(id));
}, [dispatch, id]);
also this is not the way to use the effects as well.
useEffect (() => {
dispatch(getProduct());
}, [dispatch]);
useEffect(() => {
if (error) {
alert.error(error); // i am not sure why you return here I never used react-alert lib but I don't think you return it and add it as dep in array.
}
}, [error])
try passing empty dep arrays in all useEffect to check the results.

Related

My react project does not render properly when I change a category

ok so I have this code (I'm using firebase) and this is my component Cards, I have another Component which has a link button that leads to another cathegory of my store, but in this code when I try to render the cathegory which is supposed to lead to, it doesnt render anything
import Card from "react-bootstrap/Card";
import { collection, getDocs} from "firebase/firestore";
import { db } from "../firebaseConfig/firebase.js";
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import "./Cards.css"
import { useParams } from "react-router-dom";
const Cards = () => {
const [products, setProducts] = useState([]);
const productsCollection = collection(db, "zproducts");
const categoria = useParams()
const getProducts = async () => {
const data = await getDocs(productsCollection);
if(categoria.category){
const dataCategory = data.docs.map((doc) => ({ ...doc.data(), id: doc.id }))
setProducts(dataCategory.filter(i=> i.category == categoria.category))
console.log(products)
}else {
setProducts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
}
}
useEffect(()=>{
getProducts()
},[categoria.category])
return (
<>
<div className="d-flex flex-wrap justify-content-center">
{products.map((product) => (
<Card className="card" key={product.id} style={{ width: "18rem" }}>
<Card.Img variant="top" className="cardImg" src={product.imgProduct} />
<Card.Body>
<Card.Title>{product.name}</Card.Title>
<div className="d-flex justify-content-around">
<Link variant="primary" className="btn btn-dark boton btnDetalles" to={`/Item/${product.id}`}>Ver Detalles</Link>
</div>
</Card.Body>
</Card>
))}
</div>
</>
);
}
export default Cards;
also when I open the console, I have a bunch of errors for some reasons
Uncaught TypeError: Cannot read properties of undefined (reading 'indexOf')
at rt.fromString (bundle.js:2286:13)
at Aa (bundle.js:18047:18)
at ItemDetailContainer (bundle.js:168:73)
at renderWithHooks (bundle.js:53227:22)
at mountIndeterminateComponent (bundle.js:56513:17)
at beginWork (bundle.js:57809:20)
at HTMLUnknownElement.callCallback (bundle.js:42819:18)
at Object.invokeGuardedCallbackDev (bundle.js:42863:20)
at invokeGuardedCallback (bundle.js:42920:35)
at beginWork$1 (bundle.js:62794:11)
bundle.js:55331 The above error occurred in the <ItemDetailContainer> component:
at ItemDetailContainer (http://localhost:3000/static/js/bundle.js:166:80)
at RenderedRoute (http://localhost:3000/static/js/bundle.js:67267:5)
at Routes (http://localhost:3000/static/js/bundle.js:67732:5)
at Router (http://localhost:3000/static/js/bundle.js:67670:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:65875:5)
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError # bundle.js:55331
bundle.js:49671 Uncaught TypeError: Cannot read properties of undefined (reading 'indexOf')
at rt.fromString (bundle.js:2286:13)
at Aa (bundle.js:18047:18)
at ItemDetailContainer (bundle.js:168:73)
at renderWithHooks (bundle.js:53227:22)
at mountIndeterminateComponent (bundle.js:56513:17)
at beginWork (bundle.js:57809:20)
at beginWork$1 (bundle.js:62772:18)
at performUnitOfWork (bundle.js:62041:16)
at workLoopSync (bundle.js:61964:9)
at renderRootSync (bundle.js:61937:11)
my github link to the proyect: https://github.com/LeandroMore1/PreEntrega2-More

I am trying to render data from mongodb server to react app. And it's not working

This is the console log error
Uncaught Error: Objects are not valid as a React child (found: object with keys {_id, inputText, __v}). If you meant to render a collection of children, use an array instead.
at throwOnInvalidObjectType (react-dom.development.js:14887:1)
at reconcileChildFibers (react-dom.development.js:15828:1)
at reconcileChildren (react-dom.development.js:19167:1)
at updateHostComponent (react-dom.development.js:19924:1)
at beginWork (react-dom.development.js:21618:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
I am being able to save my input to the server but am getting error while trying to fetch it.
Here's the component which is supposed to return the list.
import React, { useState, useEffect } from "react";
import ToDoItem from "./ToDoItem";
import InputArea from "./InputArea";
import "bootstrap/dist/css/bootstrap.min.css";
import axios from "axios";
const ToDoList = () => {
const [x, setX] = useState([]);
const xList = () => {
return x.map((y,index) => {
return <ToDoItem key={index} text={y} />;
});
};
useEffect(() => {
axios
.get("http://localhost:5000/")
.then((res) => {
setX(res.data);
})
.catch((err) => console.log(err));
}, []);
return (
<div className="container">
<div className="heading">
<h1>To-Do List</h1>
</div>
<InputArea />
<div>{xList()}</div>
</div>
);
};
export default ToDoList;
That specific error usually occurs when you are trying to print out an entire object instead of lets say the properties from each object.
Can you console.log the list and let us know what properties you have for each object?

though setting keyExtractor, I'm getting VirtualizedList: missing keys for items, make sure to specify a key or provide a custom keyExtractor

I've set a custom Key extractor for the orders items in the cart, also getting VirtualizedList: missing keys for items, make sure to specify a key or id property on each item or provide a custom key extractor.
Here is code for the orders page.
import React, { useState, useCallback} from "react"
import { View, FlatList, Text} from "react-native"
import axios from "axios"
import baseURL from "../../assets/common/baseUrl"
import { useFocusEffect } from "#react-navigation/native"
import OrderCard from "../../Shared/OrderCard"
const Orders = (props) => {
const [orderList, setOrderList] = useState();
useFocusEffect(
useCallback(
() => {
getOrders();
return () => {
setOrderList();
}
},
[],
)
)
const getOrders = () => {
axios
.get(`${baseURL}orders`)
.then((x) => {
setOrderList(x.data);
})
.catch((error) => console.log(error))
}
return (
<View>
<FlatList
data={orderList}
renderItem={({ item }) => (
<OrderCard navigation={props.navigation} {...item} editMode={true}/>
)}
keyExtractor={(item) => item.id}
/>
</View>
)
}
export default Orders;
After placing the orders by adding item to the cart,
There is no error shown or pop up in the mobile app,
The error is shown in the console where the react-native app is run
VirtualizedList: missing keys for items, make sure to specify a key or id property on each item or provide a custom keyExtractor.,
at node_modules\react-native\Libraries\LogBox\LogBox.js:117:10 in registerWarning
at node_modules\react-native\Libraries\LogBox\LogBox.js:63:8 in warnImpl
at node_modules\react-native\Libraries\LogBox\LogBox.js:36:4 in console.warn
at node_modules\expo\build\environment\react-native-logs.fx.js:18:4 in warn
at node_modules\react-native\Libraries\Lists\VirtualizedList.js:1075:8 in render
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:12479:21 in finishClassComponent
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:12404:43 in updateClassComponent
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:19182:22 in beginWork$1
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18086:22 in performUnitOfWork
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18014:38 in workLoopSync
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17978:18 in renderRootSync
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17675:33 in performSyncWorkOnRoot
at [native code]:null in performSyncWorkOnRoot
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5322:31 in runWithPriority$argument_1at node_modules\scheduler\cjs\scheduler.development.js:653:23 in unstable_runWithPriority
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5317:21 in flushSyncCallbackQueueImplat node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5305:28 in flushSyncCallbackQueue
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17719:28 in batchedUpdates$1
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:2492:29 in batchedUpdates
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:2638:16 in _receiveRootNodeIDEvent
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:2767:27 in receiveTouches
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
at [native code]:null in callFunctionReturnFlushedQueue
Here is the picture for it

React with redux

I am following the tutorial on linked in for react with Redux and Next.js. the code is working fine until I added Redux. I cannot understand the error below, it does not give me much info. Can some one explain to me where is the issue.
the tutorial did come with Exercise files but even they have the same issue. It could be something in my setup perhaps.
No page context
Error: No page context
at Function._callee$ (C:\learnings\SSR\node_modules\next-redux-wrapper\lib\index.js:164:23)
at tryCatch (C:\learnings\SSR\node_modules\regenerator-runtime\runtime.js:62:40)
at Generator.invoke [as _invoke] (C:\learnings\SSR\node_modules\regenerator-runtime\runtime.js:288:22)
at Generator.prototype.(anonymous function) [as next] (C:\learnings\SSR\node_modules\regenerator-runtime\runtime.js:114:21)
at asyncGeneratorStep (C:\learnings\SSR\node_modules\next-redux-wrapper\lib\index.js:18:103)
at _next (C:\learnings\SSR\node_modules\next-redux-wrapper\lib\index.js:20:194)
at C:\learnings\SSR\node_modules\next-redux-wrapper\lib\index.js:20:364
at new Promise (<anonymous>)
at Function.<anonymous> (C:\learnings\SSR\node_modules\next-redux-wrapper\lib\index.js:20:97)
at Function.getInitialProps (C:\learnings\SSR\node_modules\next-redux-wrapper\lib\index.js:205:22)
at _callee$ (C:\learnings\SSR\node_modules\next\dist\lib\utils.js:86:30)
at tryCatch (C:\learnings\SSR\node_modules\regenerator-runtime\runtime.js:62:40)
at Generator.invoke [as _invoke] (C:\learnings\SSR\node_modules\regenerator-runtime\runtime.js:288:22)
at Generator.prototype.(anonymous function) [as next] (C:\learnings\SSR\node_modules\regenerator-runtime\runtime.js:114:21)
at asyncGeneratorStep (C:\learnings\SSR\node_modules\#babel\runtime-corejs2\helpers\asyncToGenerator.js:5:24)
at _next (C:\learnings\SSR\node_modules\#babel\runtime-corejs2\helpers\asyncToGenerator.js:27:9)
My Index.js looks like this
import React from 'react';
import { bindActionCreators } from 'redux';
import { initStore, initialPosters, addItem } from '../store';
import withRedux from 'next-redux-wrapper';
import './index.css';
import Poster from './Poster';
class Index extends React.Component {
static async getInitialProps ({ store }) {
store.dispatch(initialPosters());
}
render () {
return (
<div className="App">
<header className="App-header">
<img src="/static/logo.png"
className="static-logo" alt="logo"
/>
</header>
<div className="Grid">
{
this.props.Posters.map((Poster) => (
<Poster key={Poster.id} />
))
}
</div>
</div>
)
}
};
const mapDispatchToProps = (dispatch) => {
return {
initialPosters: bindActionCreators(initialPosters, dispatch),
addItem: bindActionCreators(addItem, dispatch)
}
}
const mapStateToProps = (state) => {
return {
Posters: state.Posters,
}
}
export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(Index);
my store.js
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunkMiddleware from 'redux-thunk';
import data from './data/data.json';
// initial state
const startState = {
posters: []
}
// Actions
export const initialposters = () => {
return {
type: 'INITIALPOSTERS',
posters: data
}
}
export const addItem = (item) => {
return {
type: 'ADD',
item
}
}
// reducers
export const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INITIALPOSTERS':
return {
posters: action.posters,
}
case 'ADD':
return {
...state,
posters: [...state.posters, action.item]
}
default: return state
}
}
// create store
export const initStore = (initialState = startState) => {
return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware)));
}
the Poster.js
import './Poster.css';
const Poster = (props) => (
<div className="Poster">
<div className="front">
<img src="/static/product.jpg" alt="Avatar" className="Poster-image" />
<div className="container">
<h3>A product <span className="price">$24.99</span></h3>
<p>A description </p>
</div>
</div>
</div>
);
export default Poster;
The error stack trace suggests line 164 in index.js in next-redux-wrapper which ends up here
case 2:
if (appCtx.ctx) {
_context.next = 4;
break;
}
throw new Error('No page context');
I am very new to react and redux so i am not able to make anything out of it. the good thing is its not working so there is opportunity to solve something here :D
it is a paid tutorial ; so not sure if this link would work for people.
https://www.lynda.com/React-js-tutorials/React-Server-Side-Rendering/679641-2.html

How to test nested connected components using Enzyme?

I am trying to test nested connected components (Redux connected):
The Main component has Container component and are provided by store wrapper in App.
import React, { Component } from 'react';
import Main from './components/Main';
import './App.css';
import { Provider } from 'react-redux'
import createStore from './redux'
import applyConfigSettings from './config'
// Apply config overrides
applyConfigSettings()
const store = createStore()
class App extends Component {
render() {
return (
<Provider store={store}>
<Main/>
</Provider>
);
}
}
export default App;
Main.js
import React, { Component } from 'react';
import logo from '../logo.svg';
import { connect } from 'react-redux'
import Container from './Container'
export class Main extends Component {
render(){
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to Pomodoro App</h1>
</header>
<Container/>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
fetching: state.user.fetching,
}
}
const mapDispatchToProps = (dispatch) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Main)
Container.js
import React, { Component } from 'react';
import Grid from 'material-ui/Grid';
import { connect } from 'react-redux'
export class Container extends Component{
render(){
return (
<div className="grid-root">
</div>
)
}
}
const mapStateToProps = (state) => {
return {
fetching: state.user.fetching,
}
}
const mapDispatchToProps = (dispatch) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Container)
All this is created using Create-react-app library. I have installed Enzyme too for testing. Here is my test file for Main.test.js
import React from 'react';
import { shallow, mount } from 'enzyme';
import {Main} from '../../components/Main'
import ContainerConnect, {Container} from '../../components/Container';
import configureStore from 'redux-mock-store';
import { Provider, connect} from 'react-redux';
describe('Main', () => {
let wrapper;
let mountWrapper;
it('wraps all the contents in a div with .App class', () => {
wrapper = shallow(<Main />);
expect(wrapper.find('.App').length).toEqual(1);
});
it('wraps content of header in a div with .App-header class', () => {
wrapper = shallow(<Main />);
expect(wrapper.find('.App-header').length).toEqual(1);
});
it('mount', () => {
const middlewares = [];
const mockStore = configureStore(middlewares);
const initialState = {}
const store = mockStore(initialState)
mountWrapper = mount(
<Provider store={store}>
<Main />
</Provider>
);
});
})
I get following error for the last test:
FAIL src/tests/components/Main.test.js
● Console
console.error node_modules/react-dom/cjs/react-dom.development.js:9643
The above error occurred in the <Connect(Container)> component:
in Connect(Container) (at Main.js:16)
in div (at Main.js:11)
in Main (at Main.test.js:31)
in Provider (created by WrapperComponent)
in WrapperComponent
Consider adding an error boundary to your tree to customize error handling behavior.
Visit some link to fb to learn more about error boundaries.
● Main › mount
TypeError: Cannot read property 'fetching' of undefined
at Function.mapStateToProps [as mapToProps] (src/components/Container.js:18:30)
at mapToPropsProxy (node_modules/react-redux/lib/connect/wrapMapToProps.js:54:92)
at Function.detectFactoryAndVerify (node_modules/react-redux/lib/connect/wrapMapToProps.js:63:19)
at mapToPropsProxy (node_modules/react-redux/lib/connect/wrapMapToProps.js:54:46)
at handleFirstCall (node_modules/react-redux/lib/connect/selectorFactory.js:37:18)
at pureFinalPropsSelector (node_modules/react-redux/lib/connect/selectorFactory.js:85:81)
at Object.runComponentSelector [as run] (node_modules/react-redux/lib/components/connectAdvanced.js:43:25)
at Connect.initSelector (node_modules/react-redux/lib/components/connectAdvanced.js:195:23)
at new Connect (node_modules/react-redux/lib/components/connectAdvanced.js:136:15)
at constructClassInstance (node_modules/react-dom/cjs/react-dom.development.js:6801:20)
at updateClassComponent (node_modules/react-dom/cjs/react-dom.development.js:8336:9)
at beginWork (node_modules/react-dom/cjs/react-dom.development.js:8982:16)
at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:11814:16)
at workLoop (node_modules/react-dom/cjs/react-dom.development.js:11843:26)
at renderRoot (node_modules/react-dom/cjs/react-dom.development.js:11874:9)
at performWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:12449:24)
at performWork (node_modules/react-dom/cjs/react-dom.development.js:12370:9)
at performSyncWork (node_modules/react-dom/cjs/react-dom.development.js:12347:5)
at requestWork (node_modules/react-dom/cjs/react-dom.development.js:12247:7)
at scheduleWorkImpl (node_modules/react-dom/cjs/react-dom.development.js:12122:13)
at scheduleWork (node_modules/react-dom/cjs/react-dom.development.js:12082:12)
at scheduleRootUpdate (node_modules/react-dom/cjs/react-dom.development.js:12710:5)
at updateContainerAtExpirationTime (node_modules/react-dom/cjs/react-dom.development.js:12738:12)
at Object.updateContainer (node_modules/react-dom/cjs/react-dom.development.js:12765:14)
at ReactRoot.Object.<anonymous>.ReactRoot.render (node_modules/react-dom/cjs/react-dom.development.js:16069:15)
at node_modules/react-dom/cjs/react-dom.development.js:16488:14
at Object.unbatchedUpdates (node_modules/react-dom/cjs/react-dom.development.js:12557:12)
at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:16484:17)
at Object.render (node_modules/react-dom/cjs/react-dom.development.js:16543:12)
at Object.render (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:218:50)
at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:98:16)
at mount (node_modules/enzyme/build/mount.js:19:10)
at Object.it (src/tests/components/Main.test.js:29:42)
at new Promise (<anonymous>)
at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
Is it so hard to test nested connected components? I have to go and use more of it going forward in the application as well. And also does this mean that testing button clicks and all is harder to test as well?
Based on what you are trying to test, you should not have to deal with redux at all.
Since you are testing your <Main /> component and whether it renders the header properly, just mock your <Container /> completely:
jest.mock('../../components/Container', () => ()=> <div id="mockContainer">
mockContainer
</div>);
Then you can shallow mount your <Main /> without worrying about redux.
After that, when you start unit testing your <Container />, just unit test the React.Component class and do not bother with the connected Component, testing it is redundant.
In other words, you should be able to test any React app without ever having to mock the redux store. Just mock connected components entirely.
More info here

Categories

Resources