如何在使用 reactjs 构建的 jest Mount 测试中修复组件变量的类型推断?

How to fix type inference for a component variable in a jest Mount test built with reactjs?

我的场景是一个用打字稿构建的 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/>) 的 return 类型是 ReactWrapper。您可以在声明时显式设置包装器的类型。

import { ReactWrapper } from 'enzyme';

let wrapper: ReactWrapper;

beforeEach(() => {
  wrapper = mount(<Component/>) // ts will no longer infer the type for wrapper as any
})

同样,在使用浅层渲染时,ShallowWrapper 可以用作包装器的类型。请记住 ReactWrapperShallowWrapper 都是通用的,因此您还可以为组件提供额外的类型信息作为类型参数。