Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 617
Chris Avatar asked Jun 19 '17 08:06

Chris


2 Answers

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();
});
like image 106
Shane Avatar answered Oct 19 '22 05:10

Shane


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
});
like image 26
Chris Avatar answered Oct 19 '22 07:10

Chris