gpt4 book ai didi

javascript - 访问从 HOC 返回的组件 Prop - Jest with React

转载 作者:行者123 更新时间:2023-11-30 06:12:43 26 4
gpt4 key购买 nike

我正在尝试为我的 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 返回的组件中获取 Prop ,即从 hoc 文件计算和传递的数据。

任何帮助将不胜感激:)

最佳答案

  1. 创建测试实用函数来呈现 HOC 子级

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,
}
}

  1. 然后像这样使用它

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
})

关于javascript - 访问从 HOC 返回的组件 Prop - Jest with React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57950927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com