我有一个要测试的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实例?谢谢。
答案 0 :(得分:2)
期望具有可参数化的可变返回值类型的函数是泛型的。 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();
使用通用参数来推断ShallowWrapper
中的组件类型,目前在酶类型输入中似乎存在问题。
一种确保测试类型安全的解决方法是声明类型:
const instance = shallow(
<WrappedComponent
dispatch={dispatch}
/>,
)
.instance() as any as InstanceType<typeof WrappedComponent>;