Skip to content

Commit

Permalink
Method calls to Config helpers should return new objects to avoid uni…
Browse files Browse the repository at this point in the history
…ntended mutation. Fixes metal#310
  • Loading branch information
Robert-Frampton authored and Robert-Frampton committed Nov 22, 2017
1 parent 46a2d06 commit 15adcf6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
11 changes: 6 additions & 5 deletions packages/metal-state/src/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,11 +233,12 @@ function destructShapeOfConfigs(shape) {
*/
function mergeConfig(context, config) {
let obj = context;
if (obj === Config) {
obj = Object.create(Config);
obj.config = {};
}
object.mixin(obj.config, config);
const objConfig = obj.config || {};

obj = Object.create(Config);
obj.config = {};

Object.assign(obj.config, objConfig, config);
return obj;
}

Expand Down
22 changes: 22 additions & 0 deletions packages/metal-state/test/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -284,4 +284,26 @@ describe('Config', function() {
assert.ok(config.config.validator(10));
assert.ok(config.config.validator('test') instanceof Error);
});

it('should not mutate config object with subsequent method calls', function() {
const config = Config.string();
const config2 = config.oneOf(['1', '2']);
const config3 = config2.required();

assert.notDeepEqual(config, config2);
assert.notDeepEqual(config, config3);
assert.notDeepEqual(config2, config3);

assert.ok(config.config.validator(1) instanceof Error);
assert.ok(config2.config.validator(1) instanceof Error);
assert.ok(config3.config.validator(1) instanceof Error);

assert.ok(config.config.validator('1'));
assert.ok(config2.config.validator('1'));
assert.ok(config3.config.validator('3') instanceof Error);

assert.isTrue(config3.config.required);
assert.isUndefined(config.config.required);
assert.isUndefined(config2.config.required);
});
});

0 comments on commit 15adcf6

Please sign in to comment.