javascript - 带有 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 实例?谢谢。
解决方案
期望具有可以参数化的可变返回值类型的函数是泛型的。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>;
推荐阅读
- c++ - 为什么函数 glViewport() 给我错误?
- python - multi_vowel_words 函数返回具有 3 个或更多连续元音的所有单词
- android - Kotlin DatePicker Pop-Up 在片段内不起作用:WindowManager$BadTokenException: Unable to add window -- token null is not valid;
- android - Kotlin,Android Studio:我无法让我的程序使用第二个适配器。列表视图
- css - Blazor WebAssembly 以不同的方式处理 css
- python - AutoPy - 点越界 (smooth_move)
- android - 无法将数据保存到 Firebase
- java - SAP HANA - 处理日期数据类型的问题
- kentico - 在 kentico admin 中使用 NewClassWizard
- php - 从 POST 检索日期到 datediff 问题