【问题标题】:Impossible to test a React component wrapped with redux compose无法测试用 redux compose 包装的 React 组件
【发布时间】:2019-12-02 19:36:55
【问题描述】:

我需要用 Jest 测试一个 React 组件(Toto)。 由于 redux compose 功能,该组件使用两个 HOC 导出。

当我尝试在测试文件 (Toto.test.tsx) 中使用 Toto 组件时,出现 TS2604 错误(JSX 元素类型“Toto”没有任何构造或调用签名)。

Toto.test.tsx

import { shallow } from 'enzyme';
import * as React from 'react';
import Toto from '../../Toto';

function setupFullRenderingComponent(options: any = {}) {
  const props = {
    toto: 'hello'
  }

  const wrapper = shallow(   
    <Toto {...props} />
  );

  return {
    props,
    wrapper
  };
}

describe('Toto', () => {
  const { wrapper } = setupFullRenderingComponent();
  console.log(wrapper);
});

Toto.tsx

import * as React from 'react';
import { withRouter } from 'react-router';
import { compose } from 'redux';
import WithHelp from '../../../WithHelp';

class Toto extends React.Component<
  any,
  any
> {
  public constructor(props: any) {
    super(props);

    this.state = {
      total: 0
    };
  }

  // SOME STUFF

  public render() {
    return (
      <div>{this.state.total}</div>
    );
  }
}

export default compose(
  withRouter,
  WithHelp
)(Toto);

我该如何解决这个问题?

谢谢

【问题讨论】:

  • 这个组件在live project中能正常工作吗?
  • 是的,它以相同的方式导入,并且可以正常工作。谢谢
  • 谢谢 Skyboyer,确实添加“as React.ComponentType”解决了我的问题

标签: reactjs typescript react-redux jestjs


【解决方案1】:

你可以在测试文件中写export class Toto extends ...,然后import {Toto} from ...

【讨论】:

    【解决方案2】:

    添加“as React.ComponentType”解决了我的问题。谢谢你的帮助

    【讨论】:

      猜你喜欢
      • 2018-07-03
      • 1970-01-01
      • 2019-06-14
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      相关资源
      最近更新 更多