我正在尝试为我的hoc
编写测试用例,我将其称为另一个hoc
。代码如下:
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);
}
以及我的测试文件:
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);
});
});
测试用例成功运行。但是我想从HOC
返回的组件中获取道具,即从hoc
文件计算并传递的数据。
任何帮助将不胜感激:)
答案 0 :(得分:0)
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
})