Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (i.e title and children) are not assigning from the test . Please how do i address this? Any help or guidance would highly be appreciated.

like image 420
Nuru Salihu Avatar asked Jan 27 '16 01:01

Nuru Salihu


2 Answers

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 .

like image 188
Nuru Salihu Avatar answered Oct 02 '22 22:10

Nuru Salihu


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,
};
like image 29
Kevin Qi Avatar answered Oct 02 '22 20:10

Kevin Qi