Skip to content

Commit

Permalink
Adds options to throw error if state property is required
Browse files Browse the repository at this point in the history
  • Loading branch information
eduardolundgren committed Mar 2, 2017
1 parent 4db965c commit f29654f
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 3 deletions.
9 changes: 6 additions & 3 deletions packages/metal-state/src/State.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
}
Expand Down
58 changes: 58 additions & 0 deletions packages/metal-state/test/State.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down

0 comments on commit f29654f

Please sign in to comment.