【问题标题】:Jest warns of missing prop when it is there开玩笑时会警告缺少道具
【发布时间】:2016-12-23 02:55:07
【问题描述】:

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

警告:失败的 propType:所需的 prop 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
};

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    您的道具在您的测试文件中不可用——您需要以某种方式模拟这些道具。 这就是我编写 Jest 测试来测试组件的方式,这对我的团队来说效果很好(注意我们使用的是 Enzyme 库):

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

    这相当容易和干净。我们确实使用酶库来挂载组件,如果您想使用快照进行测试,那将是另一种方法来仔细检查您的组件是否被挂载并正确渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-11
      • 2019-04-23
      • 1970-01-01
      • 2020-04-26
      • 2021-06-20
      • 1970-01-01
      • 2018-02-15
      • 2018-09-18
      相关资源
      最近更新 更多