我正在用酶开玩笑地测试我的自定义组件(使用打字稿),所以我正在创建如下测试:
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
,我应该在钻石运算符中放什么?
答案 0 :(得分:3)
好吧,我在文档中找到了答案。
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();
就是这样。