Skip to content

Commit

Permalink
fix: can't redefine process.env when node<4
Browse files Browse the repository at this point in the history
  • Loading branch information
popomore committed Jun 12, 2016
1 parent 0975eb4 commit 7de27b7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/method.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,14 @@ method.restore = function restoreMocks() {
// delete the mock key, use key on the prototype
delete m.obj[m.key];
} else {
// redefine the origin key instead of the mock key
Object.defineProperty(m.obj, m.key, m.descriptor);
// can't redefine process.env when node<4
// https://github.com/nodejs/node/pull/2999
if (m.obj === process.env) {
m.obj[m.key] = m.descriptor.value;
} else {
// redefine the origin key instead of the mock key
Object.defineProperty(m.obj, m.key, m.descriptor);
}
}
}
mocks = [];
Expand Down
5 changes: 5 additions & 0 deletions test/method-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ describe('Mock property', function () {
enableCache: true,
delay: 10
};
var home = process.env.HOME;

afterEach(muk.restore);

Expand All @@ -91,21 +92,25 @@ describe('Mock property', function () {
it('Property are new after mocked', function () {
muk(config, 'enableCache', false);
muk(config, 'delay', 0);
muk(process.env, 'HOME', '/mockhome');

assert.equal(config.enableCache, false, 'enableCache is false');
assert.equal(config.delay, 0, 'delay is 0');
assert.equal(process.env.HOME, '/mockhome', 'process.env.HOME is /mockhome');
});

it('Should have original properties after muk.restore()', function () {
muk(config, 'enableCache', false);
muk(config, 'enableCache', false);
muk(config, 'delay', 0);
muk(process.env, 'HOME', '/mockhome');
muk(config, 'notExistProp', 'value');
muk(process.env, 'notExistProp', 0);
muk.restore();

assert.equal(config.enableCache, true, 'enableCache is true');
assert.equal(config.delay, 10, 'delay is 10');
assert.equal(process.env.HOME, home, 'process.env.HOME is ' + home);
assert(!hasOwnProperty(config, 'notExistProp'), 'notExistProp is deleted');
assert(!hasOwnProperty(process.env, 'notExistProp'), 'notExistProp is deleted');
});
Expand Down

0 comments on commit 7de27b7

Please sign in to comment.