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

标签 javascript reactjs jestjs enzyme higher-order-components

我正在尝试为我的 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/

相关文章:

javascript - IE 中的框阴影与 Chrome 中的不同

javascript - 如何从 Reactjs onPaste 事件中获取粘贴值

javascript - Jest 中的模拟 shell 命令输出

javascript - 为什么这个使用 await/act/async 的官方 React 测试配方真的有效?

reactjs - 使用 TypeScript 的 React 组件中的默认属性值

javascript - 如何模拟我在 Nestjs/jest 中测试的同一类中的方法

javascript - 测试异步函数的问题

javascript - Applescript : wait that the page is load on chrome

javascript - 使用 jquery 的元素的 css 高度不一致

javascript - 如何记住事件菜单