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

时间:2017-07-21 21:58:47

标签: reactjs typescript enzyme

我正在使用Typescript和Enzyme来测试反应组分。我对Typescript很新。

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

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

当我将其作为getComponent()运行时,此功能正常运行,但是一旦getComponent(mount)运行它就会失败,因为typescript假定getComponent返回ShallowWrapper。

我有几个问题:

  1. 如何告诉Typescript mountFn可以是shallow还是mount
  2. 如何告诉它返回值可以是ShallowWrapperReactWrapper类型?
  3. 理想情况下 - 如何判断返回值在ShallowWrapper传递时应为shallow类型,在传递ReactWrapper时应为mount
  4. 如何使用已在@ types / enzyme中定义的打字?
  5. 这是一个很好的做法吗?在使用打字稿之前,我曾经一直这样做,但也许我应该创建两个独立的函数?

1 个答案:

答案 0 :(得分:1)

  

如何告诉Typescript mountFn可以浅或挂载?

这样就可以了。

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 typesShallowWrapperReactWrapper创建类型别名。

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类型,在传递mount时是否为ReactWrapper?

您无需手动指定。

  

如何使用已在@ types / enzyme中定义的打字输出?

我们已经在shallow使用mount@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 />);
};

希望这会有所帮助:)