react-generate-props
Generate default props based on your React component's PropTypes
// => { name: 'name', number: 1 }
Installation
$ npm install --save-dev react-generate-props
Usage
Important: Initialize the library before importing any components into your test suite.
// test-helper.js
Define your component's propTypes.
const Counter = count <div>count</div>CounterpropTypes = count: PropTypesnumberisRequired
Pass the component to this library. It will generate reasonable props based on the defined types.
// => { count: 1 }
Use these default props to reduce boilerplate and prop type validation errors in your tests! 🎉
Example
A more in-depth example.
// component.jsx Component static propTypes = title: PropTypesstringisRequired followers: PropTypesnumberisRequired user: PropTypesisRequired { <div> <h1>thispropstitle</h1> <small>thispropsfollowers</small> thispropsuserloggedIn && <p>Hello thispropsusername</p> </div> }
// component-test.js import generateProps from 'react-generate-props'import Component from './component.jsx' const props = // => { title: 'title', followers: 1, user: { loggedIn: true, name: 'name' } } /* =><div> <h1>title</h1> <small>1</small> <p>Hello, name.</p></div>*/
API
The library takes two arguments.
schema
: An Object, Function, or Class containing a PropTypes definition, or a single PropType. All of the following are valid:
Plain Object
const Counter = count: PropTypesnumberisRequired
Plain Object with a propTypes
key
const Counter = propTypes: count: PropTypesnumberisRequired
Functional Component
const Counter = {/* ... */}CounterpropTypes = count: PropTypesnumberisRequired
React.Component
Class
Component static propTypes = count: PropTypesnumberisRequired
Single PropType
const Counter = PropTypesshape count: PropTypesnumberisRequired isRequired
In each of these cases, the effect would be the same
// => { count: 1 }
opts
: An Object which may contain the following:
required: true // default: true. When true, props marked as .isRequired will be generated. optional: false // default: false. When true, props *not* marked as .isRequired will be generated. generators: // Can be used to override this lib's default generators. // Each key is a prop type, each value is a function. // Each function receives the propName as its first argument, // followed by that prop type's argument, if it takes one. false propNamelength valuesvalueslength - 1
One More Example
const propTypes = name: PropTypesstringisRequired loggedIn: PropTypesbool userType: PropTypesisRequired // => { name: 'string', userType: 'admin' } // => { name: 'string', loggedIn: true, userType: 'admin' } // => { name: 'Alice', loggedIn: true, userType: 'user' }