My scenario is a react project built in typescript, and specifically regarding a unit test involving mount
from Enzyme. I'm working on aligning the project with the tsconfig parameter "noImplicitAny": true, I'm wondering how to fix the let component issue described under.
let wrapper
beforeEach(() => {
wrapper = mount(<Component/>)
})
it('shows the rendered component', () => {
expect(wrapper.find('.class-component')).toHaveLength(1)
})
and error is:
Variable 'wrapper' implicitly has type 'any' in some locations where its type cannot be determined.ts (7034)
How to create the inference of type Component
to variable component?
The return type of mount(<Component/>)
is ReactWrapper
. you can just explicitly set the type for wrapper when declaring.
import { ReactWrapper } from 'enzyme';
let wrapper: ReactWrapper;
beforeEach(() => {
wrapper = mount(<Component/>) // ts will no longer infer the type for wrapper as any
})
Similarly ShallowWrapper
can be used as the type for the wrapper when using shallow rendering. Keep in mind both ReactWrapper
and ShallowWrapper
are generic, so you can also provide additional type information for the component as type arguments.