Result of unit test always "Received:0" - reactjs

Unit test code cannot read component "jsx" content
the test result is always "Received: 0"
This is a screenshot of the unit test result using enzyme and jest with react.js
//**************************************component.js*************************************************//
class NetworkConfig extends Component {
constructor() {
super();
this.state = {
dataDeviceConfig: {
dhcp: false,
macAddress: '',
ipAddress: '',
subMask: '',
dns: '',
gateway: '',
},
alertMessage: "",
loader: false
};
}
render() {
return (
<div>
{console.log("Diagnostic Data", this.state.dataDeviceConfig)}
<Form onSubmit={this.handleSubmit}>
<div className="sn-forms-settings">
<FormItem
label={<IntlMessages id="settings.label.DHCP" />}
>
{getFieldDecorator('dhcp', {
})(
<Switch ............... />
)}
</FormItem>
<FormItem
label={(
<span>
<IntlMessages id="settings.label.MacAdres" />
</span>
)}
>
{getFieldDecorator('macAddress', {
initialValue: this.state.dataDeviceConfig.macAddress
})(
<label name="macAddress">{this.state.dataDeviceConfig.macAddress}</label>
)}
</FormItem>
</div>
</Form>
</div>
);
}
}
const mapStateToProps = ({ settingSense, common }) => {
const { dataDeviceConfig } = settingSense;
const {
loader,
alertMessage,
showAlert,
alertMessageStatus,
alertMessageComponent
} = common;
return {
dataDeviceConfig,
loader,
alertMessage,
showAlert,
alertMessageStatus,
alertMessageComponent
}
};
const NetworkConfigForm = Form.create()(NetworkConfig);
export default injectIntl(connect(mapStateToProps, {
getDevicEtherConfigAction, setDevicEtherConfigAction
, showLoaderAction, hideAlertAction, hideLoaderAction
})(NetworkConfigForm));
//**************************************component.test.js**********************************************//
import React from 'react';
import Enzyme,{shallow,configur } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16';
import configureMockStore from 'redux-mock-store';
import NetworkConfigForm from '../../../.....................';
import {Input} from "antd";
import {mountWithIntl,shallowWithIntl} from '../../helpers/intl-enzyme-test-helper.js';
Enzyme.configure({
adapter: new EnzymeAdapter(),
disableLifecycleMethods: false
});
describe('Network Config Test', () => {
it('render NetworkConfig Component', () => {
const state = {
settingSense:{
dataDeviceConfig: {
dhcp: false,
macAddress: '',
ipAddress: '',
subMask: '',
dns: '',
gateway: '',
}
},
common:{
loader: false,
alertMessage:'',
showAlert: false,
alertMessageStatus:'MESSAGE_SUCCESS',
alertMessageComponent:'ALERT_DEVICE_ETHER_CONFIG'
}
};
const mockStore = configureMockStore();
const store = mockStore(state);
const wrapper = shallowWithIntl(<NetworkConfigForm store={store}/>).dive();
expect(wrapper.find('.sn-forms-settings').children().length).toEqual(2)
});
});

Related

Converting DraftJS class component to Functional component

The following Draftjs code is in class component. The plugins like CreateImage, Focus Plugin, and BlockDndPlugin are being imported from the DraftJS. I would be grateful if somebody can convert the class-based react components into Functional based react components...............................................................................................................................................................................................................................................................................................
import React, { Component } from 'react';
import { convertFromRaw, EditorState } from 'draft-js';
import Editor, { composeDecorators } from '#draft-js-plugins/editor';
import createImagePlugin from '#draft-js-plugins/image';
import createFocusPlugin from '#draft-js-plugins/focus';
import createBlockDndPlugin from '#draft-js-plugins/drag-n-drop';
import editorStyles from './editorStyles.module.css';
const focusPlugin = createFocusPlugin();
const blockDndPlugin = createBlockDndPlugin();
const decorator = composeDecorators(
focusPlugin.decorator,
blockDndPlugin.decorator
);
const imagePlugin = createImagePlugin({ decorator });
const plugins = [blockDndPlugin, focusPlugin, imagePlugin];
/* eslint-disable */
const initialState = {
entityMap: {
0: {
type: 'IMAGE',
mutability: 'IMMUTABLE',
data: {
src: '/images/canada-landscape-small.jpg',
},
},
},
blocks: [
{
key: '9gm3s',
text:
'You can have images in your text field which are draggable. Hover over the image press down your mouse button and drag it to another position inside the editor.',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
{
key: 'ov7r',
text: ' ',
type: 'atomic',
depth: 0,
inlineStyleRanges: [],
entityRanges: [
{
offset: 0,
length: 1,
key: 0,
},
],
data: {},
},
{
key: 'e23a8',
text:
'You can checkout the alignment tool plugin documentation to see how to build a compatible block plugin …',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
};
/* eslint-enable */
export default class CustomImageEditor extends Component {
state = {
editorState: EditorState.createWithContent(convertFromRaw(initialState)),
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
focus = () => {
this.editor.focus();
};
render() {
return (
<div>
<div className={editorStyles.editor} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
ref={(element) => {
this.editor = element;
}}
/>
</div>
</div>
);
}
}
You can use useState and useRef hooks in FC & Modify your component accordingly..
const CustomImageEditor = () => {
const [editorState, setEditorState] = useState(
EditorState.createWithContent(convertFromRaw(initialState))
);
const editor = useRef();
const onChange = (editorStates) => {
setEditorState(editorStates);
};
const focus = () => {
editor.current.focus();
};
return (
<div>
<div className={editorStyles.editor} onClick={focus}>
<Editor
editorState={editorState}
onChange={onChange}
plugins={plugins}
ref={editor}
/>
</div>
</div>
);
};

I can not return data with useSelector in react redux

I want save all input values in redux with dispatch and with useSelector return all data that saved in redux , in redux I create an object and that object have many objects , but I can not return data from redux with useSelector :
import React , { useState } from 'react';
import { useForm } from 'react-hook-form';
import {ButtonForm} from '../../partComponents/button';
import Input from '../../partComponents/input';
import { createStore } from 'redux'
import { Link } from 'react-router-dom';
import {ActionCreators} from '../../redux/constants/profile';
import { reducer } from '../../redux/reducer/profile'
import { useDispatch , useSelector } from 'react-redux'
const Signin = () =>{
const dispatch = useDispatch();
const selector = useSelector(state => state.reducer);
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => {
dispatch(ActionCreators.addProfile(data))
// console.log(s.getState())
};
return(
<section className="section-signin">
<div className="app__header">
<img src={anarLogo} className="app__header--logo" alt="header logo" />
</div>
<form className='signin__form' onSubmit={handleSubmit(onSubmit)}>
<Input
register={register}
inputName='Email'
inputType='text'
inputClass='form__input--text'
inputPlaceholder='Email'
inputErrors = {errors}
inputLabel = 'email'
rules={{ required: true, minLength: 5
}}
/>
<Input
register={register}
inputName='Full Name'
inputType='text'
inputClass='form__input--text'
inputPlaceholder='Full Name'
inputErrors = {errors}
inputLabel = 'fullname'
rules={{ required: true, maxLength: 30, minLength: 3
}}
/>
<Input
register={register}
inputName='Username'
inputType='text'
inputClass='form__input--text'
inputPlaceholder='Username'
inputErrors = {errors}
inputLabel = 'username'
rules={{ required: true, maxLength: 20, minLength: 3
}}
/>
<Input
register={register}
inputName='Password'
inputType='password'
inputClass='form__input--password'
inputPlaceholder='Password'
inputErrors = {errors}
inputLabel = 'password'
rules={{ required: true, maxLength: 20, minLength: 8 ,
pattern: {
value: new RegExp("(?=.*[a-z])(?=.*[0-9])"),
message: 'Password must contain at least one letter or number'
}
}}
/>
<ButtonForm
buttonValue='Submit'
buttonType='submit'
buttonClass='form__button--white'
/>
<p className='signin__message'>Have an account? <Link className='signin__message--link' to='/login'>Log in</Link></p>
here I want print fullname of user that assigned in website:
<h1>hello {selector.profile.fullname}</h1>
</form>
</section>
)
}
my reducer file :
import { Types } from '../constants/actionTypes';
import { createStore } from 'redux'
const initialState = {
profile : {
email: '',
fullname: '',
username: '',
password: ''
},
formSubmitted: false
}
export const reducer = (state = initialState , action) => {
switch(action.type){
case Types.ADD_USER:
console.log('sing In' , action.payload.user);
return{
...state,
profile: action.payload.user,
formSubmitted: false
}
case Types.LOGIN:
console.log('login' , action.payload.user)
return{
...state,
profile: action.payload.user,
formSubmitted: false
}
case Types.FORM_SUBMITION_STATUS:
return {
...state,
formSubmitted: action.payload.status
}
default:
return state;
}
}
The selector returns a partial state, state => state.reducer has no meaning since your state doesn't have any reducer part.
Since you want to return all your state, just select it:
const state = useSelector(state => state);
state.profile.fullname

onImageLoad callback react js

Im using react-image-gallery: https://www.npmjs.com/package/react-image-gallery
Im trying to set a useState variable on onImageLoad, but its not working.
the docs say to use a callback, and I tried using a callback but I don't think I was doing it correctly for functional components.
Could someone show me how to create the proper callback to get the onImageLoad prop?
Docs say..... onImageLoad: Function, callback(event)
import React, { useEffect, useState} from "react";
import ImageGallery from 'react-image-gallery';
import "react-image-gallery/styles/css/image-gallery.css";
const Job = (props) => {
const {job} = props;
const [image, setImage] = useState([]);
const [showImages, setShowImages] = useState(false);
useEffect(() => {
async function onLoad() {
try {
const downloadedImage = await getImage(job.jobId);
setImage(downloadedImage);
} catch (e) {
alert(e);
}
}
onLoad();
}, []);
return (
{showImages ? (
<div style={{width: "95%"}}>
<ImageGallery items={image} onImageLoad={() => setShowImages(true)}/>
</div>
):(
<div>
<IonSpinner name="crescent" />
</div>
)}
);
Example given from package website
import React from 'react';
import ReactDOM from 'react-dom';
import ImageGallery from '../src/ImageGallery';
const PREFIX_URL = 'https://raw.githubusercontent.com/xiaolin/react-image-gallery/master/static/';
class App extends React.Component {
constructor() {
super();
this.state = {
showIndex: false,
showBullets: true,
infinite: true,
showThumbnails: true,
showFullscreenButton: true,
showGalleryFullscreenButton: true,
showPlayButton: true,
showGalleryPlayButton: true,
showNav: true,
isRTL: false,
slideDuration: 450,
slideInterval: 2000,
slideOnThumbnailOver: false,
thumbnailPosition: 'bottom',
showVideo: {},
};
this.images = [
{
thumbnail: `${PREFIX_URL}4v.jpg`,
original: `${PREFIX_URL}4v.jpg`,
embedUrl: 'https://www.youtube.com/embed/4pSzhZ76GdM?autoplay=1&showinfo=0',
description: 'Render custom slides within the gallery',
renderItem: this._renderVideo.bind(this)
},
{
original: `${PREFIX_URL}image_set_default.jpg`,
thumbnail: `${PREFIX_URL}image_set_thumb.jpg`,
imageSet: [
{
srcSet: `${PREFIX_URL}image_set_cropped.jpg`,
media : '(max-width: 1280px)',
},
{
srcSet: `${PREFIX_URL}image_set_default.jpg`,
media : '(min-width: 1280px)',
}
]
},
{
original: `${PREFIX_URL}1.jpg`,
thumbnail: `${PREFIX_URL}1t.jpg`,
originalClass: 'featured-slide',
thumbnailClass: 'featured-thumb',
description: 'Custom class for slides & thumbnails'
},
].concat(this._getStaticImages());
}
_onImageLoad(event) {
console.debug('loaded image', event.target.src);
}
render() {
return (
<section className='app'>
<ImageGallery
ref={i => this._imageGallery = i}
items={this.images}
onImageLoad={this._onImageLoad}
/>
</section>
);
}
}
ReactDOM.render(<App/>, document.getElementById('container'));

React Native Store value in redux

i wanted to store the Email in the redux store and i am unable to do so here is my sign in component and redux store any help would be appreciated i am using react-navigation
My Dispatch Method is invoked on the initial load as well as on every key stroke for email input i want that to invoke only on hit of continue button
I need a way to store the email in the store and retrieve it in some other screen later
SignUp.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
KeyboardAvoidingView,
Keyboard,
TouchableWithoutFeedback,
Alert
} from 'react-native';
import { SocialIcon } from 'react-native-elements';
import PropTypes from 'prop-types';
import { Header } from 'react-navigation';
import { connect } from 'react-redux';
import {
Container, Footer, FooterContainer, DefaultInput, Typography
} from '../components/common';
import { validate } from '../config';
import * as actionTypes from '../store/actions';
const styles = StyleSheet.create({
container: {
flex: 1
},
input: {
width: '80%',
height: 40
}
});
class SignUp extends Component {
state = {
controls: {
email: {
value: '',
valid: false,
validationRules: {
isEmail: true
},
touched: false
},
password: {
value: '',
valid: false,
validationRules: {
minLength: 6
},
touched: false
},
confirmPassword: {
value: '',
valid: false,
validationRules: {
equalTo: 'password'
},
touched: false
}
}
};
updateInputState = (key, value) => {
let connectedValue = {};
const stateObject = this.state;
if (stateObject.controls[key].validationRules.equalTo) {
const equalControl = stateObject.controls[key].validationRules.equalTo;
const equalValue = stateObject.controls[equalControl].value;
connectedValue = {
...connectedValue,
equalTo: equalValue
};
}
if (key === 'password') {
connectedValue = {
...connectedValue,
equalTo: value
};
}
this.setState(prevState => ({
controls: {
...prevState.controls,
confirmPassword: {
...prevState.controls.confirmPassword,
valid:
key === 'password'
? validate(
prevState.controls.confirmPassword.value,
prevState.controls.confirmPassword.validationRules,
connectedValue
)
: prevState.controls.confirmPassword.valid
},
[key]: {
...prevState.controls[key],
value,
valid: validate(value, prevState.controls[key].validationRules, connectedValue),
touched: true
}
}
}));
};
render () {
const stateData = this.state;
const { navigation } = this.props;
return (
<KeyboardAvoidingView
style={styles.container}
behavior="padding"
keyboardVerticalOffset={Header.HEIGHT + 20}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<Container>
<Typography textType="loginLabelStyle" textLabel="Use any of your existing profiles" />
<View style={‌{
flexDirection: 'row',
justifyContent: 'space-between',
}}
>
<SocialIcon type="twitter" />
<SocialIcon type="facebook" />
<SocialIcon type="google" light onPress={this.signIn} />
</View>
<Typography textType="loginLabelStyle" textLabel="or create one on SimpliFid" />
<DefaultInput
placeholder="Your E-Mail Address"
style={styles.input}
value={stateData.controls.email.value}
onChangeText={val => this.updateInputState('email', val)}
valid={stateData.controls.email.valid}
touched={stateData.controls.email.touched}
autoCapitalize="none"
autoCorrect={false}
keyboardType="email-address"
/>
<DefaultInput
placeholder="Password"
style={styles.input}
value={stateData.controls.password.value}
onChangeText={val => this.updateInputState('password', val)}
valid={stateData.controls.password.valid}
touched={stateData.controls.password.touched}
secureTextEntry
/>
<DefaultInput
placeholder="Confirm Password"
style={styles.input}
value={stateData.controls.confirmPassword.value}
onChangeText={val => this.updateInputState('confirmPassword', val)}
valid={stateData.controls.confirmPassword.valid}
touched={stateData.controls.confirmPassword.touched}
secureTextEntry
/>
<FooterContainer>
<Footer
leftButtonHandler={() => navigation.goBack()}
rightButtonHandler={this.props.onSignUp(stateData.controls.email.value, navigation)}
/* rightButtonHandler={() => navigation.navigate('ChatBot')} */
/>
</FooterContainer>
</Container>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
);
}
}
SignUp.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func.isRequired
}).isRequired
};
const mapDispatchToProps = dispatch => ({
onSignUp: (email, navigation) => {
Alert.alert(email);
dispatch({ type: actionTypes.SIGNUP, email });
navigation.navigate('ChatBot');
}
});
export default connect(
null,
mapDispatchToProps
)(SignUp);
Reducers.js
import * as actionTypes from './actions';
const initialState = {
email: '',
accountType: '',
name: '',
dob: '',
address: '',
ssn: '',
phoneNumber: '',
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.SIGNUP:
return {
...state,
email: action.email,
};
default:
return state;
}
};
export default reducer;
You are calling the this.props.onSingUp methods on each render
Try wrapping the call in a handler method:
handleRightButton = () => {
this.props.onSignUp(this.state..controls.email.value, this.props.navigation);
}
// And on render
render() {
...
rightButtonHandler={this.handleRightButton}
...
}
The problem was that i was trying to access the store in a wrong way i was trying using this
import state from '../store/reducers';
const Email = state.email;
However the correct way and probably the only way to access the store is using mapStateToProps
const mapStateToProps = state => ({
email: state.email,
});
<Footer
leftButtonHandler={() => navigation.goBack()}
rightButtonHandler={(event) => {
event.preventDefault();
this.props.onSignUp(stateData.controls.email.value,navigation)
/>
Try adding the event.preventDefault() in the rightButtonHandler.

React test vcoverage doesnot fulfill

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { compose } from 'recompose'
import { startWorkflow } from 'wf-dbd-react-ui/es/actions'
import Block from 'wf-dbd-react-ui/es/Block'
import BrowserTitle from 'wf-dbd-react-ui/es/BrowserTitle'
import ScrollToTopOnMount from 'wf-dbd-react-ui/es/ScrollToTopOnMount'
import FormMessages from 'wf-dbd-react-ui/es/FormMessages'
import { globals } from 'wf-dbd-react-ui/es/lib'
import withStrings from 'wf-dbd-react-ui/es/withStrings'
import PanelHeader from './panel-header/PanelHeader'
import AppHubTabs from './app-hub-tabs/AppHubTabs'
import RightRail from '../right-rail/RightRail'
import MessageDisplay from '../common/message-display/MessageDisplay'
import AddPayeeMessage from '../common/add-payee-message/AddPayeeMessage'
import { ADD_PAYEE, SEARCH_PAYEE } from '../workflows/add-payee/constants'
import ChangeFundingAccount from '../common/change-funding-account/ChangeFundingAccount'
import EditPaymentHotTaskModalContainer from '../common/hottask-edit-payment-modal/EditPaymentHotTaskModalContainer'
import DismissReminder from '../common/dismiss-reminder-modal/DismissReminder'
import HistoryTabViewPaymentDetailsModal from '../history-tab/group-history-form/history-tab-hot-task-menu/HistoryTabViewPaymentDetailsModal'
import * as actions from '../../lib/store/hub/actions'
import { getPayeeDetails } from '../../lib/store/payee-details/actions'
import { getPaymentDetails } from '../../lib/store/payment-details/actions'
import { resetPayeeTabFilterOption } from '../../lib/store/payees/actions'
import { closeViewPaymentDetailsModal } from '../../lib/store/history-tab/actions'
import { getHistoricalPayments } from '../../lib/selectors/selectors'
import styles from './AppHub.less'
class AppHub extends React.Component {
componentDidMount() {
const { getPayeeDetails, getPaymentDetails } = this.props
// payee details need to be fetched unconditionally. the cache in saga ensures it is not fetched until required
getPayeeDetails()
getPaymentDetails()
// Fix for for wide page layout issue in ie11 - Problem: ie11 nested flex element issue when window is minimized
Iif (!!window.MSInputMethodContext && !!document.documentMode) { // will be true for only for ie11 browser
document.querySelector('body > div > div > div > div').style.flexBasis = '0%'
}
// end of fix for ie11 wide page layout issue
}
componentWillUnmount() {
const { clearMessages, resetPayeeTabFilterOption } = this.props
clearMessages()
//clearing the selected payees-tab filter option
resetPayeeTabFilterOption()
}
handleTabSelect = activeTabIndexNew => {
const { clearMessages, activeTabIndex, setActiveTabIndex } = this.props
if (activeTabIndexNew !== activeTabIndex) {
setActiveTabIndex(activeTabIndexNew)
clearMessages()
}
}
render() {
const { activeTabIndex,
getString,
successMessage,
errorMessage,
ineligibleAccountMessage,
payees,
noOfHistoricalPayments,
payeesLoaded,
startAddPayeeWorkflow,
shouldShowChangeAccount,
reminderDismissalInProgress,
reminderDueDate,
closeViewPaymentDetailsModal,
isViewPaymentDetailsModalOpen,
viewPaymentData,
showEditPaymentSeriesModal
} = this.props
const panelHeaderId = globals().billpayBusinessUser ? 'app.hub.business.bill.pay.header' : 'app.hub.bill.pay.header'
return (
<Block layout={true} horizontal={true}>
<BrowserTitle title={getString('app.title')} />
<ScrollToTopOnMount />
<Block flex={true} relative={true} className={styles.billPayHub}>
<PanelHeader headerId={panelHeaderId} />
{
successMessage &&
<Block className={styles.message}>
<MessageDisplay messages={successMessage} />
</Block>
}
{
errorMessage &&
<Block className={styles.message}>
<MessageDisplay messages={errorMessage} />
</Block>
}
{
ineligibleAccountMessage && globals().enableDisplayPayeesWithIneligibleAccounts &&
<Block className={styles.message}>
<MessageDisplay messages={ineligibleAccountMessage} focusOnMount={true} />
</Block>
}
<Block className={styles.message}>
<FormMessages formId="makePaymentForm" className="formMessages" />
</Block>
{payeesLoaded && payees.size === 0 && <AddPayeeMessage startAddPayeeWorkflow={startAddPayeeWorkflow} />}
{payeesLoaded && (payees.size > 0 || noOfHistoricalPayments > 0) && (
<AppHubTabs
activeTabIndex={activeTabIndex}
onTabSelect={this.handleTabSelect}
/>
)
}
</Block>
<Block relative={true} styles={styles.rightRailContainer}>
<RightRail />
</Block>
{shouldShowChangeAccount && <ChangeFundingAccount />}
{showEditPaymentSeriesModal && <EditPaymentHotTaskModalContainer />}
{reminderDismissalInProgress && <DismissReminder dueDate={reminderDueDate} />}
{isViewPaymentDetailsModalOpen &&
<HistoryTabViewPaymentDetailsModal
isOpen={isViewPaymentDetailsModalOpen}
closeModal={closeViewPaymentDetailsModal}
viewPaymentData={viewPaymentData}
/>
}
</Block>
)
}
}
AppHub.propTypes = {
activeTabIndex: PropTypes.number.isRequired,
payees: PropTypes.object.isRequired,
noOfHistoricalPayments: PropTypes.number.isRequired,
payeesLoaded: PropTypes.bool,
startAddPayeeWorkflow: PropTypes.func.isRequired,
errorMessage: PropTypes.object,
successMessage: PropTypes.object,
shouldShowChangeAccount: PropTypes.bool,
resetPayeeTabFilterOption: PropTypes.func.isRequired,
getPayeeDetails: PropTypes.func.isRequired,
getPaymentDetails: PropTypes.func.isRequired,
clearMessages: PropTypes.func.isRequired,
setActiveTabIndex: PropTypes.func.isRequired,
getString: PropTypes.func.isRequired,
reminderDismissalInProgress: PropTypes.bool,
reminderDueDate: PropTypes.string,
closeViewPaymentDetailsModal: PropTypes.func.isRequired,
isViewPaymentDetailsModalOpen: PropTypes.bool,
viewPaymentData: PropTypes.object,
showEditPaymentSeriesModal: PropTypes.func.isRequired,
ineligibleAccountMessage: PropTypes.object
}
const mapStateToProps = state => ({
activeTabIndex: state.app.hub.activeHubTab,
successMessage: state.app.hub.successMessage,
errorMessage: state.app.hub.errorMessage,
ineligibleAccountMessage: state.app.hub.ineligibleAccountMessage,
payees: state.app.payees.payees,
noOfHistoricalPayments: getHistoricalPayments(state),
payeesLoaded: state.app.payees.payeesLoaded,
shouldShowChangeAccount: state.app.hub.showChangeAccount,
showEditPaymentSeriesModal: state.app.editPayment.editPaymentModal.isModalOpen,
reminderDismissalInProgress: state.app.hub.reminderDismissalInProgress,
reminderDueDate: state.app.hub.reminderDueDate,
isViewPaymentDetailsModalOpen: state.app.historyTab.isViewPaymentDetailsModalOpen,
viewPaymentData: state.app.historyTab.viewPaymentDetails
})
const mapDispatchToProps = dispatch => ({
setActiveTabIndex: index => dispatch(actions.setHubActiveTab(index)),
clearMessages: () => dispatch(actions.clearMessages()),
startAddPayeeWorkflow: () => dispatch(startWorkflow({ name: ADD_PAYEE, startingView: SEARCH_PAYEE })),
getPayeeDetails: () => dispatch(getPayeeDetails()),
getPaymentDetails: () => dispatch(getPaymentDetails()),
resetPayeeTabFilterOption: () => dispatch(resetPayeeTabFilterOption()),
closeViewPaymentDetailsModal: () => dispatch(closeViewPaymentDetailsModal())
})
export default compose(withStrings, connect(mapStateToProps, mapDispatchToProps))(AppHub)
iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.iamtryingtofindasolutionpleasehelp.
import React from 'react'
import { mount } from 'enzyme'
import MockStoreProvider from 'wf-dbd-react-ui/es/MockStoreProvider'
import Immutable from 'immutable'
import AppHub from '../AppHub'
import AppHubTabs from '../app-hub-tabs/AppHubTabs'
import AddPayeeMessage from '../../common/add-payee-message/AddPayeeMessage'
import PanelHeader from '../panel-header/PanelHeader'
jest.mock('../panel-header/PanelHeader', () => () => 'PanelHeader')
jest.mock('../app-hub-tabs/AppHubTabs', () => () => 'AppHubTabs')
jest.mock('../../common/add-payee-message/AddPayeeMessage', () => () => 'AddPayeeMessage')
jest.mock('../../common/message-display/MessageDisplay', () => () => 'MessageDisplay')
jest.mock('../../right-rail/RightRail', () => () => 'RightRail')
jest.mock('../../history-tab/group-history-form/history-tab-hot-task-menu/HistoryTabViewPaymentDetailsModal', () => () => 'HistoryTabViewPaymentDetailsModal')
describe('AppHub', () => {
let wrapper
describe('when rendered without any payees and payments', () => {
beforeEach(() => {
const getString = jest.fn().mockImplementation(() => 'testString')
const appState = {
hub: {
activeHubTab: 0,
successMessage: { SuccessMessageBean: { globalMessages: [{ level: 'confirm', message: 'message' }] } },
errorMessage: {}
},
payees: {
payees: Immutable.List([]),
enableSubmitBar: false,
payeesLoaded: true
},
paymentAccounts: {
paymentAccounts: Immutable.List([]),
enableSubmitBar: false
},
scheduledPayments: {
paymentsLoaded: false
},
historyTab: {
isViewPaymentDetailsModalOpen: true,
viewPaymentDetails: { key: 'value' },
historicalPayments: {
payments: []
}
},
editPayment: {
editPaymentModal: {
isModalOpen: false
}
}
}
wrapper = mount(
<MockStoreProvider appState={appState}>
<AppHub getString={getString} />
</MockStoreProvider>
)
})
it('should be defined', () => {
expect(AppHub).toBeDefined()
})
it('should render a PanelHeader', () => {
expect(wrapper.find(PanelHeader)).toHaveLength(1)
})
it('should render AddPayeeMessage', () => {
expect(wrapper.find(AddPayeeMessage)).toHaveLength(1)
})
})
describe('when rendered without any payees and historical payments are present', () => {
beforeEach(() => {
const getString = jest.fn().mockImplementation(() => 'testString')
const appState = {
hub: {
activeHubTab: 0,
successMessage: { SuccessMessageBean: { globalMessages: [{ level: 'confirm', message: 'message' }] } },
errorMessage: {}
},
payees: {
payees: Immutable.List([]),
enableSubmitBar: false,
payeesLoaded: true
},
paymentAccounts: {
paymentAccounts: Immutable.List([]),
enableSubmitBar: false
},
scheduledPayments: {
paymentsLoaded: false
},
historyTab: {
isViewPaymentDetailsModalOpen: true,
viewPaymentDetails: { key: 'value' },
historicalPayments: {
payments: [{
mockKey: 'mockValue'
}]
}
},
editPayment: {
editPaymentModal: {
isModalOpen: false
}
}
}
wrapper = mount(
<MockStoreProvider appState={appState}>
<AppHub getString={getString} />
</MockStoreProvider>
)
})
it('should render AppHubTabs', () => {
expect(wrapper.find(AppHubTabs)).toHaveLength(1)
})
it('should render AddPayeeMessage', () => {
expect(wrapper.find(AddPayeeMessage)).toHaveLength(1)
})
})
describe('when rendered with payees and there are no historical payments', () => {
beforeEach(() => {
const getString = jest.fn().mockImplementation(() => 'testString')
const appState = {
hub: {
activeHubTab: 0,
successMessage: { SuccessMessageBean: { globalMessages: [{ level: 'confirm', message: 'message' }] } },
errorMessage: {}
},
payees: {
payees: Immutable.List([{ id: 1 }]),
enableSubmitBar: false,
payeesLoaded: true
},
paymentAccounts: {
paymentAccounts: Immutable.List([]),
enableSubmitBar: false
},
scheduledPayments: {
paymentsLoaded: false
},
historyTab: {
isViewPaymentDetailsModalOpen: true,
viewPaymentDetails: { key: 'value' },
historicalPayments: {
payments: []
}
},
editPayment: {
editPaymentModal: {
isModalOpen: false
}
}
}
wrapper = mount(
<MockStoreProvider appState={appState}>
<AppHub getString={getString} />
</MockStoreProvider>
)
})
it('should render AppHubTabs', () => {
expect(wrapper.find(AppHubTabs)).toHaveLength(1)
})
it('should render AddPayeeMessage', () => {
expect(wrapper.find(AddPayeeMessage)).toHaveLength(0)
})
})
})

Resources