Reputation: 2864
I am new to react programming. I am writing test cases for redux connect component. So i am receiving props from different reducers.I am using jest and react testing library for writing test cases. I am using redux-mock-store to mock store data but that is not working.
TestComponent:
import customerInfo from './customerInfo.json'
import appInfo from './appInfo.json'
const middlewares = []
const mockStore = configureStore(middlewares)
const initialState = {
customerInfo:customerInfo,
appInfo:appInfo
}
let appStore = mockStore(initialState)
render(
<Provider store={appStore}>
<PersistGate loading={null} persistor={persistor}>
<Router history={newHistory}>
<Home/>
</Router>
</PersistGate>
</Provider>
);
HomeComponent:
<Home/>
const mapStateToProps = (state) => {
return {
appInfo: state.appReducer.appInfo,
customerInfo: state.userReducer.customerInfo
};
};
Upvotes: 0
Views: 137
Reputation: 102347
You didn't provide the correct initial state to mockStore
function.
It should be:
const initialState = {
userReducer: { customerInfo },
appReducer: { appInfo }
}
A completed example:
import { render } from "@testing-library/react";
import React from "react";
import { Provider, connect } from "react-redux";
import configureStore from 'redux-mock-store';
const Home = (props) => {
console.log(props)
return null;
}
const mapStateToProps = (state) => {
return {
appInfo: state.appReducer.appInfo,
customerInfo: state.userReducer.customerInfo
};
};
const HomeComponent = connect(mapStateToProps)(Home)
const middlewares = []
const mockStore = configureStore(middlewares)
describe('61453980', () => {
test('should pass', () => {
const customerInfo = { name: 'nick' }
const appInfo = { appId: '123' }
const initialState = {
userReducer: { customerInfo },
appReducer: { appInfo }
}
let appStore = mockStore(initialState)
render(
<Provider store={appStore}>
<HomeComponent />
</Provider>
)
})
})
Test result:
PASS stackoverflow/61453980/index.test.tsx (19.847 s)
61453980
✓ should pass (51 ms)
console.log
{
appInfo: { appId: '123' },
customerInfo: { name: 'nick' },
dispatch: [Function: dispatch]
}
at Home (stackoverflow/61453980/index.test.tsx:8:11)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 21.042 s
Upvotes: 0