【问题标题】:Testing a React component with Enzyme. Typescript can't find instance methods用 Enzyme 测试一个 React 组件。打字稿找不到实例方法
【发布时间】:2017-11-21 09:01:11
【问题描述】:

我想测试一个 React 类组件。

假设我的班级中有一个方法可以根据当前状态和道具进行计算。

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&lt;any, any&gt;。我如何告诉 Typscript 我的类的外观以及它有哪些方法?

这方面有什么好的例子吗?

【问题讨论】:

  • 你总是可以使用类型断言:(wrapper.instance() as typeof ComponentInstance).someInstanceMethod()

标签: reactjs typescript enzyme


【解决方案1】:

您可以将调用中的组件类型设置为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();
});

【讨论】:

    【解决方案2】:

    感谢@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 要求您传递整个事件对象,这不是开发人员在编写测试用例时想要的。

    【讨论】:

      【解决方案3】:

      一种可能的解决方案(感谢 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
      });
      

      【讨论】:

      • 如果函数是私有的会发生什么? ts 有一个错误:属性“someInstanceMethod”是私有的,只能在“组件”类中访问。
      • @jhonnylopez 我遇到了同样的问题,您找到解决方案了吗?
      • 这行得通。但我很好奇为什么它无法弄清楚......只是花了我一天的时间。
      • 我得到:“组件引用了一个值,但在这里用作类型”
      • @Sytham 您可以尝试将文件扩展名更改为.tsx吗?
      猜你喜欢
      • 2019-01-04
      • 2017-02-12
      • 2017-02-25
      • 1970-01-01
      • 2017-10-26
      • 2021-07-01
      • 2017-12-15
      • 2020-02-06
      • 2018-08-20
      相关资源
      最近更新 更多