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

[亡魂溺海] 提交于 2019-12-09 02:32:48

问题


I want to test a React class component.

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 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?


回答1:


You can set the component type in the call to shallow. This is a little bit of biolerplate, 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();
});



回答2:


One possible solution (thanks to the comment from marzelin) is to explicitly declare the type of the instance() method. There might be more elegant ways to do this.

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



回答3:


Thanks to @marzelin and @Chris! Other possible solution

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

This comes in handy where someInstanceMethod receives event as parameter, explicitly declare type as component requires you to pass whole event object which is not something a developer want for writing test cases.



来源:https://stackoverflow.com/questions/44625581/testing-a-react-component-with-enzyme-typescript-cant-find-instance-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!