Test whether React component has rendered

匆匆过客 提交于 2019-12-06 13:46:18

So I've had a chat to some people and decided that maybe I am going about this the wrong way.

It's probably a better idea to determine whether or not this gets rendered by the parent component, otherwise any time I want to use MyComponent, I am going to have to pass this shouldRender prop into it.

MyComponent now looks like this:

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      foo: 'bar',
    };
  }

  render() {
    return (
      <div>
        <span>My component</span>
      </div>
    );
  }
}

MyComponent.propTypes = propTypes;

export default MyComponent;

and MyParentComponent that uses MyComponent looks like this:

import React from 'react';

const propTypes = {
  myComponent: React.PropTypes.bool,
};

class MyParentComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      boz: 'baz',
    };
  }

  render() {
    return (
      <div>
        { this.props.myComponent && 
          <MyComponent />
        }
      </div>
    );
  }
}

export default MyComponent;

Not only does allow MyComponent to be more reusable, it removes the need for the test I wanted to write altogether. Thank you to everyone that looked at this.

I think Jest's snapshot testing is what you need. With snapshot testing when a test fails you can check to see if it's intended or unintended change. Check out their example here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!