【问题标题】:Exact types for ReactWrapper in enzyme using typescript使用打字稿的酶中 ReactWrapper 的确切类型
【发布时间】:2019-11-18 21:35:39
【问题描述】:

我正在使用带有酶的玩笑(使用打字稿)测试我的自定义组件,所以我正在创建如下测试:

const wrapper = mount(<MyCustomComponent/>);
expect(wrapper).toMatchSnapshot();

但是,mounts 的返回类型是ReactWrapper,所以我正在使用它:

const wrapper: ReactWrapper = mount(<MyCustomComponent/>);
expect(wrapper).toMatchSnapshot();

而且还可以。但深入挖掘让我了解到ReactWrapper 是通用的。而且...mount 函数有 3 个声明。我一直这样使用它:

const wrapper: ReactWrapper<MyCustomComponent> = mount(<MyCustomComponent/>);
expect(wrapper).toMatchSnapshot();

但现在恐怕不行了。我强烈希望使用确切的类型。对于ReactWrapper,我究竟应该在钻石运算符中输入什么?

【问题讨论】:

    标签: typescript testing types jestjs enzyme


    【解决方案1】:

    好的,我在文档中找到了答案。

    ReactWrapperShallowWrapper 有 3 个通用参数。假设我们有:

    export Interface ComponentProps {
        someComponentProp: string;
    }
    
    export interface ComponentState {
        someComponentState: string;
    }
    
    export class MyCustomComponent extends React.Component<ComponentProps, ComponentState> {
    
    }
    

    在这样的代码中,测试 DOM 对象应该有以下类型:

    const wrapper: ReactWrapper<MyCustomComponent, ComponentProps, ComponentState> = mount(<MyCustomComponent/>);
    expect(wrapper).toMatchSnapshot();
    

    但是,find 存在问题。在以下代码中:

    const wrapper: ReactWrapper<MyCustomComponent, ComponentProps, ComponentState> = mount(<MyCustomComponent/>);
    const subWrapper: ReactWrapper = wrapper.find(SubComponent);
    expect(subWrapper).toMatchSnapshot();
    

    subWrapper 类型不能是:ReactWrapper&lt;SubComponent, SubComponentProps, SubComponentState&gt; - 它不会编译。它会强制使用:

    const wrapper: ReactWrapper<MyCustomComponent, ComponentProps, ComponentState> = mount(<MyCustomComponent/>);
    const subWrapper: ReactWrapper<React.Component<SubComponentProps, SubComponentState>, SubComponentProps, SubComponentState> = wrapper.find(SubComponent);
    expect(subWrapper).toMatchSnapshot();
    

    看起来很糟糕。幸运的是,我们可以通过 as 使用 cast 来获得我们的自定义类型。

    const wrapper: ReactWrapper<MyCustomComponent, ComponentProps, ComponentState> = mount(<MyCustomComponent/>);
    const subWrapper: ReactWrapper<SubComponent, SubComponentProps, SubComponentState> = wrapper.find(SubComponent) as SubComponent;
    expect(subWrapper).toMatchSnapshot();
    

    就是这样。

    【讨论】:

    • 谢谢!你能举一个 FunctionComponent 的例子吗?我无法理解它。例如const Foo: FC&lt;FooProps&gt; = ({ bar }) =&gt; (&lt;&gt;{bar}&lt;/&gt;);
    • @igor 你可以使用const wrapper: ShallowWrapper&lt;typeof SomeComponent&gt; = shallow(&lt;SomeComponent/&gt;); 或更隐含的const wrapper: ShallowWrapper&lt;(props: SomeComponentProps) =&gt; JSX.Element&gt; = shallow(&lt;SomeComponent/&gt;);
    猜你喜欢
    • 2022-08-18
    • 2020-12-27
    • 1970-01-01
    • 2021-08-15
    • 2012-11-06
    • 2020-04-17
    • 2018-01-31
    • 2020-10-12
    • 2021-06-03
    相关资源
    最近更新 更多