Description
🚀 Feature Proposal
It would be great to have interface to replace object's property value as part of Jest API.
Similar to Sinon's sandbox.replace(object, property, replacement);
Ref: https://sinonjs.org/releases/v14/sandbox/#sandboxreplaceobject-property-replacement
Motivation
Quite often there are parts of an object, we have to mock in tests. For example process.argv
, process.env
or some configuration settings coming out of whichever piece in codebase.
Usually we end up writing code like:
const oldProcessEnv = process.env;
beforeEach(() => process.env = {EXTRA_VAR: 'foo'});
afterEach(() => process.env = oldProcessEnv);
Problem is, that for trivial property replace, one needs to split it across multiple pieces, store old value and then properly return it. This might be cause for errors.
Example
// jest.mockProperty(<object>, <property>, <new value>);
jest.mockProperty(process, env, {EXTRA_VAR: 'foo'});
Property would be replaced back by calling jest.restoreAllMocks();
It is questionable, what should the mock return. If it should return something to intercept the calls and other stuff (probably yes, but I do not have opinion on that).
Pitch
Jest provides great and extensive way for mocking modules and methods. One piece, that is missing, is mocking individual properties for arbitrary object.
Of course, this is doable manually. However the biggest benefit of integrating this functionality to Jest API would be the integration into 'autoclean' feature that will simplify the boilerplate for individual property mocking, and thus making the code more error prone.