I am trying to write test cases for my hoc
, which i call in another hoc
. The code looks like:
getData.jsx
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
export default function getData(Receiver) {
function fetchData(props) {
const [dataInState, setData] = useState([]);
useEffect(() => {
loadData();
}, []);
const loadData = () => {
const { ids = [], data: existingData = [] } = props; // existing data from redux store
if(ids.length) {
if(existingData.length) {
setData([...existingData]);
}
else {
// fetching data from actions
setData([...dataFromActions]);
}
} else {
console.log("in else")
}
}
return (<Receiver data={dataInState} {...props} />);
}
const mapStateToProps = ({ router, dataFromStore }) => {
const { data = [] } = dataFromStore;
return {
router,
data,
};
};
const mapDispatchToProps = {
doGetDataRequest,
};
return connect(mapStateToProps, mapDispatchToProps)(fetchData);
}
and in my test file :
import React from 'react';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import configureStore from 'redux-mock-store';
import getData from './getData';
let store;
describe('test for hoc', () => {
beforeEach(() => {
const mockStore = configureStore();
// creates the store with any initial state or middleware needed
store = mockStore({
...
});
});
it('Should render the component ', () => {
configure({ adapter: new Adapter() });
const ids = [];
const Component = <h1 ids={ids}>Hola</h1>;
const ConditionalHOC = getData(Component);
// read props here somewhere
const wrapper = shallow(<ConditionalHOC store={store} />);
expect(wrapper).not.toBe(null);
});
});
the test case runs successfully. However i want's to get the props from the component which is returned from HOC
ie data which is calculated and passed from hoc
file.
Any help will be appreciated :)
import React from 'react' import { mount } from 'enzyme' const render = (hoc, props, context) => { const Component = () => <div /> const WrappedComponent = hoc(Component) return mount(<WrappedComponent {...props} />, { context }) } export default (hoc, props, context) => { const component = render(hoc, props, context) const update = () => { component.update() return component.find('Component') } return { component: component.find('Component'), update, root: component, } }
import renderHOC from 'your/path' it('your test', () => { const {component} = renderHOC(yourHOC, props) expect(component.prop('propName')).toBe(expected) component.prop('anotherProp')() // runs state update in HOC expect(component.update().prop('updatedProp')).toBe(expected) // NB `update()` is required if you are updating state of the HOC })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.