Jest警告说,当它在那里时缺少道具

时间:2016-06-08 03:29:25

标签: reactjs jestjs

如何使用此ReactJS组件在Jest中抑制此警告:

  

警告:propType失败:未指定必需的道具post   MyShowOnePost

我通过TestUtils.renderIntoDocument使用post道具调用React组件。

MyShowOnePost-test.js

describe('MyShowOnePost', () => {

    const instance = TestUtils.renderIntoDocument(
        <MyShowOnePost post={post} />
    );  

MyShowOnePost.js

export default class MyShowOnePost extends React.Component {
  render() {
    return (
      <div>
        One Post: {this.props.post.content}
      </div>
    );
  }
}

MyShowOnePost.propTypes = {
  post: React.PropTypes.object.isRequired
};

1 个答案:

答案 0 :(得分:2)

您的道具在您的测试文件中无法使用 - 您需要以某种方式嘲笑这些道具。 这就是我为测试组件编写Jest测试的方法,这对我的团队来说效果很好(注意我们使用的是酶库):

<强> MyShowOnePost-test.js

import { mount } from 'enzyme';
import MyShowOnePost from './MyShowOnePost'

describe('MyShowOnePost', () => {
  const fakeProps = { post: 'I'm a post!' };

  it('renders the post content', () => {
      const component = mount(<MyShowOnePost post={fakeProps.post} />);

      expect(component.containsMatchingElement(<div>One Post: {'I'm a post!'}</div>).toBeTruthy();
  });
});

这非常简单和干净。我们确实使用酶库来安装组件,如果你想使用快照进行测试,这将是另一种双重检查你的组件正在被正确安装和渲染的方法。