diff --git a/packages/metal-state/src/State.js b/packages/metal-state/src/State.js index 45b17e87..c7c6774e 100644 --- a/packages/metal-state/src/State.js +++ b/packages/metal-state/src/State.js @@ -97,9 +97,12 @@ class State extends EventEmitter { this.get(name) : this.initialValues_[name]; if (!isDefAndNotNull(value)) { - console.error( - `The property called "${name}" is required but didn't receive a value.` - ); + let errorMessage = `The property called "${name}" is required but didn't receive a value.`; + if (this.getThrowValidationError()) { + throw new Error(errorMessage); + } else { + console.error(errorMessage); + } } } } diff --git a/packages/metal-state/test/State.js b/packages/metal-state/test/State.js index be40f659..d73737a5 100644 --- a/packages/metal-state/test/State.js +++ b/packages/metal-state/test/State.js @@ -583,6 +583,64 @@ describe('State', function() { state.key = undefined; assert.strictEqual(2, console.error.callCount); }); + + it('should throw error if required property gets no initial value via configState and throwValidationError is enabled', function() { + var state = new State({ + key2: 'initialValue' + }); + state.setThrowValidationError(true); + + assert.doesNotThrow(() => { + state.configState({ + key1: {} + }); + }); + + assert.doesNotThrow(() => { + state.configState( + { + key2: { + required: true + } + } + ); + }); + + assert.throws(() => { + state.configState({ + key3: { + required: true + } + }); + }); + }); + + it('should log error if required property is set to null or undefined and throwValidationError is enabled', function() { + var state = new State({ + key: 'initialValue' + }); + state.setThrowValidationError(true); + + assert.doesNotThrow(() => { + state.configState({ + key: { + required: true + } + }); + }); + + assert.doesNotThrow(() => { + state.key = 'value'; + }); + + assert.throws(() => { + state.key = null; + }); + + assert.throws(() => { + state.key = undefined; + }); + }); }); it('should emit event when a state key\'s value changes', function() {