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

问题描述 投票:0回答:1

[我的场景是一个内置有打字稿的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的变量组件的推断?

reactjs typescript unit-testing type-inference mount
1个回答
0
投票

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可以用作包装器使用浅渲染的类型。请记住ReactWrapperShallowWrapper都是通用的,因此您还可以提供组件的其他类型信息作为类型参数。

© www.soinside.com 2019 - 2024. All rights reserved.