如何在酶测试中设置安装功能的类型?

How to set types for mounting function in enzyme tests?

我正在使用 Typescript 和 Enzyme 来测试 React 组件。我是 Typescript 的新手。

我在测试中得到了这个辅助函数:

const getComponent = (mountFn = shallow) => (
  mountFn(<Component />)
)

这在我 运行 它作为 getComponent() 时有效,但是一旦我 getComponent(mount) 它就失败了,因为打字稿假定 getComponent returns ShallowWrapper。

我有几个问题:

  1. 如何告诉 Typescript mountFn 可以是 shallowmount
  2. 如何告诉它 return 值可以是 ShallowWrapperReactWrapper 类型?
  3. 理想情况下 - 当 shallow 被传递时,我如何告诉它 return 值应该是 ShallowWrapper 类型,而当 mount 被传递时,我如何告诉它 ReactWrapper 类型通过了吗?
  4. 如何使用@types/enzyme中已经定义的类型来执行此操作?
  5. 这是一个好习惯吗?在使用打字稿之前,我曾经一直这样做,但也许我应该只创建 2 个单独的函数?

How do I tell Typescript that mountFn can be either shallow or mount?

这样就可以了。

import {ShallowWrapper, ReactWrapper} from 'enzyme';

type mountFnType<P, S> = (node: React.ReactElement<P>, options?: any): ShallowWrapper<P, S> | ReactWrapper<P, S>

const getComponent = <P, S>(mountFn: mountFnType<P, S>) => (
     mountFn(<Component />)
)

在这里,如果您愿意,可以使用 union types.

ShallowWrapperReactWrapper 创建类型别名
type Wrapper<P, S> =  ShallowWrapper<P, S> | ReactWrapper<P, S>;

现在,你的函数看起来像,

type mountFnType<P, S> = (node: React.ReactElement<P>, options?: any) => Wrapper<P, S>;

const getComponent = <P, S>(mountFn: mountFnType<P, S>) => (
     mountFn(<Component />)
)

How do I tell it that the return value can be of type ShallowWrapper or ReactWrapper?

通过添加 return 类型,

const getComponent = <P, S>(mountFn: mountFnType<P, S>): Wrapper<P, S>

Ideally - how do I tell it that the return value should be of type ShallowWrapper when shallow was passed and ReactWrapper when mount was passed?

无需手动指定。

How do I do this using typings that are already defined in @types/enzyme?

我们已经在使用 @types/enzymeshallowmount 的类型定义。

Is this a good practice at all? I used to do it all the time before using typescript but maybe I should just create 2 separate functions?

我想这只是个人喜好问题。您可以使用辅助函数来简化一些工作。如果我在你那里,我也会将组件作为第二个参数传递。所以最后你的代码看起来像,

import {ShallowWrapper, ReactWrapper} from 'enzyme';

type Wrapper<P, S> =  ShallowWrapper<P, S> | ReactWrapper<P, S>;

type mountFnType<P, S> = (node: React.ReactElement<P>, options?: any) => Wrapper<P, S>;

const getComponent = <P, S>(mountFn: mountFnType<P, S>, CustomComponent: React.ComponentClass<P>): Wrapper<P, S> => {
      return mountFn(<CustomComponent />);
};

希望这对您有所帮助:)