【问题标题】:Test whether React component has rendered测试 React 组件是否已经渲染
【发布时间】:2016-11-30 14:56:12
【问题描述】:

我有一个 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;

我有一个看起来像这样的测试:

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.
  });
});

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

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

谢谢!

【问题讨论】:

  • 只是一个通知。根据从render 返回未定义的文档,这不是一个有效的选项。 "您也可以返回nullfalse 以表明您不希望渲染任何内容。"
  • 糟糕——我只是在现场手工编写了组件以获得更简化的版本——我现在将修复代码。谢谢!

标签: javascript reactjs jestjs enzyme


【解决方案1】:

所以我和一些人聊了聊,并决定我可能会以错误的方式处理这个问题。

确定它是否由父组件呈现可能是一个更好的主意,否则任何时候我想使用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;

而使用MyComponentMyParentComponent 看起来像这样:

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;

不仅让MyComponent 更加可重用,它还完全消除了我想要编写的测试的需要。感谢所有看过这篇文章的人。

【讨论】:

    【解决方案2】:

    我认为 Jest 的快照测试正是您所需要的。通过测试失败时的快照测试,您可以检查它是有意的还是无意的更改。查看他们的示例here

    【讨论】:

    • 这就是我的想法,但后来我意识到我不应该对此进行快照测试 - 有条件地在使用它的父/基础组件中渲染组件更有意义。这样子组件实际上是可重用的:)
    猜你喜欢
    • 2021-03-28
    • 2021-10-27
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2015-05-12
    • 2021-05-26
    相关资源
    最近更新 更多