Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Method calls to Config helpers should return new objects to avoid unintended mutation #311

Merged
merged 2 commits into from
Nov 29, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions packages/metal-state/src/Config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict';

import {object} from 'metal';
import validators from './validators';

/**
Expand Down Expand Up @@ -233,11 +232,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);
});
});