Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invariant Violation: ReactShallowRenderer render()

I am writing a unitTest script for the following reactjs file.

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 uniTest Example Here , i though i could do like below.

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

describe('Collapsible', ()=>{
    it('works', ()=>{
        let renderer = createRenderer();
        renderer.render(<details><summary>Title</summary>Text</details>);
        let actualElement = renderer.getRenderOutput();
        let expectedElement = (<details><summary></summary></details>);
        expect(actualElement).toEqual(expectedElement);                     
    });
});

However, when i run my test , i get the error

Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, not primitives (details). Instead of calling .render(el) and inspecting the rendered output, look at el.props directly instead.

Please where do i go wrong ? How do i write the unitTest for the script above. ?Any help would appreciated.

Update

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

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

When i run the code above, i get

Cannot read property 'propTypes' of undefined . I am guessing may be i have to pass the title and props.children considering they are properties in Collapsible. Please how do do that?

like image 628
Nuru Salihu Avatar asked Sep 25 '22 14:09

Nuru Salihu


1 Answers

You're not using your Collapsible element in your test, which is why you're getting that error.

The error message that you get you'll get using any primitive element, that is basically any HTML tag, you can only pass your own components to the Shallow renderer.

renderer.render(<Collapsible />);
like image 50
Henrik Andersson Avatar answered Dec 03 '22 03:12

Henrik Andersson