UNPKG

bdn-pocket

Version:

pocket tools for managing redux and redux-saga

148 lines (122 loc) 2.99 kB
import test from 'ava' import PropTypes, { Types } from '../src/prop_types' const { string, array, object } = Types test('PropTypes', t => { const c = PropTypes.propTypes({ a: string, b: string, }) t.notThrows( () => c({a: 'a', b: 'b'}), 'validate an object according to its prop types - only string' ) t.throws( () => c({a: 10, b: 'b'}), Error, 'validate an object according to its prop types - bad type' ) t.throws( () => c({a: 'a'}), Error, 'validate an object according to its prop types - missing prop' ) }) test('PropTypes shortcut', t => { const c = PropTypes.propTypes('a', 'b') t.notThrows( () => c({a: 'a', b: 'b'}), 'validate an object with string type and required value' ) t.notThrows( () => c({a: 10, b: 'b'}), 'validate an object with string type and required value - bad type' ) t.throws( () => c({a: 'a'}), Error, 'validate an object with string type and required value - missing prop' ) }) test('PropTypes with type definition', t => { const c = PropTypes.propTypes({ a: string, b: string({ required: false, allowNull: true }), }) t.notThrows( () => c({a: 'a', b: 'b'}), 'validate an object according to its prop types - only string' ) t.notThrows( () => c({ a: 'a' }), 'validate an object according to its prop types - allowed missing prop' ) t.notThrows( () => c({ a: 'a', b: null }), 'validate an object according to its prop types - allowed null prop' ) t.throws( () => c({ b: 'b'}), Error, 'validate an object according to its prop types - missing prop' ) }) test('PropTypes.hasPropTypes', t => { const c = PropTypes.propTypes({ a: string, b: string({ required: false, allowNull: true }), }) t.true( c.hasPropTypes(), 'return true if prop types defined' ) t.false( PropTypes.hasPropTypes(), 'return false if not proptypes defined' ) }) test('PropType array', t => { const c = PropTypes.propTypes({ a: array, b: array({ required: false, allowNull: true }), }) t.throws( () => c({ a: 1, b: ['hello']}), Error, 'validate required array prop - bad format' ) t.throws( () => c({ b: ['hello']}), Error, 'validate required array prop - missing prop' ) t.notThrows( () => c({ a: ['hello']}), 'validate required array prop - not required prop' ) }) test('PropType array vs object', t => { const cObj = PropTypes.propTypes({ a: object, }) const cArray = PropTypes.propTypes({ a: array, }) t.throws( () => cObj({ a: ['hello'] }), Error, 'validate object prop - array throws error' ) t.notThrows( () => cObj({ a: {} }), 'validate object - correct format' ) t.throws( () => cArray({ a: {} }), Error, 'validate array prop - object throws error' ) t.notThrows( () => cArray({ a: [] }), 'validate array prop - correct format' ) })