After consulting the documentation, I was able to find the solution.
ReactWrapper
and ShallowWrapper
each have 3 generic arguments. For example:
export Interface ComponentProps {
someComponentProp: string;
}
export interface ComponentState {
someComponentState: string;
}
export class MyCustomComponent extends React.Component<ComponentProps, ComponentState> {
}
In this scenario, the test DOM objects should be of the following types:
const wrapper: ReactWrapper<MyCustomComponent, ComponentProps, ComponentState> = mount(<MyCustomComponent/>);
expect(wrapper).toMatchSnapshot();
However, there is a complication with the find
method. In the code snippet below:
const wrapper: ReactWrapper<MyCustomComponent, ComponentProps, ComponentState> = mount(<MyCustomComponent/>);
const subWrapper: ReactWrapper = wrapper.find(SubComponent);
expect(subWrapper).toMatchSnapshot();
The type of subWrapper
cannot be:
ReactWrapper<SubComponent, SubComponentProps, SubComponentState>
- it will not compile. This requires using:
const wrapper: ReactWrapper<MyCustomComponent, ComponentProps, ComponentState> = mount(<MyCustomComponent/>);
const subWrapper: ReactWrapper<React.Component<SubComponentProps, SubComponentState>, SubComponentProps, SubComponentState> = wrapper.find(SubComponent);
expect(subWrapper).toMatchSnapshot();
This approach may not look ideal. Thankfully, we can create our custom type by utilizing type casting through as
.
const wrapper: ReactWrapper<MyCustomComponent, ComponentProps, ComponentState> = mount(<MyCustomComponent/>);
const subWrapper: ReactWrapper<SubComponent, SubComponentProps, SubComponentState> = wrapper.find(SubComponent) as SubComponent;
expect(subWrapper).toMatchSnapshot();
And that's all for now.