How do I mock or stub process.argv so that it can return a specific argument?
I tried using Sinon.js like this:
beforeEach(
() => {
sandbox.stub(
process.argv.slice(2)[0], 'C:\\home\\project\\assignment'
).value('--local');
}
);
afterEach(
() => {
sandbox.restore();
}
);
test(
'it replace value of node argument',
() => {
assert(process.argv.slice(2)[0], '--local');
}
);
But I keep getting an error that says trying to stub property 'C:\\home\\project\\assignment' of undefined.
Since 29.x, Jest has a replaceProperty method.
jest.replaceProperty(process, 'argv', ['what', 'ever', 'you', 'like']);
The advantage is this mock can be reverted.
You can rebind process.argv (cf. Modify node process environment or arguments runtime):
import assert from 'node:assert/strict';
import test from 'node:test';
test.describe(
() => {
const originalArgv = process.argv;
test.afterEach(
() => {
process.argv = originalArgv;
}
);
test.test(
() => {
process.argv = process.argv.slice(0, 1).concat(['--local']);
assert.equal(process.argv[1], '--local');
}
);
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With