[英]Shallow HOC with Enzyme and TypeScript
我有一個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
是通用的 :
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>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.