1

What I've been trying is to test a react component with Jest (Enzyme) in a .tsx file (i.e. Typescript), following this post and this post.

Here is a snippet of my code.

(EDIT: Thank you @WillJenkins! I updated this snippet after I read your advice)

describe('MyComponent', ()=>{
  const mockStore = createMockStore([thunk]);
  let store = mockStore({});      

  it('should render ChildComponent if getFoo is true', () => {
    let wrapper = mount(
        <Provider store={store}>
            <MyComponent />
        </Provider>
    );

    let instance = wrapper.find(MyComponent).instance() as MyComponent;
    // "MyComponent" shows a warning message,
    // saying "Cannot find name 'MyComponent'."

    instance().getFoo = jest.fn();
    instance().getFoo.mockImplementation(() => true);

    instance.update();

    expect(instance.contains(<ChildComponent />)).toBe(true);
  });
});

For some reason, MyComponent after the as keyword can't be found when I use it as the type of wrapper.instance().

If I hover over it, it says "Cannot find name 'MyComponent'."

(Strangely, MyComponent within find()) doesn't give any warning)

If I replace

let instance = wrapper.find(MyComponent).instance() as MyComponent;

with

wrapper.find(MyComponent).instance().getFoo = jest.fn()

..., it results in a different warning message, saying that "Property 'getFoo' does not exist on type 'Component<any, any, any>'"

If I put any instead of MyComponent, it doesn't show any warning but the test itself results in an type error (instance.update() is not a function)

What is the correct type for instance()? I can't find any clue in Jest and Enzyme's doc.

Any advice will be appreciated.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Hiroki
  • 3,893
  • 13
  • 51
  • 90
  • are you importing the component from the `.jsx` file like in the example: `import Component from './Component'` at the top of your test file? in your case it would be `import MyComponent from './MyComponent'` where `./MyComponent` should be a relative path to your `MyComponent.jsx` file (don't include the extension on the import) – Pedro Costa Jun 07 '19 at 15:09
  • @PedroMaiaCosta, this component is imported as `import { MyComponent } from '../MyComponent'`. I'm sure that the path is correct, because changing it to anything else will give a warning message, which is caused by TypeScript. – Hiroki Jun 07 '19 at 15:34

1 Answers1

0

Your wrapper isn't a <MyComponent>, it's a <Provider>.

You need to use find to locate your MyComponent in your mounted tree:

let instance = wrapper.find(MyComponent).instance();
Will Jenkins
  • 9,507
  • 1
  • 27
  • 46
  • Thank you for your comment! Unfortunately, however, using the line (`let instance = wrapper.find(MyComponent).instance()`) didn't solve the issue. TypeScript is now complaining that `Property 'getFoo' does not exist on type 'Component'` just after the line. – Hiroki Jun 07 '19 at 14:55