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

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

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

map not defined in my react after bring data from database

i have a website with api to get movies,i have a user in my web and this user can like a movie and get him into his favorite. then he have a commponent that call favorite and i want to do there a get request from my data base and bring him the title of my movie.after he get the title i do in my useeffect an api request to get the poster and all the details of the movie and then i wanna to show it in my favorite useing map function.
but i have a problem
my map dosent work or if it work he dosent bring the data from the api
this is the favorite componnent
import { getAllFavorite } from "../../service/favServics";
import { useState, useEffect } from "react";
import PageHeader from "../common/pageHeader";
import FavoriteChiled from "./favoritechild";
function Favorite() {
const [favorite, setFavorite] = useState([]);
const [movies, setMovies] = useState([]);
const [data, setData] = useState([]);
async function getAll() {
const { data } = await getAllFavorite();
setFavorite(data);
for (let i = 0; i < data.length; i++) {
const url = `http://www.omdbapi.com/?s=${data[i]}&apikey=aea06659`;
const response = await fetch(url);
const responseJson = await response.json();
const obj = responseJson.Search[0];
if (responseJson.Search) {
setMovies(obj.Title);
}
}
}
useEffect(() => {
getAll(favorite);
}, []);
This is the return of favorite component
<div className="row">
{movies.map((movie) => (
<FavoriteChiled movie={movie} />
))}
</div>
this is the child componnent
function FavoriteChiled(props) {
let { movies } = props;
return (
<>
<div key={movies.imdbID} className="image-container d-flex justify-content-start m-3">
<img src={movies.Poster} alt="movie"></img>
</div>
</>
);
}
the console error
favorite.jsx:32 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
at Favorite (favorite.jsx:32:1)
at renderWithHooks (react-dom.development.js:16305:1)
at updateFunctionComponent (react-dom.development.js:19588:1)
at beginWork (react-dom.development.js:21601: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)
at workLoopSync (react-dom.development.js:26466:1)`
or this error
favorite.jsx:32 Uncaught TypeError: movies.map is not a function
at Favorite (favorite.jsx:32:1)
at renderWithHooks (react-dom.development.js:16305:1)
at updateFunctionComponent (react-dom.development.js:19588:1)
at beginWork (react-dom.development.js:21601: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)
at workLoopSync (react-dom.development.js:26466:1)`

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

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.

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?

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