存根/模拟process.platform sinon

我正在使用process.platform并希望存根string值来伪造不同的操作系统。

(这个对象是生成在我的范围之外,我需要testing它可以采取不同的值)

是否有可能残留/伪造这个值?

我已经尝试了以下没有任何运气:

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

我得到错误TypeError: Attempted to wrap string property platform as function

同样的事情发生,如果我尝试使用这样的模拟:

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

你不需要Sinon来完成你所需要的。 尽pipeprocess.platform进程不可writable ,但是可以configurable 。 所以,您可以暂时重新定义它,只需在完成testing后将其恢复。

以下是我将如何做到这一点:

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