25

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?

Chris
  • 2,069
  • 3
  • 22
  • 27
  • 2
    you can always use type assertion: `(wrapper.instance() as typeof ComponentInstance).someInstanceMethod()` – marzelin Jun 19 '17 at 09:08

3 Answers3

28

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();
});
Fidan Hakaj
  • 6,818
  • 3
  • 30
  • 33
Shane
  • 1,255
  • 14
  • 14
26

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
});
ericsoco
  • 24,913
  • 29
  • 97
  • 127
Chris
  • 2,069
  • 3
  • 22
  • 27
0

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.

mukuljainx
  • 716
  • 1
  • 6
  • 16