使用打字稿的酶中ReactWrapper的确切类型

问题描述 投票:0回答:1

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

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

但是,mount的返回类型为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个回答
0
投票

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

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<SubComponent, SubComponentProps, SubComponentState>-无法编译。将强制使用:

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

看起来糟透了。我们可以通过as使用强制类型转换来获得自定义类型。

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

就是这样。

© www.soinside.com 2019 - 2024. All rights reserved.