Skip to content

Commit fd68111

Browse files
committed
Merge pull request #85 from TechnologyAdvice/feature/unhandled-props-util
add getUnhandledProps util
2 parents 15fae87 + a1516db commit fd68111

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

src/utils/getUnhandledProps.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import _ from 'lodash';
2+
3+
/**
4+
* Returns an object consisting of props not defined in propTypes nor defaultProps.
5+
* @param {*} instance The `this` keyword in a React Component class.
6+
* @returns {{}} A shallow copy of the prop object
7+
*/
8+
const getUnhandledProps = instance => {
9+
return _.omit(instance.props, (val, key) => {
10+
const inPropTypes = _.has(instance.constructor.propTypes, key);
11+
const inDefaultProps = _.has(instance.constructor.defaultProps, key);
12+
return inPropTypes || inDefaultProps;
13+
});
14+
};
15+
16+
export default getUnhandledProps;
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import _ from 'lodash';
2+
import getUnhandledProps from 'src/utils/getUnhandledProps';
3+
4+
// Helper class that takes in props and merges defaultProps
5+
class TestClass {
6+
constructor(props) {
7+
this.props = _.assign({}, this.constructor.defaultProps, props);
8+
this.unhandledProps = getUnhandledProps(this);
9+
}
10+
}
11+
12+
describe.only('getUnhandledProps', () => {
13+
it('removes props defined in defaultProps', () => {
14+
TestClass.defaultProps = {imHandled: 'thanks'};
15+
new TestClass()
16+
.unhandledProps
17+
.should.not.have.any.keys(_.keys(TestClass.defaultProps));
18+
});
19+
it('removes props defined in propTypes', () => {
20+
TestClass.propTypes = {imHandled: 'thanks'};
21+
new TestClass()
22+
.unhandledProps
23+
.should.not.have.any.keys(_.keys(TestClass.defaultProps));
24+
});
25+
it('leave props not in defaultProps || propTypes in tact', () => {
26+
TestClass.defaultProps = {imHandled: 'thanks'};
27+
TestClass.propTypes = {alsoHandled: 'got it'};
28+
const props = {thisShould: 'still be here'};
29+
new TestClass(props)
30+
.unhandledProps
31+
.should.eql(props);
32+
});
33+
});

0 commit comments

Comments
 (0)