测试React组件是否已经渲染

Dav*_*per 5 javascript reactjs jestjs enzyme

我有一个 React 组件,正在尝试使用 Enzyme/Jest 进行测试。我试图找出最合适的测试来确保组件已呈现。

我的组件有一个 prop shouldRender,如果为 false,将导致组件无法渲染。我的组件如下所示:

import React from 'react';

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

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

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

  render() {
    if (!this.props.shouldRender) {
      return null;
    }

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

MyComponent.propTypes = propTypes;

export default MyComponent;
Run Code Online (Sandbox Code Playgroud)

我有一个如下所示的测试:

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from '../MyComponent';

describe('MyComponent', () => {
  it('Should render if we want it to', () => {
    const component = shallow(<MyComponent shouldRender />);

    expect(component).toBeDefined(); // Passes
  });

  it('Should not render if we do not want it to', () => {
    const component = shallow(<MyComponent />);

    expect(component).not.toBeDefined(); // Does not pass, as component isn't undefined.
  });
});
Run Code Online (Sandbox Code Playgroud)

我希望第二个测试失败,因为该组件未渲染。有没有更好的方法来测试组件是否已渲染?

如果需要的话,很乐意提供更多信息。

谢谢!

Dav*_*per 2

因此,我与一些人进行了交谈,并决定也许我的处理方式是错误的。

确定它是否由父组件渲染可能是一个更好的主意,否则任何时候我想使用MyComponent,我都必须将此shouldRender道具传递给它。

MyComponent现在看起来像这样:

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;
Run Code Online (Sandbox Code Playgroud)

MyParentComponent的使用MyComponent看起来像这样:

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;
Run Code Online (Sandbox Code Playgroud)

不仅可以MyComponent提高可重用性,而且还消除了我想完全编写的测试的需要。感谢所有看过这篇文章的人。