使用 Enzyme 测试 React 组件。打字稿找不到实例方法

Testing a React component with Enzyme. Typescript can't find instance methods

我想测试 React class 组件。

假设我的 class 中有一个方法可以根据当前状态和道具计算某些东西。

import Component from './Component'

const wrapper = enzyme.shallow(<Component {...props} />);

it('does something', () => {
  expect(wrapper.instance().someInstanceMethod(input)).toBe(true);
});

打字稿说 Property 'someInstanceMethod' is not defined on type Component<any, any>。我如何告诉 Typscript 我的 class 看起来如何以及它有什么方法?

有这方面的好例子吗?

一个可能的解决方案(感谢 marzelin 的评论)是显式声明 instance() 方法的类型。可能有更优雅的方法来做到这一点。

import Component from './Component'

const wrapper = enzyme.shallow(<Component {...props} />);
const instance = wrapper.instance() as Component; // explicitly declare type

it('does something', () => {
  expect(instance.someInstanceMethod(input)).toBe(true); // no TS error
});

感谢@marzelin 和@Chris! 其他可能的解决方案

import Component from './Component'

const wrapper = enzyme.shallow(<Component {...props} />);
const instance = wrapper.instance() as any; // explicitly declare type

it('does something', () => {
  expect(instance.someInstanceMethod(input)).toBe(true); // no TS error
});

这在 someInstanceMethod 接收事件作为参数时派上用场,显式声明类型 component 要求您传递整个事件对象,这不是开发人员编写测试用例所希望的。

您可以在对shallow的调用中设置组件类型。这是一些样板文件,但它使事情类型安全。好处是包装器是类型安全的,而不仅仅是你拉出的实例。

import Component from './Component'

// Wrapper will know the type of the component.
const wrapper = enzyme.shallow<Component>(<Component {...props} />);

it('does something', () => {
  expect(wrapper.instance().someInstanceMethod(input)).toBe(true);
  // You can also get the state from the wrapper.
  expect(wrapper.state().someComponentState).toBeTruthy();
});