首页 > 解决方案 > 带有 Enzyme 和 TypeScript 的浅层 HOC

问题描述

我有一个 HOC 来测试,在浅挂载期间我应该调用一些类方法:

it('Should not call dispatch', () => {
        const dispatch = jest.fn()
        const WrappedComponent = someHoc(DummyComponent)
        const instance = shallow(
          <WrappedComponent
            dispatch={dispatch}
          />,
        ).instance() as WrappedComponent
        instance.someMethod()
        expect(dispatch).toHaveBeenCalledTimes(0)
})

测试工作正常,但 TS 编译器抛出错误

 Cannot find name 'WrappedComponent'.

这是正确的,因为 WrappedComponent 不是类型或类,但如果我删除

 as WrappedComponent

行,TS 抛出错误

Property 'someMethod' does not exist on type 'Component<{}, {}, any>'.

此外,如果我将该行更改为

as typeof WrappedComponent

一些Hoc描述:

import ...

interface State {
  /*state*/
}

interface Props {
  dispatch: Dispatch<Action>
  /*props*/
}

export someHoc = <T extends {}>(
  ChildComponent: React.ComponentClass<T>,
) => {
  class Wrapper extends React.PureComponent<T & Props, State> {

    someMethod = () => {
       /*do smth*/
    }

    render() {
      return (
        <div>
          <ChildComponent {...this.props} />
        </div>
      )
    }
  }

  return Wrapper
}

如何键入 HOC 实例?谢谢。

标签: javascriptreactjstypescriptenzyme

解决方案


期望具有可以参数化的可变返回值类型的函数是泛型的。shallow是通用的

export function shallow<C extends Component, P = C['props'], S = C['state']>(node: ReactElement<P>, options?: ShallowRendererProps): ShallowWrapper<P, S, C>;
export function shallow<P>(node: ReactElement<P>, options?: ShallowRendererProps): ShallowWrapper<P, any>;
export function shallow<P, S>(node: ReactElement<P>, options?: ShallowRendererProps): ShallowWrapper<P, S>;

它可能应该用作:

const instance = shallow<typeof WrappedComponent>(
  <WrappedComponent
    dispatch={dispatch}
  />,
).instance();

目前在使用泛型参数推断组件类型的酶分型中似乎存在问题ShallowWrapper

在测试中确保类型安全的一种解决方法是断言类型:

const instance = shallow(
  <WrappedComponent
    dispatch={dispatch}
  />,
)
.instance() as any as InstanceType<typeof WrappedComponent>;

推荐阅读