javascript - 测试 React 组件是否已经渲染

标签 javascript reactjs jestjs enzyme

我有一个 React 组件,我正在尝试使用 Enzyme/Jest 对其进行测试。我试图弄清楚最合适的测试是什么以确保组件已呈现。

我的组件有一个 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.
  });
});

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

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

谢谢!

最佳答案

所以我和一些人聊天后决定,也许我的做法是错误的。

确定这是否由父组件呈现可能是一个更好的主意,否则任何时候我想使用 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 更可重用,它还消除了我想要完全编写的测试的需要。感谢所有看过这篇文章的人。

关于javascript - 测试 React 组件是否已经渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40869042/

相关文章:

javascript - Next.js 中 babelification 后的对象相等问题

javascript - 图表 JS 集成

javascript - VueJs计算方法错误: Cannot read property 'words' of undefined"?

javascript - 如何在移动设备上显示图片的实际宽度?

javascript - 从滚动位置更改覆盖不透明度

node.js - NodeJS : How do I unit test an Async function that depends on other Async calls

reactjs - Gatsby 和 GraphQL - 从查询的文件中呈现下载链接

javascript - enzyme - Mount 无法通过 id 找到元素

javascript - 如何使用 javascript jest 监视导出的独立函数?

javascript - 如何使用 Jest 和 toThrow 断言异步方法抛出错误