[我的场景是一个内置有打字稿的React项目,特别是涉及来自Enzyme的mount
的单元测试。我正在使用tsconfig参数“ noImplicitAny”对齐项目:是的,我想知道如何解决下面描述的let组件问题。
let wrapper
beforeEach(() => {
wrapper = mount(<Component/>)
})
it('shows the rendered component', () => {
expect(wrapper.find('.class-component')).toHaveLength(1)
})
并且错误是:
Variable 'wrapper' implicitly has type 'any' in some locations where its type cannot be determined.ts (7034)
如何创建类型为Component
的变量组件的推断?
mount(<Component/>)
的返回类型为ReactWrapper
。您可以在声明时显式设置包装器的类型。
import { ReactWrapper } from 'enzyme';
let wrapper: ReactWrapper;
beforeEach(() => {
wrapper = mount(<Component/>) // ts will no longer infer the type for wrapper as any
})
类似地,ShallowWrapper
可以用作包装器使用浅渲染的类型。请记住ReactWrapper
和ShallowWrapper
都是通用的,因此您还可以提供组件的其他类型信息作为类型参数。