'How to Mock or Stub Process.argv

How do I mock or stub process.argv value so it can return a specific argument?

I tried using sandbox like this:

beforeEach(() => {
  sandbox.stub(process.argv.slice(2)[0], 'C:\\home\\project\\assignment').value('--local')
});

test("it replace value of node argument", () => {
    assert(process.argv.slice(2)[0], '--local')
});
    
afterEach(() =>{
    sandbox.restore()
})

But I keep getting an error that says trying to stub property *'C:\home\project\assignment' * of undefined



Solution 1:[1]

You can modify the process.argv by programming. see Modify node process environment or arguments runtime

const assert = require('assert');

describe('71476237', () => {
  let originalArgv;
  beforeEach(() => {
    originalArgv = process.argv;
  });

  afterEach(() => {
    process.argv = originalArgv;
  });

  it('it replace value of node argument', () => {
    process.argv = process.argv.concat(['node', 'C:\\home\\project\\assignment', '--local']);
    assert(process.argv.slice(2)[0], '--local');
  });
});

Test result:

  71476237
    ? it replace value of node argument


  1 passing (3ms)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 slideshowp2