mercredi 15 février 2017

Jest report error when using object spread feature in React component's props

A simple example for my issue, say I have a component Control.jsx as below:

class Control extends React.Components {
    render() {
        const props = {a: 1};
        return <AnotherComponent {...props} />;
    }
}
export default Control;

As you can see, it renders with 1 props using ES6 rest spread feature.

In AnotherComponent.jsx, the props are defined to be "isRequired" like this:

const AnotherComponent = ({a, b}) => {
    // some code here ...
};
AnotherComponent.propTypes = {
    a: React.PropTypes.number.isRequired
};

In my Jest test file,

import ... ;

describe('Test <Control />', () => {
    it('test', () => {
        const wrapper = mount(<Control />);
        // ...
    });
});

When I run the test, Jest will report "Warning: Failed prop type: The prop a is marked as required in AnotherComponent, but its value is undefined."

If I write prop a explictly as <AnotherComponent a={1} /> rather than using object spread, it works fine.

I use webpack2 and babel, does anyone know how to fix it? Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire