typescript - 使用 typescript 的 enzyme 中 ReactWrapper 的确切类型

标签 typescript testing types jestjs enzyme

我正在使用带有 enzyme 的 Jest (使用 typescript )测试我的自定义组件,因此我正在创建如下测试:

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

然而,mount s 返回类型为 ReactWrapper ,所以我正在使用它:
const wrapper: ReactWrapper = mount(<MyCustomComponent/>);
expect(wrapper).toMatchSnapshot();

而且还可以。但深入挖掘让我了解到 ReactWrapper是通用的。还有... mount函数有 3 个声明。我一直这样使用它:
const wrapper: ReactWrapper<MyCustomComponent> = mount(<MyCustomComponent/>);
expect(wrapper).toMatchSnapshot();

但现在恐怕不行了。我非常想使用精确类型。我到底应该为 ReactWrapper 的钻石运算符(operator)输入什么? ?

最佳答案

好的,我在文档中找到了答案。
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();

就是这样。

关于typescript - 使用 typescript 的 enzyme 中 ReactWrapper 的确切类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58923271/

相关文章:

c++ - 初始化nullptr_t时,0与其他整数如何区分?

Angular 2 : Property injection instead of constructor injection

spring - TestNG - 仅当定义了 6 个或更多测试时才会出现异常

typescript - 如何通过 TypeScript 中的装饰器获取另一个属性的值

unit-testing - 像往常一样对 docker 容器或 dockerize 测试运行测试?

testing - 如何使用testNG+Java在appium中运行多个测试用例?

haskell - 为什么 6/length [1, 2, 3] 在 Haskell 中不起作用

scala - 为什么我不能在 Scala 中创建 F 有界对象

javascript - 一个组件中的 ngForm 给出表单值,其他组件中的相同代码给出未定义

typescript - 使用 jsPDF rtl 支持的 Html 到 pdf