简体   繁体   English

Reactjs:TypeError:无法读取undefined的属性'propTypes'

[英]Reactjs : TypeError: Cannot read property 'propTypes' of undefined

Please i am asked to write a unitTest for the following reactjs page. 请我为下面的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>
        );
    }
}

Following the tut Here I wrote my test below like 跟着啧啧在这里,我在下面写了我的测试

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

However, my test is throwing the error in the title above, i am suspecting my props on the Collapsible (ie title and children) are not assigning from the test . 但是,我的测试是在上面的标题中抛出错误,我怀疑我在Collapsible上的道具(即标题和孩子)没有从测试中分配。 Please how do i address this? 请问我该如何解决这个问题? Any help or guidance would highly be appreciated. 非常感谢任何帮助或指导。

Thanks for your time all. 谢谢你的时间。 It turns out i was importing the Collapsible in to the test file wrongly . 事实证明我错误地将Collapsible导入测试文件。 Below is how i was importing before 以下是我之前的导入方式

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

After changing to 改为之后

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

It seems to work. 它似乎工作。 I was importing Collapsible as an existing variable/object before. 我以前导入Collapsible作为现有的变量/对象。 After reading through docs and few tutorials i realised . 通过阅读文档和很少的教程,我意识到。

Per the docs , one way to define props with ES6 classes is as follows: 根据文档 ,使用ES6类定义道具的一种方法如下:

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,
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM