Automatico
Automatico

Reputation: 12926

Stub/mock process.platform sinon

I am working with process.platform and want to stub that string value to fake different OSes.

(this object is generated out of my reach, and I need to test against different values it can take on)

Is it possible to stub/fake this value?

I have tried the following without any luck:

stub = sinon.stub(process, "platform").returns("something")

I get the error TypeError: Attempted to wrap string property platform as function

The same thing happens if I try to use a mock like this:

mock = sinon.mock(process);
mock.expects("platform").returns("something");

Upvotes: 7

Views: 2878

Answers (2)

Ron Wang
Ron Wang

Reputation: 119

sinon's stub supports a "value" function to set the new value for a stub now:

sinon.stub(process, 'platform').value('ANOTHER_OS');
...
sinon.restore() // when you finish the mocking

For details please check from https://sinonjs.org/releases/latest/stubs/

Upvotes: 3

JME
JME

Reputation: 3642

You don't need Sinon to accomplish what you need. Although the process.platform process is not writable, it is configurable. So, you can temporarily redefine it and simply restore it when you're done testing.

Here's how I would do it:

var assert = require('assert');

describe('changing process.platform', function() {
  before(function() {
    // save original process.platform
    this.originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform');

    // redefine process.platform
    Object.defineProperty(process, 'platform', {
      value: 'any-platform'
    });
  });

  after(function() {
    // restore original process.platfork
    Object.defineProperty(process, 'platform', this.originalPlatform);
  });

  it('should have any-platform', function() {
    assert.equal(process.platform, 'any-platform');
  });
});

Upvotes: 12

Related Questions