用酶测试React组件.Typescript无法找到实例方法

Chr*_*ris 18 typescript reactjs enzyme

我想测试一个React类组件.

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

import Component from './Component'

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

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

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

这有一个很好的例子吗?

Chr*_*ris 22

一个可能的解决方案(感谢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
});
Run Code Online (Sandbox Code Playgroud)

  • 如果函数是私有的会发生什么?ts有一个错误:属性'someInstanceMethod'是私有的,只能在类'Component'中访问. (2认同)

Sha*_*ane 16

您可以在调用中将组件类型设置为shallow。这有点像biolerplate,但它使类型安全。好处是包装器是类型安全的,而不仅仅是您拉出的实例。

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();
});
Run Code Online (Sandbox Code Playgroud)