酶试验中如何设置封固功能的类型?

api*_*art 3 typescript reactjs enzyme

我正在使用 Typescript 和 Enzyme 来测试反应组件。我对 Typescript 很陌生。

我在测试中有这个辅助函数:

const getComponent = (mountFn = shallow) => (
  mountFn(<Component />)
)
Run Code Online (Sandbox Code Playgroud)

当我运行它时,这是有效的,getComponent()但一旦我这样做,getComponent(mount)它就会失败,因为打字稿假设getComponent返回ShallowWrapper。

我有一些问题:

  1. 我如何告诉 TypescriptmountFn可以是shallowor mount
  2. 我如何告诉它返回值可以是类型ShallowWrapperReactWrapper类型?
  3. 理想情况下 - 我如何告诉它返回值应该是ShallowWrapper何时shallow传递以及ReactWrapper何时mount传递的类型?
  4. 如何使用 @types/enzyme 中已定义的类型来执行此操作?
  5. 这是一个好的做法吗?在使用打字稿之前我一直这样做,但也许我应该创建两个单独的函数?

Har*_*dha 5

我如何告诉 TypescriptmountFn可以是浅的还是安装的?

这样就可以解决问题了。

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 />)
)
Run Code Online (Sandbox Code Playgroud)

如果您愿意,可以在此处为ShallowWrapperReactWrapper使用联合类型创建类型别名。

type Wrapper<P, S> =  ShallowWrapper<P, S> | ReactWrapper<P, S>;
Run Code Online (Sandbox Code Playgroud)

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

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

const getComponent = <P, S>(mountFn: mountFnType<P, S>) => (
     mountFn(<Component />)
)
Run Code Online (Sandbox Code Playgroud)

我如何告诉它返回值可以是ShallowWrapper 或ReactWrapper 类型?

通过添加返回类型,

const getComponent = <P, S>(mountFn: mountFnType<P, S>): Wrapper<P, S>
Run Code Online (Sandbox Code Playgroud)

理想情况下-我如何告诉它,当传递shallow时,返回值应该是ShallowWrapper类型,而当传递mount时,返回值应该是ReactWrapper类型?

您不需要手动指定它。

如何使用 @types/enzyme 中已定义的类型来执行此操作?

我们已经在使用shallowmountfrom的类型定义@types/enzyme

这是一个好的做法吗?在使用打字稿之前我一直这样做,但也许我应该创建两个单独的函数?

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

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 />);
};
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 :)