【问题标题】:React/Jest - Render connected HOC component in Jest unit testReact/Jest - 在 Jest 单元测试中渲染连接的 HOC 组件
【发布时间】:2018-05-29 01:45:27
【问题描述】:

我一直在玩 React 和 HOC 中的单元测试。我有一个返回新 WrapperComponent 的高阶组件。此外,在返回 WrapperComponent 时,我还将它与 props 和其他 HOC 连接起来,例如 mapStateToProps 等。我正在努力解决的是如何正确渲染与其他 HOC 组合的 HOC。我确定我遗漏了一些概念。

检查 hoc 发现它是一个函数,这对 HOC 有意义,但是当我尝试浅渲染 hoc 时,我收到以下错误:encountered declaration error

HOC - 为简洁起见删除了一些代码

export default function withComposition(WrappedComponent) {
    class CompositionComponent extends Component {

        static displayName = `withComposition(${WrappedComponent.displayName || WrappedComponent.name})`;

        render() {
            return (
                <WrappedComponent
                    {...this.props}
                />
            );
        }
    }

    const mapStateToProps = state => ({
        isMounted: selectIsMounted(state),
    });

    const enhance = compose(
        connect(mapStateToProps),
        withTranslate,
    );

    return enhance(CompositionComponent);
}

单元测试

import React, { Component } from 'react';
import withComposition from '../modules/withComposition';

describe('CompositionComponent', () => {   
    const hoc = withComposition(<Component />);
    debugger;
    const wrapper = shallow(hoc);
});

我也收到以下错误,我认为这很奇怪,因为我的其他测试使用 shallow 方法并且没有引发任何问题。

Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.

【问题讨论】:

    标签: reactjs unit-testing jestjs


    【解决方案1】:

    HOC返回组件,所以shallow你应该传递JSX组件:

    describe('CompositionComponent', () => {   
        const Hoc = withComposition(<Component />);
        debugger;
        const wrapper = shallow(<Hoc foo="foo" bar="bar" />);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 2018-04-03
      • 2018-01-15
      • 2020-06-12
      • 1970-01-01
      • 2019-11-22
      • 2022-09-25
      相关资源
      最近更新 更多