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

Chris picture Chris · Jun 19, 2017 · Viewed 13.5k times · Source

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?

Answer

Chris picture Chris · Jun 21, 2017

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