Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "Component.WrappedComponent" when writing enzyme tests

What I'm trying to do:

I'm trying to use shallow rendering from enzyme by following the below pattern which works for many other components in my project.

describe('>> MyComponent - Render', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<MyComponent.WrappedComponent
      actions={{}}
      history={}
    />);
  });

  it("test something", () => { expect(wrapper).toEqual(1); });

});

What's the problem I have:

I got an error saying "Cannot read property 'contextTypes' of undefined", which means wrapper is undefined. But when I change <MyComponent.WrappedComponent /> to just <MyComponent />, the tests are successful. This is my code:

describe('>> Legends - render', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<Legends textsAndColor={[]} />);
  });

  it('+++ render the component', () => {
    expect(wrapper.length).toEqual(1);
  });

  it('+++ match snapshot', () => {
    expect(wrapper).toMatchSnapshot();
  });
});

Question I have:

What exactly does .WrappedComponent do ? And why does <MyComponent /> works but not <MyComponent.WrappedComponent /> ?

like image 472
Liutong Chen Avatar asked Apr 09 '18 19:04

Liutong Chen


1 Answers

By using .WrappedComponent you are getting access to component, wrapped by redux's connect function. I assume that most of your components are connected (since there are no problems with use of .WrappedComponent) and component that throwing described error isn't connected.

I suggest you to read redux docs to find out how to write tests for this case. Briefly said they suggest to have default export for your connected component and non-default for raw component. And then import only raw component for testing purposes, like this:

import { MyComponent } from './path/to/my/component`;

after this you will be able to mount (or shallow) your raw component like this:

describe('>> MyComponent - Render', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<MyComponent />);
  }
});
like image 126
Andrew Miroshnichenko Avatar answered Nov 02 '22 19:11

Andrew Miroshnichenko