编程语言
首页 > 编程语言> > javascript – 用酶和TypeScript浅HOC

javascript – 用酶和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

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
}

如何键入HOC实例?谢谢.

解决方法:

期望具有可参数化的可变返回值类型的函数是泛型. shallow is a generic

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();

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

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

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

标签:javascript,typescript,reactjs,enzyme
来源: https://codeday.me/bug/20190701/1346198.html