我正在使用Preact、Typescript和Parcel为项目配置Jest。组件代码本身一切正常,但当设置Jest测试并使用Enzyme的mount
或shallow
函数(使用预作用适配器(呈现组件时,我收到一个错误,表明传递到函数中的类型缺少ref
属性:
src/features/homepage/homepage.spec.tsx:10:13 - error TS2769: No overload matches this call.
Overload 1 of 3, '(node: ReactElement<any, string | JSXElementConstructor<any>>, options?: MountRendererProps | undefined): ReactWrapper<any, Readonly<...>, Component<...>>', gave the following error.
Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>>'.
Types of property 'type' are incompatible.
Type 'string | ComponentType<any>' is not assignable to type 'string | JSXElementConstructor<any>'.
Type 'ComponentClass<any, {}>' is not assignable to type 'string | JSXElementConstructor<any>'.
Type 'ComponentClass<any, {}>' is not assignable to type 'new (props: any) => Component<any, any, any>'.
Property 'refs' is missing in type 'Component<any, {}>' but required in type 'Component<any, any, any>'.
Overload 2 of 3, '(node: ReactElement<any, string | JSXElementConstructor<any>>, options?: MountRendererProps | undefined): ReactWrapper<any, any, Component<...>>', gave the following error.
Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>>'.
Overload 3 of 3, '(node: ReactElement<any, string | JSXElementConstructor<any>>, options?: MountRendererProps | undefined): ReactWrapper<any, unknown, Component<...>>', gave the following error.
Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>>'.
10 <Homepage/>
~~~~~~~~~~~
node_modules/@types/react/index.d.ts:501:9
501 refs: {
~~~~
'refs' is declared here.
最新版本的@types/react和Enzyme之间是否存在冲突?如果是这样的话,是否有一些重写这种类型声明的最佳实践?
此错误的原因是preact中仍然存在开放的类型定义问题。解决方案是在node_modules/preact/src/index.d.ts
中添加一行。搜索componentDidCatch
并在其后面添加此行:
refs: { [key: string]: Component<any> | Element; };
。
这将把丢失的refs
成员添加到预作用Component
接口。
如果您不想修补已安装的节点模块,请在tsconfig.json文件中添加路径映射,如本期所述。
{
"baseUrl": "./",
"paths": {
"react": ["./node_modules/preact/compat/"],
"react-dom": ["./node_modules/preact/compat/"]
}