Search code examples
node.jsmockingsinonstub

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");

Solution

  • 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');
      });
    });