【问题标题】:Reactjs : TypeError: Cannot read property 'propTypes' of undefinedReactjs:TypeError:无法读取未定义的属性“propTypes”
【发布时间】:2016-01-27 01:41:59
【问题描述】:

请我为以下 reactjs 页面编写 unitTest。

export default class Collapsible extends React.Component {
    static propTypes = {
        title: React.PropTypes.string,
        children: React.PropTypes.any,
    };

    render() {
        const { title } = this.props;
        return (
            <details>
                <summary>{title}</summary>
                {this.props.children}
            </details>
        );
    }
}

按照 tut Here 我在下面写了我的测试

describe('Collapsible', ()=>{
    it('works', ()=>{
        let renderer = createRenderer();
        renderer.render(<Collapsible title="MyTitle"><span>HEllo</span></Collapsible>);
        let actualElement = renderer.getRenderOutput();
        let expectedElement = (<details><summary>title</summary>Details</details>);
        expect(actualElement).toEqual(expectedElement);                     
    });
});

但是,我的测试在上面的标题中抛出了错误,我怀疑我在 Collapsible 上的道具(即标题和子项)没有从测试中分配。请问我该如何解决这个问题?任何帮助或指导将不胜感激。

【问题讨论】:

    标签: javascript unit-testing reactjs


    【解决方案1】:

    感谢您的宝贵时间。事实证明,我错误地将 Collapsible 导入到测试文件中。以下是我之前的导入方式

    import React from 'react';
    import expect from 'expect';
    import {createRenderer} from 'react-addons-test-utils';
    import { Collapsible }  from '../Collapsible.js';
    

    改成后

    import React from 'react';
    import expect from 'expect';
    import {createRenderer} from 'react-addons-test-utils';
    import Collapsible  from '../Collapsible';
    

    它似乎工作。我之前将 Collapsible 作为现有变量/对象导入。在阅读了文档和一些教程后,我意识到。

    【讨论】:

    • 在我的情况下,情况正好相反——我添加了 redux 的 connect() 方法并以不同的名称导出。忘记在测试中更改它。
    【解决方案2】:

    根据the docs,用 ES6 类定义 props 的一种方法如下:

    export default class Collapsible extends React.Component {
        render() {
            const { title } = this.props;
            return (
                <details>
                    <summary>{title}</summary>
                    {this.props.children}
                </details>
            );
        }
    }
    
    Collapsible.propTypes = {
        title: React.PropTypes.string,
        children: React.PropTypes.any,
    };
    

    【讨论】:

    • 感谢您的回复。我们使用该组件并且工作正常。我在实现上面的 unitTest 时遇到了这个问题。我怀疑错误在于我在上面的 uniTest 文件中传递道具的方式。但是,我不确定在哪里以及如何解决这个问题。
    猜你喜欢
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多