Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock or stub process.argv

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.

like image 874
Dane Decker Avatar asked Oct 29 '25 14:10

Dane Decker


2 Answers

Since 29.x, Jest has a replaceProperty method.

jest.replaceProperty(process, 'argv', ['what', 'ever', 'you', 'like']);

The advantage is this mock can be reverted.

like image 126
Jean-Pierre Bécotte Avatar answered Oct 31 '25 03:10

Jean-Pierre Bécotte


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');
      }
    );
  }
);
like image 31
slideshowp2 Avatar answered Oct 31 '25 04:10

slideshowp2