简体   繁体   中英

Reactjs : TypeError: Cannot read property 'propTypes' of undefined

Please i am asked to write a unitTest for the following reactjs page.

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 . 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 . 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. After reading through docs and few tutorials i realised .

Per the docs , one way to define props with ES6 classes is as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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