使用酶测试React组件。打字稿找不到实例方法 [英] Testing a React component with Enzyme. Typescript can't find instance methods

查看:68
本文介绍了使用酶测试React组件。打字稿找不到实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个React类的组件。

I want to test a React class component.

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

Let's say I have a method in my class that computes something based on the current state and props.

import Component from './Component'

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

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

Typescript说属性'someInstanceMethod'未在Component< any类型上定义,任何> 。我该如何告诉Typscript我的班级状况以及班级采用什么方法?

Typescript says Property 'someInstanceMethod' is not defined on type Component<any, any>. How can I tell Typscript how my class is looking and what methods it has?

是否有一个很好的例子?

Is there a good example for this?

推荐答案

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

You can set the component type in the call to shallow. This is a little bit of boilerplate, but it makes things typesafe. The good thing is that the wrapper is typesafe, not just the instance you pull out.

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();
});

这篇关于使用酶测试React组件。打字稿找不到实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆