具有酶和TypeScript的浅层HOC

Ale*_*din 6 javascript typescript reactjs enzyme

我有一个要测试的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)
})
Run Code Online (Sandbox Code Playgroud)

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

 Cannot find name 'WrappedComponent'.
Run Code Online (Sandbox Code Playgroud)

没错,因为WrappedComponent不是类型或类,但是如果我删除了

 as WrappedComponent
Run Code Online (Sandbox Code Playgroud)

行,TS抛出错误

Property 'someMethod' does not exist on type 'Component<{}, {}, any>'.
Run Code Online (Sandbox Code Playgroud)

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

as typeof WrappedComponent
Run Code Online (Sandbox Code Playgroud)

someHoc说明:

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
}
Run Code Online (Sandbox Code Playgroud)

如何输入HOC实例?谢谢。

Est*_*ask 6

具有可参数化的可变返回值类型的函数应该是泛型。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>;
Run Code Online (Sandbox Code Playgroud)

它可能应该用作:

const instance = shallow<typeof WrappedComponent>(
  <WrappedComponent
    dispatch={dispatch}
  />,
).instance();
Run Code Online (Sandbox Code Playgroud)

目前,使用泛型参数来推断 .x 中的组件类型的酶类型似乎存在问题ShallowWrapper。

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

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