繁体   English   中英

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

[英]How to set types for mounting function in enzyme tests?

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

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

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

当我将其作为getComponent()运行时,此方法有效,但是一旦执行getComponent(mount)它就会失败,因为打字稿假定getComponent返回ShallowWrapper。

我有一些问题:

  1. 我如何告诉Typescript mountFn可以是shallow也可以是mount
  2. 我如何告诉它返回值可以是ShallowWrapperReactWrapper类型?
  3. 理想的情况是-我怎么告诉它的返回值应该是类型ShallowWrappershallow传递和ReactWrappermount获得通过?
  4. 如何使用@ types / enzyme中已经定义的类型来执行此操作?
  5. 这是个好习惯吗? 在使用打字稿之前,我一直都这样做,但是也许我应该只创建2个单独的函数?

如何告诉Typescript mountFn可以是浅的也可以是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 />)
)

如果愿意,可以在这里使用联合类型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 />)
)

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

通过添加返回类型,

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

理想情况下-我如何告诉它,当传递浅值时返回值应为ShallowWrapper类型,而当传递挂载时返回值应为ReactWrapper类型?

您无需手动指定。

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

我们已经在使用shallow类型定义并从@types/enzyme mount

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

我想这只是一个偏好问题。 您可以使用帮助器功能使一些工作变得容易。 如果我在您的位置,我也会将该组件作为第二个参数传递。 所以最终您的代码将如下所示:

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 />);
};

希望这可以帮助 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM