Syed Jafri
Syed Jafri

Reputation: 476

enzyme test multiple render methods within same component

I have a component with multiple render methods. How can I test them all? Using enzyme and jest with react.

Some pseudo code as an example of my component structure as the component is quiet large.

class MyComponent extends Component{

  render1(){
    return(
      <div>render1</div>
    )
  }
  
  render2(){
    return(
      <div>render2</div>
    )
  }
  
  render(){
    return(
      <div>default</div>
    )
  }
}

export default MyComponent;

My test only covers render() it does not cover render1() or render2(). It would seem enzyme looks at the default render() method?

describe('MyComponent', () => {
    beforeEach(() => {
      wrapper = shallow(<MyComponent />);
    });
  
  it('MyComponent renders without crashing', () => {
      expect(wrapper.length).toBeTruthy();
  });
};

How can I include render1() and render2() in my coverage?

Upvotes: 0

Views: 1311

Answers (1)

elas
elas

Reputation: 815

You should only have one render() method, that's the method called when mounting components with ReactDOM.render or enzyme.shallow. How are the other rendering methods working for you?

Maybe you could do something like this, deciding which method to call from the render() method based on some prop or state:

class MyComponent extends Component{

  render1(){
    return(
      <div>render1</div>
    )
  }

  render2(){
    return(
      <div>render2</div>
    )
  }

  render(){
    const {shouldRender1, shouldRender2} = this.props;

    if (shouldRender1) {
      return this.render1();
    }

    if (shouldRender2) {
      return this.render2();
    }    

    return(
      <div>default</div>
    )
  }
}

export default MyComponent;

Then your tests can look like this:

describe('MyComponent', () => {
  it('MyComponent should render with render1 method', () => {
      wrapper = shallow(<MyComponent shouldRender1={true} />);
      expect(wrapper.length).toBeTruthy();
  });

  it('MyComponent should render with render2 method', () => {
      wrapper = shallow(<MyComponent shouldRender2={true} />);
      expect(wrapper.length).toBeTruthy();
  });  

  it('MyComponent should render with default render method', () => {
      wrapper = shallow(<MyComponent />);
      expect(wrapper.length).toBeTruthy();
  });    
};

Upvotes: 1

Related Questions