Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Props not validated when stateless component is called as a function #107

Closed
presence1 opened this issue Aug 31, 2017 · 4 comments
Closed

Comments

@presence1
Copy link

If I have a stateless functional component such as this:

const SlideView = ({text}) => {   
...
 return (
        <div className="example-slide-view">
             {text}            
        </div>
    );
};

SlideView.propTypes = {
    text: PropTypes.string.isRequired
};
...

If I test it like this:

context('SlideView...', () => {
            context('when called without a "text" prop', () => {
                shallow(<SlideView text={undefined} />);
                it('should throw a missing prop error', () => {
                    testUtils.expectMissingPropError('text', 'SlideView');
                });
            });
        });

The test passes.

However, if instead I test the SlideView like this:

context('SlideView...', () => {
            context('when called without a "text" prop', () => {
               SlideView({text: undefined});
               it('should throw a missing prop error', () => {
                    testUtils.expectMissingPropError('text', 'SlideView');
                });
            });
        });

No prop-types error is logged to the console, so the test fails.

I didn't expect this behaviour. I think it would be useful if the props were validated in this case.

@ljharb
Copy link
Collaborator

ljharb commented Aug 31, 2017

That's not possible due to the nature of JavaScript. Calling functions doesn't care about the nature of static properties.

Calling an SFC as a function is just incorrect.

@presence1
Copy link
Author

OK, so I will call checkPropTypes instead:
PropTypes.checkPropTypes(SlideView.propTypes, slideViewProps, 'prop', 'SlideView');

Thanks.

@uniphil
Copy link

uniphil commented Sep 5, 2017

Hey @ONE-BIG-MOB1, if you're running checkPropTypes in tests, be aware that you can get false negatives, since prop-types won't log any error it has already seen.

Here is a bit of discussion, an open PR with one solution, and a hopefully helpful package (I'm the author) made specifically for testing with prop-types.

Happy testing!

@presence1
Copy link
Author

@uniphil this is a very helpful comment. I was indeed stubbing console.error to check for prop-types errors. I will definitely give your package a try instead. Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants