我正在使用带有 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)输入什么? ?
最佳答案
好的,我在文档中找到了答案。ReactWrapper
和 ShallowWrapper
有 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/